<commit_before>'use strict';

angular.module('documents')
	.directive('tmplDocumentsUploadGeneral', directiveDocumentsUploadGeneral)
	.directive('tmplDocumentsLink', directiveDocumentsLink)
	.directive('tmplDocumentsUploadClassifyMem', directiveDocumentsUploadClassifyMem)
	.directive('tmplDocumentsUploadClassify', directiveDocumentsUploadClassify)
	.directive('tmplDocumentsList', directiveDocumentsList)
	.directive('tmplDocumentsBrowser', directiveDocumentsBrowser)
	.directive('tmplDocumentsApprovals', directiveDocumentsApprovals)
	.directive('modalDocumentUploadReview', directiveModalDocumentUploadReview)
	.directive('modalDocumentLink', directiveModalDocumentLink)
	.directive('modalPdfViewer', directiveModalPdfViewer)
	.directive('modalDocumentUploadClassifyMem', directiveModalDocumentUploadClassifyMem)
	.directive('modalDocumentUploadClassify', directiveModalDocumentUploadClassify);

	// .directive('modalDocumentViewer', directiveModalDocumentViewer)
	// .directive('modalDocumentBuckets', directiveModalDocumentBuckets);

// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Upload General
//
// -----------------------------------------------------------------------------------
function directiveDocumentsUploadGeneral() {

	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-upload-general.html',
		scope: {
			project: '=',
			artifact: '=',
			type: '@',
			hideUploadButton: '=',
			parentId: '=',
			docLocationCode: '='
		},
		controller: 'controllerDocumentUploadGlobal',
		controllerAs: 'docUpload'
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Link General
//
// -----------------------------------------------------------------------------------
function directiveDocumentsLink() {
	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-link.html',
		scope: {
			project: '=',
			artifact: '=',
			type: '@',  //project or comment
			current: '=',
			parentId: '=',
			docLocationCode: '=',
			documentsControl: '='
		},
		controller: 'controllerDocumentLinkGlobal',
		controllerAs: 'docLink'
	};

	return directive;
}

directiveModalPdfViewer.$inject = ['$modal'];
/* @ngInject */
function directiveModalPdfViewer($modal) {
	var directive = {
		restrict:'A',
		scope: {
			pdfobject: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocView = $modal.open({
					resolve: {
						pdfobject: function() { return scope.pdfobject; }
					},
					templateUrl: 'modules/documents/client/views/partials/pdf-viewer.html',
					controller: 'controllerModalPdfViewer',
					controllerAs: 'pdfViewer',
					size: 'lg',
					windowClass: 'document-viewer-modal'
				});
				modalDocView.result.then(function () {}, function () {});
			});
		}
	};
	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Upload General for
//
// -----------------------------------------------------------------------------------
function directiveDocumentsUploadClassify() {
	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-upload-classify.html',
		scope: {
			project: '=',
			artifact: '=',
			type: '@',  //project or comment
			hideUploadButton: '=',
			parentId: '=',
			docLocationCode: '=',
			documentsControl: '='
		},
		controller: 'controllerDocumentUploadGlobal',
		controllerAs: 'docUpload'
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Upload General for MEM
//
// -----------------------------------------------------------------------------------
function directiveDocumentsUploadClassifyMem() {
	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-upload-classify-mem.html',
		scope: {
			project: '=',
			artifact: '=',
			type: '@',  //project or comment
			hideUploadButton: '=',
			parentId: '=',
			docLocationCode: '='
		},
		controller: 'controllerDocumentUploadGlobal',
		controllerAs: 'docUpload'
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document List Table
//
// -----------------------------------------------------------------------------------
function directiveDocumentsList() {

	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-list.html',
		controller: 'controllerDocumentList',
		controllerAs: 'docList',
		scope: {
			documents: '=',
			project: '=',
			documentsObjs: '=',
			allowEdit: '@'
		}
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Browser
//
// -----------------------------------------------------------------------------------
directiveDocumentsBrowser.$inject = ['$modal'];
/* @ngInject */
function directiveDocumentsBrowser() {

	var directive = {
		restrict: 'E',
		replace: true,
		templateUrl: 'modules/documents/client/views/partials/document-browser.html',
		controller: 'controllerDocumentBrowser',
		controllerAs: 'docBrowser',
		scope: {
			project: '=',
			artifact: '=',
			allowLink: '@',
			approvals: '@',
			docLocationCode: '@',
			documentsControl: '='
		}
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Documents for Approval
//
// -----------------------------------------------------------------------------------
directiveDocumentsApprovals.$inject = ['$modal'];
/* @ngInject */
function directiveDocumentsApprovals() {

	var directive = {
		restrict: 'E',
		replace: true,
		templateUrl: 'modules/documents/client/views/partials/document-approvals.html',
		controller: 'controllerDocumentBrowser',
		controllerAs: 'docBrowser',
		scope: {
			project: '=',
			approvals: '@'
		}
	};

	return directive;
}

// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Modal document viewer
//
// -----------------------------------------------------------------------------------
directiveModalDocumentViewer.$inject = ['$modal'];
/* @ngInject */
function directiveModalDocumentViewer($modal) {
	var directive = {
		restrict:'A',
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocView = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal_document_viewer.html',
					controller: 'controllerModalDocumentViewer',
					controllerAs: 'md',
					size: 'lg'
				});
				modalDocView.result.then(function () {}, function () {});
			});
		}
	};
	return directive;
}
// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Link in a modal
//
// -----------------------------------------------------------------------------------
directiveModalDocumentLink.$inject = ['$modal', '$rootScope'];
/* @ngInject */
function directiveModalDocumentLink($modal, $rootScope) {
	var directive = {
		restrict:'A',
		scope: {
			project: '=',
			artifact: '=',
			current: '=',
			docLocationCode: '=',
			documentsControl: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				// console.log("Docs Current: ",attrs.current);
				var modalDocLink = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal-document-link.html',
					controller: 'controllerModalDocumentLink',
					controllerAs: 'docLinkModal',
					size: 'lg',
					resolve: {
						rProject: function() { return scope.project; },
						rArtifact: function() {
							return scope.artifact;
						},
						rCurrent: function() { return scope.current; },
						rDocLocationCode: function() {
							return scope.docLocationCode;
						},
						rDocumentsControl: function() {
							return scope.documentsControl;
						}
					}
				});
				modalDocLink.result.then(function (data) {
					// console.log("New set of Documents:",data);
					$rootScope.$broadcast('refreshDocumentList');
				}, function () {});
			});
		}
	};
	return directive;
}   // -----------------------------------------------------------------------------------
//
// DIRECTIVE: Upload in a modal
//
// -----------------------------------------------------------------------------------
directiveModalDocumentUploadClassify.$inject = ['$modal', '$rootScope'];
/* @ngInject */
function directiveModalDocumentUploadClassify($modal, $rootScope) {
	var directive = {
		restrict:'A',
		scope: {
			project: '=',
			artifact: '=',
			docLocationCode: '=',
			documentsControl: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocUpload = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal-document-upload-classify.html',
					controller: 'controllerModalDocumentUploadClassify',
					controllerAs: 'docUploadModal',
					size: 'lg',
					resolve: {
						rProject: function() { return scope.project; },
						rArtifact: function() {
							return scope.artifact;
						},
						rDocLocationCode: function() {
							return scope.docLocationCode;
						},
						rDocumentsControl: function() {
							return scope.documentsControl;
						}
					}
				});
				modalDocUpload.result.then(function (data) {
					$rootScope.$broadcast('refreshDocumentList');
				}, function () {});
			});
		}
	};
	return directive;
}
// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Upload in a modal
//
// -----------------------------------------------------------------------------------
directiveModalDocumentUploadClassifyMem.$inject = ['$modal', '$rootScope'];
/* @ngInject */
function directiveModalDocumentUploadClassifyMem($modal, $rootScope) {
	var directive = {
		restrict:'A',
		scope: {
			project: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocUpload = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal-document-upload-classify-mem.html',
					controller: 'controllerModalDocumentUploadClassify',
					controllerAs: 'docUploadModal',
					size: 'lg',
					resolve: {
						rProject: function() { return scope.project; }
					}
				});
				modalDocUpload.result.then(function (data) {
					$rootScope.$broadcast('refreshDocumentList');
				}, function () {});
			});
		}
	};
	return directive;
}
// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Upload in a modal
//
// -----------------------------------------------------------------------------------
directiveModalDocumentUploadReview.$inject = ['$modal', '$rootScope'];
/* @ngInject */
function directiveModalDocumentUploadReview($modal, $rootScope) {
	var directive = {
		restrict:'A',
		scope: {
			project: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocUpload = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal-document-upload-review.html',
					controller: 'controllerModalDocumentUploadReview',
					controllerAs: 'docUploadModalReview',
					size: 'lg',
					resolve: {
						rProject: function() { return scope.project; }
					}
				});
				modalDocUpload.result.then(function (data) {
					$rootScope.$broadcast('refreshDocumentList');
				}, function () {});
			});
		}
	};
	return directive;
}
// // -----------------------------------------------------------------------------------
// //
// // DIRECTIVE: Modal document Tags
// //
// // -----------------------------------------------------------------------------------
// directiveModalDocumentBuckets.$inject = ['$modal'];
// /* @ngInject */
// function directiveModalDocumentBuckets($modal) {
//     var directive = {
//         restrict:'A',
//         scope: {
//             doc: '=',
//             project: '='
//         },
//         link : function(scope, element, attrs) {
//             element.on('click', function() {
//                 var modalDocBuckets = $modal.open({
//                     animation: true,
//                     templateUrl: 'modules/documents/client/views/partials/modal_document_buckets.html',
//                     controller: 'controllerModalDocumentBuckets',
//                     controllerAs: 'docBuckets',
//                     size: 'md',
//                     resolve: {
//                         rDoc: function() { return scope.doc; },
//                         rProject: function() { return scope.project; }
//                     }
//                 });
//                 modalDocBuckets.result.then(function (data) {
//                     scope.doc = data;
//                 }, function () {});
//             });
//         }
//     };
//     return directive;
// }
<commit_msg>Bringing over PDF Viewer fix, removing LG view.<commit_after>'use strict';

angular.module('documents')
	.directive('tmplDocumentsUploadGeneral', directiveDocumentsUploadGeneral)
	.directive('tmplDocumentsLink', directiveDocumentsLink)
	.directive('tmplDocumentsUploadClassifyMem', directiveDocumentsUploadClassifyMem)
	.directive('tmplDocumentsUploadClassify', directiveDocumentsUploadClassify)
	.directive('tmplDocumentsList', directiveDocumentsList)
	.directive('tmplDocumentsBrowser', directiveDocumentsBrowser)
	.directive('tmplDocumentsApprovals', directiveDocumentsApprovals)
	.directive('modalDocumentUploadReview', directiveModalDocumentUploadReview)
	.directive('modalDocumentLink', directiveModalDocumentLink)
	.directive('modalPdfViewer', directiveModalPdfViewer)
	.directive('modalDocumentUploadClassifyMem', directiveModalDocumentUploadClassifyMem)
	.directive('modalDocumentUploadClassify', directiveModalDocumentUploadClassify);

	// .directive('modalDocumentViewer', directiveModalDocumentViewer)
	// .directive('modalDocumentBuckets', directiveModalDocumentBuckets);

// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Upload General
//
// -----------------------------------------------------------------------------------
function directiveDocumentsUploadGeneral() {

	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-upload-general.html',
		scope: {
			project: '=',
			artifact: '=',
			type: '@',
			hideUploadButton: '=',
			parentId: '=',
			docLocationCode: '='
		},
		controller: 'controllerDocumentUploadGlobal',
		controllerAs: 'docUpload'
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Link General
//
// -----------------------------------------------------------------------------------
function directiveDocumentsLink() {
	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-link.html',
		scope: {
			project: '=',
			artifact: '=',
			type: '@',  //project or comment
			current: '=',
			parentId: '=',
			docLocationCode: '=',
			documentsControl: '='
		},
		controller: 'controllerDocumentLinkGlobal',
		controllerAs: 'docLink'
	};

	return directive;
}

directiveModalPdfViewer.$inject = ['$modal'];
/* @ngInject */
function directiveModalPdfViewer($modal) {
	var directive = {
		restrict:'A',
		scope: {
			pdfobject: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocView = $modal.open({
					resolve: {
						pdfobject: function() { return scope.pdfobject; }
					},
					templateUrl: 'modules/documents/client/views/partials/pdf-viewer.html',
					controller: 'controllerModalPdfViewer',
					controllerAs: 'pdfViewer',
					windowClass: 'document-viewer-modal'
				});
				modalDocView.result.then(function () {}, function () {});
			});
		}
	};
	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Upload General for
//
// -----------------------------------------------------------------------------------
function directiveDocumentsUploadClassify() {
	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-upload-classify.html',
		scope: {
			project: '=',
			artifact: '=',
			type: '@',  //project or comment
			hideUploadButton: '=',
			parentId: '=',
			docLocationCode: '=',
			documentsControl: '='
		},
		controller: 'controllerDocumentUploadGlobal',
		controllerAs: 'docUpload'
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Upload General for MEM
//
// -----------------------------------------------------------------------------------
function directiveDocumentsUploadClassifyMem() {
	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-upload-classify-mem.html',
		scope: {
			project: '=',
			artifact: '=',
			type: '@',  //project or comment
			hideUploadButton: '=',
			parentId: '=',
			docLocationCode: '='
		},
		controller: 'controllerDocumentUploadGlobal',
		controllerAs: 'docUpload'
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document List Table
//
// -----------------------------------------------------------------------------------
function directiveDocumentsList() {

	var directive = {
		restrict: 'E',
		templateUrl: 'modules/documents/client/views/partials/document-list.html',
		controller: 'controllerDocumentList',
		controllerAs: 'docList',
		scope: {
			documents: '=',
			project: '=',
			documentsObjs: '=',
			allowEdit: '@'
		}
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Document Browser
//
// -----------------------------------------------------------------------------------
directiveDocumentsBrowser.$inject = ['$modal'];
/* @ngInject */
function directiveDocumentsBrowser() {

	var directive = {
		restrict: 'E',
		replace: true,
		templateUrl: 'modules/documents/client/views/partials/document-browser.html',
		controller: 'controllerDocumentBrowser',
		controllerAs: 'docBrowser',
		scope: {
			project: '=',
			artifact: '=',
			allowLink: '@',
			approvals: '@',
			docLocationCode: '@',
			documentsControl: '='
		}
	};

	return directive;
}
// -----------------------------------------------------------------------------------
//
// CONTROLLER: Documents for Approval
//
// -----------------------------------------------------------------------------------
directiveDocumentsApprovals.$inject = ['$modal'];
/* @ngInject */
function directiveDocumentsApprovals() {

	var directive = {
		restrict: 'E',
		replace: true,
		templateUrl: 'modules/documents/client/views/partials/document-approvals.html',
		controller: 'controllerDocumentBrowser',
		controllerAs: 'docBrowser',
		scope: {
			project: '=',
			approvals: '@'
		}
	};

	return directive;
}

// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Modal document viewer
//
// -----------------------------------------------------------------------------------
directiveModalDocumentViewer.$inject = ['$modal'];
/* @ngInject */
function directiveModalDocumentViewer($modal) {
	var directive = {
		restrict:'A',
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocView = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal_document_viewer.html',
					controller: 'controllerModalDocumentViewer',
					controllerAs: 'md',
					size: 'lg'
				});
				modalDocView.result.then(function () {}, function () {});
			});
		}
	};
	return directive;
}
// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Link in a modal
//
// -----------------------------------------------------------------------------------
directiveModalDocumentLink.$inject = ['$modal', '$rootScope'];
/* @ngInject */
function directiveModalDocumentLink($modal, $rootScope) {
	var directive = {
		restrict:'A',
		scope: {
			project: '=',
			artifact: '=',
			current: '=',
			docLocationCode: '=',
			documentsControl: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				// console.log("Docs Current: ",attrs.current);
				var modalDocLink = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal-document-link.html',
					controller: 'controllerModalDocumentLink',
					controllerAs: 'docLinkModal',
					size: 'lg',
					resolve: {
						rProject: function() { return scope.project; },
						rArtifact: function() {
							return scope.artifact;
						},
						rCurrent: function() { return scope.current; },
						rDocLocationCode: function() {
							return scope.docLocationCode;
						},
						rDocumentsControl: function() {
							return scope.documentsControl;
						}
					}
				});
				modalDocLink.result.then(function (data) {
					// console.log("New set of Documents:",data);
					$rootScope.$broadcast('refreshDocumentList');
				}, function () {});
			});
		}
	};
	return directive;
}   // -----------------------------------------------------------------------------------
//
// DIRECTIVE: Upload in a modal
//
// -----------------------------------------------------------------------------------
directiveModalDocumentUploadClassify.$inject = ['$modal', '$rootScope'];
/* @ngInject */
function directiveModalDocumentUploadClassify($modal, $rootScope) {
	var directive = {
		restrict:'A',
		scope: {
			project: '=',
			artifact: '=',
			docLocationCode: '=',
			documentsControl: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocUpload = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal-document-upload-classify.html',
					controller: 'controllerModalDocumentUploadClassify',
					controllerAs: 'docUploadModal',
					size: 'lg',
					resolve: {
						rProject: function() { return scope.project; },
						rArtifact: function() {
							return scope.artifact;
						},
						rDocLocationCode: function() {
							return scope.docLocationCode;
						},
						rDocumentsControl: function() {
							return scope.documentsControl;
						}
					}
				});
				modalDocUpload.result.then(function (data) {
					$rootScope.$broadcast('refreshDocumentList');
				}, function () {});
			});
		}
	};
	return directive;
}
// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Upload in a modal
//
// -----------------------------------------------------------------------------------
directiveModalDocumentUploadClassifyMem.$inject = ['$modal', '$rootScope'];
/* @ngInject */
function directiveModalDocumentUploadClassifyMem($modal, $rootScope) {
	var directive = {
		restrict:'A',
		scope: {
			project: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocUpload = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal-document-upload-classify-mem.html',
					controller: 'controllerModalDocumentUploadClassify',
					controllerAs: 'docUploadModal',
					size: 'lg',
					resolve: {
						rProject: function() { return scope.project; }
					}
				});
				modalDocUpload.result.then(function (data) {
					$rootScope.$broadcast('refreshDocumentList');
				}, function () {});
			});
		}
	};
	return directive;
}
// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Upload in a modal
//
// -----------------------------------------------------------------------------------
directiveModalDocumentUploadReview.$inject = ['$modal', '$rootScope'];
/* @ngInject */
function directiveModalDocumentUploadReview($modal, $rootScope) {
	var directive = {
		restrict:'A',
		scope: {
			project: '='
		},
		link : function(scope, element, attrs) {
			element.on('click', function() {
				var modalDocUpload = $modal.open({
					animation: true,
					templateUrl: 'modules/documents/client/views/partials/modal-document-upload-review.html',
					controller: 'controllerModalDocumentUploadReview',
					controllerAs: 'docUploadModalReview',
					size: 'lg',
					resolve: {
						rProject: function() { return scope.project; }
					}
				});
				modalDocUpload.result.then(function (data) {
					$rootScope.$broadcast('refreshDocumentList');
				}, function () {});
			});
		}
	};
	return directive;
}
// // -----------------------------------------------------------------------------------
// //
// // DIRECTIVE: Modal document Tags
// //
// // -----------------------------------------------------------------------------------
// directiveModalDocumentBuckets.$inject = ['$modal'];
// /* @ngInject */
// function directiveModalDocumentBuckets($modal) {
//     var directive = {
//         restrict:'A',
//         scope: {
//             doc: '=',
//             project: '='
//         },
//         link : function(scope, element, attrs) {
//             element.on('click', function() {
//                 var modalDocBuckets = $modal.open({
//                     animation: true,
//                     templateUrl: 'modules/documents/client/views/partials/modal_document_buckets.html',
//                     controller: 'controllerModalDocumentBuckets',
//                     controllerAs: 'docBuckets',
//                     size: 'md',
//                     resolve: {
//                         rDoc: function() { return scope.doc; },
//                         rProject: function() { return scope.project; }
//                     }
//                 });
//                 modalDocBuckets.result.then(function (data) {
//                     scope.doc = data;
//                 }, function () {});
//             });
//         }
//     };
//     return directive;
// }
<|endoftext|>


<commit_before>import {Repetir, Si, Sino, Hasta, Procedimiento} from 'pilas-engine-bloques/actividades/bloques';
import {IrAbajo, IrIzquierda, IrDerecha, IrArriba} from 'pilas-engine-bloques/actividades/direccionesCuadricula';
import {EncenderLuz,TocandoLuz} from 'pilas-engine-bloques/actividades/bloquesTito';
import {Numero,OpComparacion,OpAritmetica,Texto} from 'pilas-engine-bloques/actividades/expresiones';

export default {
  nombre: 'Tito cuadrado',
  id: 'TitoCuadrado',
  enunciado: 'Tito debe encender todas las luces del cuadrado. Tené en cuenta que las casillas de la esquina nunca se prenden y que el tamaño del cuadrado no varía de una ejecución a la otra.',

  escena: TitoCuadrado,  // jshint ignore:line
  puedeComentar: false,
  puedeDesactivar: false,
  puedeDuplicar: false,

  bloques: [Procedimiento, Repetir, Si, Sino, Hasta, TocandoLuz, EncenderLuz,
    IrAbajo,IrArriba,IrIzquierda,IrDerecha,Numero,OpComparacion,OpAritmetica,Texto],
};
<commit_msg>Edité el enunciado<commit_after>import {Repetir, Si, Sino, Hasta, Procedimiento} from 'pilas-engine-bloques/actividades/bloques';
import {IrAbajo, IrIzquierda, IrDerecha, IrArriba} from 'pilas-engine-bloques/actividades/direccionesCuadricula';
import {EncenderLuz,TocandoLuz} from 'pilas-engine-bloques/actividades/bloquesTito';
import {Numero,OpComparacion,OpAritmetica,Texto} from 'pilas-engine-bloques/actividades/expresiones';

export default {
  nombre: 'Tito cuadrado',
  id: 'TitoCuadrado',
  enunciado: 'Tito debe encender todas las luces del cuadrado, en cada ejecución distribuidas de una manera diferente. Tené en cuenta que las casillas de la esquina nunca se prenden y que el tamaño del cuadrado no varía de una ejecución a la otra.',

  escena: TitoCuadrado,  // jshint ignore:line
  puedeComentar: false,
  puedeDesactivar: false,
  puedeDuplicar: false,

  bloques: [Procedimiento, Repetir, Si, Sino, Hasta, TocandoLuz, EncenderLuz,
    IrAbajo,IrArriba,IrIzquierda,IrDerecha,Numero,OpComparacion,OpAritmetica,Texto],
};
<|endoftext|>


<commit_before>(function(Dropdown, $) {
  Dropdown.setup = function(link) {
    var menuToWrap = Dropdown.findMenu(link);
    menuToWrap.wrap("

");

    $(link).on('click', function(event){
      event.preventDefault();
      $(this).toggleClass('selected');
      Dropdown.findMenu(this).closest('.dropdown_wrapper').slideToggle();
    });
  }

  Dropdown.findMenu = function(link) {
    var match = $(link).attr('href').match(/\#(.+)$/)[1];
    return $('#' + match);
  }

}(window.Dropdown = window.Dropdown || {}, jQuery));

$(function () {
  $('a.dropdown').each(function(){
    Dropdown.setup(this);
  });
});
<commit_msg>Fixing child page dropdowns.<commit_after>(function(Dropdown, $) {
  Dropdown.setup = function(link) {
    var menuToWrap = Dropdown.findMenu(link);
    if ($(menuToWrap).parent("div").length == 0) {
      menuToWrap.wrap("

");

      $(link).on('click', function (event) {
        event.preventDefault();
        $(this).toggleClass('selected');
        Dropdown.findMenu(this).closest('.dropdown_wrapper').slideToggle();
      })
    };
  }

  Dropdown.findMenu = function(link) {
    var match = $(link).attr('href').match(/\#(.+)$/)[1];
    return $('#' + match);
  }

}(window.Dropdown = window.Dropdown || {}, jQuery));

$(function () {
  $('a.dropdown').each(function(){
    Dropdown.setup(this);
  });
});
<|endoftext|>


<commit_before>var object = {
  x: {
    j() {
      return this.j;
    }
  },
  f() {
    return this.f;
  },
  'g'() {},
  "h"() {},
  42() {},
  null() {},
  true() {},
  false() {},
  function() {},
  var() {},
  'class'() {}  // NodeJS incorrectly flags {class: ...} as an error.
};

// ----------------------------------------------------------------------------

assert.deepEqual([
  '42',
  'x',
  'f',
  'g',
  'h',
  'null',
  'true',
  'false',
  'function',
  'var',
  'class'
], Object.keys(object));

function assertMethod(object, name) {
  assert.isTrue(object.hasOwnProperty(name));
  var descriptor = Object.getOwnPropertyDescriptor(object, name);
  assert.equal('object', typeof descriptor);
  assert.isTrue(descriptor.enumerable);
  assert.equal('function', typeof object[name]);
  // IE does not have a name property on functions.
  assert.isTrue(object[name].name === '' || object[name].name === undefined);
}

assertMethod(object, 'f');
assertMethod(object, 'g');
assertMethod(object, 'h');
assertMethod(object, '42');
assertMethod(object, 'null');
assertMethod(object, 'true');
assertMethod(object, 'false');
assertMethod(object, 'function');
assertMethod(object, 'var');
assertMethod(object, 'class');

assert.equal(object.f, object.f());

// Test the nested object.
assert.deepEqual(['j'], Object.keys(object.x));
assertMethod(object.x, 'j');

// Test name binding.
var m = 42;
class C {
  m() {
    return m;
  }
}
assert.equal(42, new C().m())
<commit_msg>Fix PropertyMethodAssignment test (#2134)<commit_after>var object = {
  x: {
    j() {
      return this.j;
    }
  },
  f() {
    return this.f;
  },
  'g'() {},
  "h"() {},
  42() {},
  null() {},
  true() {},
  false() {},
  function() {},
  var() {},
  'class'() {}  // NodeJS incorrectly flags {class: ...} as an error.
};

// ----------------------------------------------------------------------------

assert.deepEqual([
  '42',
  'x',
  'f',
  'g',
  'h',
  'null',
  'true',
  'false',
  'function',
  'var',
  'class'
], Object.keys(object));

function assertMethod(object, name) {
  assert.isTrue(object.hasOwnProperty(name));
  var descriptor = Object.getOwnPropertyDescriptor(object, name);
  assert.equal('object', typeof descriptor);
  assert.isTrue(descriptor.enumerable);
  assert.equal('function', typeof object[name]);
  // IE does not have a name property on functions.
  // ES6 compliant engines will set the name of {x: function() {}} to x
  var fn = object[name].name;
  assert.include(['', undefined, name], fn);
}

assertMethod(object, 'f');
assertMethod(object, 'g');
assertMethod(object, 'h');
assertMethod(object, '42');
assertMethod(object, 'null');
assertMethod(object, 'true');
assertMethod(object, 'false');
assertMethod(object, 'function');
assertMethod(object, 'var');
assertMethod(object, 'class');

assert.equal(object.f, object.f());

// Test the nested object.
assert.deepEqual(['j'], Object.keys(object.x));
assertMethod(object.x, 'j');

// Test name binding.
var m = 42;
class C {
  m() {
    return m;
  }
}
assert.equal(42, new C().m())
<|endoftext|>


<commit_before>goog.provide('ol.renderer.canvas.VectorLayer2');

goog.require('goog.dom');
goog.require('goog.vec.Mat4');
goog.require('ol.extent');
goog.require('ol.layer.Vector');
goog.require('ol.renderer.canvas.Layer');
goog.require('ol.renderer.canvas.Vector');

/**
 * @constructor
 * @extends {ol.renderer.canvas.Layer}
 * @param {ol.renderer.Map} mapRenderer Map renderer.
 * @param {ol.layer.Vector} layer Vector layer.
 */
ol.renderer.canvas.VectorLayer2 = function(mapRenderer, layer) {

  goog.base(this, mapRenderer, layer);

  /**
   * @private
   * @type {!goog.vec.Mat4.Number}
   */
  this.coordsTransform_ = goog.vec.Mat4.createNumber();

  /**
   * @private
   * @type {!goog.vec.Mat4.Number}
   */
  this.transform_ = goog.vec.Mat4.createNumber();

  /**
   * @private
   * @type {number}
   */
  this.renderedResolution_ = 0;

  /**
   * @private
   * @type {ol.Extent}
   */
  this.renderedExtent_ = null;

  /**
   * @private
   * @type {function()}
   */
  this.requestMapRenderFrame_ = goog.bind(function() {
    mapRenderer.getMap().requestRenderFrame();
  }, this);

};
goog.inherits(ol.renderer.canvas.VectorLayer2, ol.renderer.canvas.Layer);

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.composeFrame =
    function(frameState, layerState, context) {

  var extent = frameState.extent;
  var view2DState = frameState.view2DState;
  var viewCenter = view2DState.center;
  var viewProjection = view2DState.projection;
  var viewResolution = view2DState.resolution;
  var viewRotation = view2DState.rotation;

  var vectorLayer = this.getVectorLayer();

  var features = vectorLayer.getFeaturesObjectForExtent(extent,
      viewProjection, this.requestMapRenderFrame_);

  if (goog.isNull(features)) {
    return;
  }

  this.renderedResolution_ = viewResolution;
  this.renderedExtent_ = extent;

  var canvasWidth = frameState.size[0];
  var canvasHeight = frameState.size[1];

  var halfWidth = canvasWidth;
  var halfHeight = canvasHeight;

  // transform for map coords to sketch canvas pixel coords
  var coordsTransform = this.coordsTransform_;
  var origin = ol.extent.getTopLeft(extent);
  goog.vec.Mat4.makeIdentity(coordsTransform);
  goog.vec.Mat4.translate(coordsTransform,
      halfWidth, halfHeight, 0);
  goog.vec.Mat4.scale(coordsTransform,
      1 / viewResolution, -1 / viewResolution, 1);
  goog.vec.Mat4.translate(coordsTransform,
      -(origin[0] + halfWidth * viewResolution),
      -(origin[1] - halfHeight * viewResolution),
      0);
  var renderer = new ol.renderer.canvas.Vector(context, coordsTransform,
      this.requestMapRenderFrame_);

  var groups = vectorLayer.groupFeaturesBySymbolizerLiteral(features,
      viewResolution);

  var i, ii, group, deferred;

  ii = groups.length;
  for (i = 0; i < ii; ++i) {
    group = groups[i];
    deferred = renderer.renderFeatures(group[0], group[1], group[2]);
    if (deferred) {
      break;
    }
  }

  var transform = this.transform_;
  goog.vec.Mat4.makeIdentity(transform);
  goog.vec.Mat4.translate(transform,
      frameState.size[0] / 2,
      frameState.size[1] / 2,
      0);
  goog.vec.Mat4.scale(transform,
      this.renderedResolution_ / viewResolution,
      this.renderedResolution_ / viewResolution,
      1);
  goog.vec.Mat4.rotateZ(transform, viewRotation);
  goog.vec.Mat4.translate(transform,
      (this.renderedExtent_[0] - viewCenter[0]) / this.renderedResolution_,
      (viewCenter[1] - this.renderedExtent_[3]) / this.renderedResolution_,
      0);

};

/**
 * @return {ol.layer.Vector} Vector layer.
 */
ol.renderer.canvas.VectorLayer2.prototype.getVectorLayer = function() {
  return /** @type {ol.layer.Vector} */ (this.getLayer());
};

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.getTransform = function() {
  return this.transform_;
};

/**
 * @param {ol.layer.VectorEvent} event Vector layer event.
 * @private
 */
ol.renderer.canvas.VectorLayer2.prototype.handleLayerChange_ = function(event) {
  this.requestMapRenderFrame_();
};

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.prepareFrame = goog.nullFunction;
<commit_msg>Correct transform and remove unused variables<commit_after>goog.provide('ol.renderer.canvas.VectorLayer2');

goog.require('goog.dom');
goog.require('goog.vec.Mat4');
goog.require('ol.layer.Vector');
goog.require('ol.renderer.canvas.Layer');
goog.require('ol.renderer.canvas.Vector');

/**
 * @constructor
 * @extends {ol.renderer.canvas.Layer}
 * @param {ol.renderer.Map} mapRenderer Map renderer.
 * @param {ol.layer.Vector} layer Vector layer.
 */
ol.renderer.canvas.VectorLayer2 = function(mapRenderer, layer) {

  goog.base(this, mapRenderer, layer);

  /**
   * @private
   * @type {!goog.vec.Mat4.Number}
   */
  this.transform_ = goog.vec.Mat4.createNumber();

  /**
   * @private
   * @type {function()}
   */
  this.requestMapRenderFrame_ = goog.bind(function() {
    mapRenderer.getMap().requestRenderFrame();
  }, this);

};
goog.inherits(ol.renderer.canvas.VectorLayer2, ol.renderer.canvas.Layer);

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.composeFrame =
    function(frameState, layerState, context) {

  var extent = frameState.extent;
  var view2DState = frameState.view2DState;
  var viewCenter = view2DState.center;
  var viewProjection = view2DState.projection;
  var viewResolution = view2DState.resolution;
  var viewRotation = view2DState.rotation;

  var vectorLayer = this.getVectorLayer();

  var features = vectorLayer.getFeaturesObjectForExtent(extent,
      viewProjection, this.requestMapRenderFrame_);

  if (goog.isNull(features)) {
    return;
  }

  var transform = this.transform_;
  goog.vec.Mat4.makeIdentity(transform);
  goog.vec.Mat4.translate(transform,
      frameState.size[0] / 2,
      frameState.size[1] / 2,
      0);
  goog.vec.Mat4.scale(transform,
      1 / viewResolution,
      -1 / viewResolution,
      1);
  goog.vec.Mat4.rotateZ(transform, -viewRotation);
  goog.vec.Mat4.translate(transform,
      -viewCenter[0],
      -viewCenter[1],
      0);
  var renderer = new ol.renderer.canvas.Vector(context, transform,
      this.requestMapRenderFrame_);

  var groups = vectorLayer.groupFeaturesBySymbolizerLiteral(features,
      viewResolution);

  var i, ii, group, deferred;

  ii = groups.length;
  for (i = 0; i < ii; ++i) {
    group = groups[i];
    deferred = renderer.renderFeatures(group[0], group[1], group[2]);
    if (deferred) {
      break;
    }
  }

};

/**
 * @return {ol.layer.Vector} Vector layer.
 */
ol.renderer.canvas.VectorLayer2.prototype.getVectorLayer = function() {
  return /** @type {ol.layer.Vector} */ (this.getLayer());
};

/**
 * @param {ol.layer.VectorEvent} event Vector layer event.
 * @private
 */
ol.renderer.canvas.VectorLayer2.prototype.handleLayerChange_ = function(event) {
  this.requestMapRenderFrame_();
};

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.prepareFrame = goog.nullFunction;
<|endoftext|>


<commit_before>/*****************************************************************************************************************************************************
*                                                                                *
*                                                 1 +-------------------+ 1                                                                          *
*                                     +-------------+     Company       +---------------+           1 +---------------+ 1        * +----------------+*
*                                     |             |                   |               |      +------+   Constructor +------------+   Department   |*
*                                     |             +-------------------+               |      |      |               |            |                |*
*                                     |                                                 |      |      +---------------+            +----------------+*
*                                     |                                                 |      |                                                     *
*                                     |                                                 |      |                                                     *
*                                   * |                                                 | *  * |                                                     *
* +---------------+          +--------+-------+                                 +-------+------+--+                  +-----------------+             *
* |    Address    |1        1|    Driver      |                                 |     Taxi        | 1              * |   BreakDown     |             *
* |               +----------+                |                                 |                 +------------------+                 |             *
* +---------------+          +--------+-------+                                 +-------+---------+                  +-----------------+             *
*                                   1 |                                                 | 1                                                          *
*                                     |                                                 |                                                            *
*                                     |                                                 |                                                            *
*                                     |                                                 |                                                            *
*                                     |             +--------------------+              |                                                            *
*                                     |           * |        Ride        | *            |                                                            *
*                                     +-------------+                    +--------------+                                                            *
*                                                   +--------------------+                                                                           *
*                                                                                *
*                                                                                *
*                                                                                *
*                                                                                *
*                                                                                *
*  1. A company may have many taxis and many drivers (OnToMany).                                                                                *
*  2. A driver may drive many taxis and a taxi may be driven by many drivers (ManyToMany through Ride).                                              *
*  3. A taxi may pass through many breakdowns (OneToMany) and may have only one constructor (ManyToOne).                                             *
*  4. A constructor may have many departments (OneToMany).                                                                                *
*  5. A driver may have only one address (OneToOne).                                                                                *
*                                                                                *
******************************************************************************************************************************************************/

var Waterline = require('../../../../lib/waterline'),
        assert = require('assert'),
        async = require('async');

var waterline = new Waterline();
var migrate = 'drop';

describe('Populate Deep', function () {
  var companyModel, taxiModel, driverModel, rideModel, constructorModel, addressModel, breakDownModel, departmentModel;
  before(function (done) {
    var Company = Waterline.Collection.extend({
      identity: 'Company',
      connection: 'pop_deep',
      tableName: 'company_table',
      migrate: migrate,
      attributes: {
        "companyId": {
          "type": "integer",
          "primaryKey": true
        },
        "companyName": {
          "type": "string"
        },
        "taxis": {
          "collection": "Taxi",
          "via": "company"
        },
        "drivers": {
          "collection": "Driver",
          "via": "company"
        }
      }
    });

    var Driver = Waterline.Collection.extend({
      identity: 'Driver',
      connection: 'pop_deep',
      tableName: 'driver_table',
      migrate: migrate,
      attributes: {
        "driverId": {
          "type": "integer",
          "primaryKey": true
        },
        "driverName": {
          "type": "string"
        },
        "taxis": {
          "collection": "Taxi",
          "via": "driver",
          "through": "ride"
        },
        "address": {
          "model": "Address"
        },
        "company": {
          "model": "Company"
        }
      }
    });

    var Taxi = Waterline.Collection.extend({
      identity: 'Taxi',
      connection: 'pop_deep',
      tableName: 'taxi_table',
      migrate: migrate,
      attributes: {
        "taxiId": {
          "type": "integer",
          "primaryKey": true
        },
        "taxiMatricule": {
          "type": "string"
        },
        "drivers": {
          "collection": "Driver",
          "via": "taxi",
          "through": "ride"
        },
        "company": {
          "model": "Company"
        },
        "constructor": {
          "model": "Constructor"
        },
        "breakdowns": {
          "collection": "BreakDown",
          "via": "taxi"
        }
      }
    });

    var Ride = Waterline.Collection.extend({
      identity: 'Ride',
      connection: 'pop_deep',
      tableName: 'ride_table',
      migrate: migrate,
      attributes: {
        "taxi": {
          "model": "Taxi"
        },
        "driver": {
          "model": "Driver"
        }
      }
    });

    var Address = Waterline.Collection.extend({
      identity: 'Address',
      connection: 'pop_deep',
      tableName: 'address_table',
      migrate: migrate,
      attributes: {
        "addressId": {
          "type": "integer",
          "primaryKey": true
        },
        "addressCity": {
          "type": "string"
        }
      }
    });

    var Constructor = Waterline.Collection.extend({
      identity: 'Constructor',
      connection: 'pop_deep',
      tableName: 'constructor_table',
      migrate: migrate,
      attributes: {
        "constructorId": {
          "type": "integer",
          "primaryKey": true
        },
        "constructorName": {
          "type": "string"
        },
        "taxis": {
          "collection": "Taxi",
          "via": "constructor"
        },
        departments: {
          "collection": "Department",
          "via": "constructor"
        }
      }
    });

    var BreakDown = Waterline.Collection.extend({
      identity: 'breakdown',
      connection: 'pop_deep',
      tableName: 'breakdown_table',
      migrate: migrate,
      attributes: {
        "breakDownId": {
          "type": "integer",
          "primaryKey": true
        },
        "breakDownLevel": {
          "type": "integer"
        },
        "taxi": {
          "model": "Taxi"
        }
      }
    });

    var Department = Waterline.Collection.extend({
      identity: 'Department',
      connection: 'pop_deep',
      tableName: 'department_table',
      migrate: migrate,
      attributes: {
        "departmentId": {
          "type": "integer",
          "primaryKey": true
        },
        "departmentLabel": {
          "type": "string"
        },
        "constructor": {
          "model": "Constructor"
        }
      }
    });

    var companies = [
      {companyId : 1, companyName: 'company 1'},
      {companyId : 2, companyName: 'company 2'}
    ];
    var drivers = [
      {driverId : 1, driverName: 'driver 1', company: 1, address: 1},
      {driverId : 2, driverName: 'driver 2', company: 2, address: 2},
      {driverId : 3, driverName: 'driver 3', company: 1, address: 3}
    ];
    var taxis = [
      {taxiId : 1, taxiMatricule: 'taxi_1', company: 1, constructor: 1},
      {taxiId : 2, taxiMatricule: 'taxi_2', company: 2, constructor: 2},
      {taxiId : 3, taxiMatricule: 'taxi_3', company: 2, constructor: 2}
    ];
    var rides = [
      {taxi: 1, driver: 1},
      {taxi: 1, driver: 2},
      {taxi: 2, driver: 2},
      {taxi: 3, driver: 3},
      {taxi: 2, driver: 3}
    ];

    var addresses = [
      {addressId : 1, addressCity: 'city 1'},
      {addressId : 2, addressCity: 'city 2'},
      {addressId : 3, addressCity: 'city 3'}
    ];
    var constructors = [
      {constructorId : 1, constructorName: 'constructor 1'},
      {constructorId : 2, constructorName: 'constructor 2'}
    ];

    var breakDowns = [
      {breakDownId: 1, breakDownLevel: '5', taxi: 3},
      {breakDownId: 2, breakDownLevel: '7', taxi: 2},
      {breakDownId: 3, breakDownLevel: '1', taxi: 3},
      {breakDownId: 4, breakDownLevel: '8', taxi: 3}
    ];

    var departments = [
      {departmentId : 1, departmentLabel : 'dep 1', constructor : 1},
      {departmentId : 2, departmentLabel : 'dep 2', constructor : 1},
      {departmentId : 3, departmentLabel : 'dep 3', constructor : 2}
    ];

    waterline.loadCollection(Company);
    waterline.loadCollection(Driver);
    waterline.loadCollection(Taxi);
    waterline.loadCollection(Address);
    waterline.loadCollection(Ride);
    waterline.loadCollection(Constructor);
    waterline.loadCollection(BreakDown);
    waterline.loadCollection(Department);

    var connections = {'pop_deep': {
        adapter: 'adapter'}
    };

    waterline.initialize({adapters: {adapter: require('sails-memory')}, connections: connections}, function (err, colls) {
      if (err)
        return done(err);

      companyModel = colls.collections.company;
      taxiModel = colls.collections.taxi;
      driverModel = colls.collections.driver;
      addressModel = colls.collections.address;
      rideModel = colls.collections.ride;
      constructorModel = colls.collections.constructor;
      breakDownModel = colls.collections.breakdown;
      departmentModel = colls.collections.department;

      async.series([
        function (callback) {
          companyModel.createEach(companies, callback);
        },
        function (callback) {
          taxiModel.createEach(taxis, callback);
        },
        function (callback) {
          driverModel.createEach(drivers, callback);
        },
        function (callback) {
          rideModel.createEach(rides, callback);
        }, function (callback) {
          addressModel.createEach(addresses, callback);
        },
        function (callback) {
          constructorModel.createEach(constructors, callback);
        },
        function (callback) {
          breakDownModel.createEach(breakDowns, callback);
        },
        function (callback) {
          departmentModel.createEach(departments, callback);
        }
      ], function (err) {
        if (err)
          return done(err);
        done();
      });
    });

  });
  /* no hypothesis can be made on the find result order, so adding sorts in each test */
  it('should deeply populate a branch', function (done) {
    companyModel.find().sort('companyId asc')
            .populate('drivers.taxis',{sort : {taxiId : 1}})
            .populate('drivers.taxis.constructor.departments',{sort : {departmentId : 1}})
            .exec(function (err, companies) {
              if (err)
                return done(err);
              // Root Level
              assert(companies.length === 2 && companies[1].companyName === 'company 2', 'Root criteria not applied.');
              //Level 1
              assert(companies[1].drivers.length === 1, 'Could not populate first level oneToMany collection.');
              assert(companies[1].drivers[0].driverName === 'driver 2', 'First level not correctly populated.');

              //Level 2
              assert(companies[1].drivers[0].taxis.length === 2, 'Could not populate second level manyToMany collection.');
              var taxi1 = companies[1].drivers[0].taxis[0];
              var taxi2 = companies[1].drivers[0].taxis[1];
              assert(taxi1.taxiMatricule === 'taxi_1' && taxi2.taxiMatricule === 'taxi_2', 'Second level not correctly populated.');
              //Level 3
              assert(taxi1.constructor, 'Could not populate third level manyToOne model.');
              var constructor1 = taxi1.constructor;
              var constructor2 = taxi2.constructor;
              assert(constructor1.constructorName === 'constructor 1' && constructor2.constructorName === 'constructor 2',
                      'Third level not correctly populated.');
              //Level 4
              assert(constructor1.departments.length === 2,'Could not populate forth level oneToMany collection.');
              assert(constructor1.departments[0].departmentLabel === 'dep 1' && constructor1.departments[1].departmentLabel === 'dep 2',
                      'Forth level not correctly populated.');
              assert(constructor2.departments.length === 1,'Could not populate forth level oneToMany collection.');
              assert(constructor2.departments[0].departmentLabel === 'dep 3',
                      'Forth level not correctly populated.');
              done();
            });
  });

  it('should populate multiple branchs', function (done) {
    companyModel.find().where({companyName: 'company 2'})
            .populate('drivers.taxis',{sort : {taxiId : 1}})
            .populate('drivers.taxis.constructor')
            .populate('drivers.address')
            .exec(function (err, companies) {
              if (err)
                return done(err);
              // Root Level
              assert(companies.length === 1 && companies[0].companyName === 'company 2', 'Root criteria not applied.');
              //Level 1
              assert(companies[0].drivers.length === 1, 'Could not populate first level oneToMany collection.');
              assert(companies[0].drivers[0].driverName === 'driver 2', 'First level not correctly populated.');
              //Level 2 A
              assert(companies[0].drivers[0].taxis.length === 2, 'Could not populate second level manyToMany collection.');
              var taxi1 = companies[0].drivers[0].taxis[0];
              var taxi2 = companies[0].drivers[0].taxis[1];
              assert(taxi1.taxiMatricule === 'taxi_1' && taxi2.taxiMatricule === 'taxi_2', 'Second level (A) not correctly populated.');
              //Level 2 B
              assert(companies[0].drivers[0].address.addressCity === 'city 2', 'Second level (B) criteria not populated.');
              done();
            });
  });

  it('should apply criteria to current populate path last alias', function (done) {
    companyModel.find().where({companyName: 'company 1'})
            .populate('drivers', {driverName: 'driver 3'})
            .populate('drivers.taxis', {taxiMatricule: 'taxi_3'})
            .populate('drivers.taxis.breakdowns', {where : {breakDownLevel: {'>': 2}}, sort : {breakDownLevel : 1}})
            .exec(function (err, companies) {
              if (err)
                return done(err);
              // Root Level
              assert(companies.length === 1 && companies[0].companyName === 'company 1', 'Root criteria not applied.');
              //Level 1
              assert(companies[0].drivers.length === 1, 'Could not populate first level oneToMany collection.');
              assert(companies[0].drivers[0].driverName === 'driver 3', 'First level criteria not applied.');
              //Level 2
              assert(companies[0].drivers[0].taxis.length === 1, 'Could not populate second level manyToMany collection.');
              var taxi = companies[0].drivers[0].taxis[0];
              assert(taxi.taxiMatricule === 'taxi_3', 'Second level criteria not applied.');
              //Level 3
              assert(taxi.breakdowns.length === 2, 'Could not populate third level oneToMany collection.');
              assert(taxi.breakdowns[0].breakDownLevel === 5 && taxi.breakdowns[1].breakDownLevel  === 8, 'Third level criteria not applied.');

              done();
            });
  });
});
<commit_msg>Stable.<commit_after>/*****************************************************************************************************************************************************
*                                                                                *
*                                                 1 +-------------------+ 1                                                                          *
*                                     +-------------+     Company       +---------------+           1 +---------------+ 1        * +----------------+*
*                                     |             |                   |               |      +------+   Constructor +------------+   Department   |*
*                                     |             +-------------------+               |      |      |               |            |                |*
*                                     |                                                 |      |      +---------------+            +----------------+*
*                                     |                                                 |      |                                                     *
*                                     |                                                 |      |                                                     *
*                                   * |                                                 | *  * |                                                     *
* +---------------+          +--------+-------+                                 +-------+------+--+                  +-----------------+             *
* |    Address    |1        1|    Driver      |                                 |     Taxi        | 1              * |   BreakDown     |             *
* |               +----------+                |                                 |                 +------------------+                 |             *
* +---------------+          +--------+-------+                                 +-------+---------+                  +-----------------+             *
*                                   1 |                                                 | 1                                                          *
*                                     |                                                 |                                                            *
*                                     |                                                 |                                                            *
*                                     |                                                 |                                                            *
*                                     |             +--------------------+              |                                                            *
*                                     |           * |        Ride        | *            |                                                            *
*                                     +-------------+                    +--------------+                                                            *
*                                                   +--------------------+                                                                           *
*                                                                                *
*                                                                                *
*                                                                                *
*                                                                                *
*                                                                                *
*  1. A company may have many taxis and many drivers (OnToMany).                                                                                *
*  2. A driver may drive many taxis and a taxi may be driven by many drivers (ManyToMany through Ride).                                              *
*  3. A taxi may pass through many breakdowns (OneToMany) and may have only one constructor (ManyToOne).                                             *
*  4. A constructor may have many departments (OneToMany).                                                                                *
*  5. A driver may have only one address (OneToOne).                                                                                *
*                                                                                *
******************************************************************************************************************************************************/

var Waterline = require('../../../../lib/waterline'),
        assert = require('assert'),
        async = require('async');

var waterline = new Waterline();
var migrate = 'drop';

describe('Populate Deep', function () {
  var companyModel, taxiModel, driverModel, rideModel, constructorModel, addressModel, breakDownModel, departmentModel;
  before(function (done) {
    var Company = Waterline.Collection.extend({
      identity: 'Company',
      connection: 'pop_deep',
      tableName: 'company_table',
      migrate: migrate,
      attributes: {
        "companyId": {
          "type": "integer",
          "primaryKey": true
        },
        "companyName": {
          "type": "string"
        },
        "taxis": {
          "collection": "Taxi",
          "via": "company"
        },
        "drivers": {
          "collection": "Driver",
          "via": "company"
        }
      }
    });

    var Driver = Waterline.Collection.extend({
      identity: 'Driver',
      connection: 'pop_deep',
      tableName: 'driver_table',
      migrate: migrate,
      attributes: {
        "driverId": {
          "type": "integer",
          "primaryKey": true
        },
        "driverName": {
          "type": "string"
        },
        "taxis": {
          "collection": "Taxi",
          "via": "driver",
          "through": "ride"
        },
        "address": {
          "model": "Address"
        },
        "company": {
          "model": "Company"
        }
      }
    });

    var Taxi = Waterline.Collection.extend({
      identity: 'Taxi',
      connection: 'pop_deep',
      tableName: 'taxi_table',
      migrate: migrate,
      attributes: {
        "taxiId": {
          "type": "integer",
          "primaryKey": true
        },
        "taxiMatricule": {
          "type": "string"
        },
        "drivers": {
          "collection": "Driver",
          "via": "taxi",
          "through": "ride"
        },
        "company": {
          "model": "Company"
        },
        "constructor": {
          "model": "Constructor"
        },
        "breakdowns": {
          "collection": "BreakDown",
          "via": "taxi"
        }
      }
    });

    var Ride = Waterline.Collection.extend({
      identity: 'Ride',
      connection: 'pop_deep',
      tableName: 'ride_table',
      migrate: migrate,
      attributes: {
        "taxi": {
          "model": "Taxi"
        },
        "driver": {
          "model": "Driver"
        }
      }
    });

    var Address = Waterline.Collection.extend({
      identity: 'Address',
      connection: 'pop_deep',
      tableName: 'address_table',
      migrate: migrate,
      attributes: {
        "addressId": {
          "type": "integer",
          "primaryKey": true
        },
        "addressCity": {
          "type": "string"
        }
      }
    });

    var Constructor = Waterline.Collection.extend({
      identity: 'Constructor',
      connection: 'pop_deep',
      tableName: 'constructor_table',
      migrate: migrate,
      attributes: {
        "constructorId": {
          "type": "integer",
          "primaryKey": true
        },
        "constructorName": {
          "type": "string"
        },
        "taxis": {
          "collection": "Taxi",
          "via": "constructor"
        },
        departments: {
          "collection": "Department",
          "via": "constructor"
        }
      }
    });

    var BreakDown = Waterline.Collection.extend({
      identity: 'breakdown',
      connection: 'pop_deep',
      tableName: 'breakdown_table',
      migrate: migrate,
      attributes: {
        "breakDownId": {
          "type": "integer",
          "primaryKey": true
        },
        "breakDownLevel": {
          "type": "integer"
        },
        "taxi": {
          "model": "Taxi"
        }
      }
    });

    var Department = Waterline.Collection.extend({
      identity: 'Department',
      connection: 'pop_deep',
      tableName: 'department_table',
      migrate: migrate,
      attributes: {
        "departmentId": {
          "type": "integer",
          "primaryKey": true
        },
        "departmentLabel": {
          "type": "string"
        },
        "constructor": {
          "model": "Constructor"
        }
      }
    });

    var companies = [
      {companyId : 1, companyName: 'company 1'},
      {companyId : 2, companyName: 'company 2'}
    ];
    var drivers = [
      {driverId : 1, driverName: 'driver 1', company: 1, address: 1},
      {driverId : 2, driverName: 'driver 2', company: 2, address: 2},
      {driverId : 3, driverName: 'driver 3', company: 1, address: 3}
    ];
    var taxis = [
      {taxiId : 1, taxiMatricule: 'taxi_1', company: 1, constructor: 1},
      {taxiId : 2, taxiMatricule: 'taxi_2', company: 2, constructor: 2},
      {taxiId : 3, taxiMatricule: 'taxi_3', company: 2, constructor: 2}
    ];
    var rides = [
      {taxi: 1, driver: 1},
      {taxi: 1, driver: 2},
      {taxi: 2, driver: 2},
      {taxi: 3, driver: 3},
      {taxi: 2, driver: 3}
    ];

    var addresses = [
      {addressId : 1, addressCity: 'city 1'},
      {addressId : 2, addressCity: 'city 2'},
      {addressId : 3, addressCity: 'city 3'}
    ];
    var constructors = [
      {constructorId : 1, constructorName: 'constructor 1'},
      {constructorId : 2, constructorName: 'constructor 2'}
    ];

    var breakDowns = [
      {breakDownId: 1, breakDownLevel: '5', taxi: 3},
      {breakDownId: 2, breakDownLevel: '7', taxi: 2},
      {breakDownId: 3, breakDownLevel: '1', taxi: 3},
      {breakDownId: 4, breakDownLevel: '8', taxi: 3}
    ];

    var departments = [
      {departmentId : 1, departmentLabel : 'dep 1', constructor : 1},
      {departmentId : 2, departmentLabel : 'dep 2', constructor : 1},
      {departmentId : 3, departmentLabel : 'dep 3', constructor : 2}
    ];

    waterline.loadCollection(Company);
    waterline.loadCollection(Driver);
    waterline.loadCollection(Taxi);
    waterline.loadCollection(Address);
    waterline.loadCollection(Ride);
    waterline.loadCollection(Constructor);
    waterline.loadCollection(BreakDown);
    waterline.loadCollection(Department);

    var connections = {'pop_deep': {
        adapter: 'adapter'}
    };

    waterline.initialize({adapters: {adapter: require('sails-memory')}, connections: connections}, function (err, colls) {
      if (err)
        return done(err);

      companyModel = colls.collections.company;
      taxiModel = colls.collections.taxi;
      driverModel = colls.collections.driver;
      addressModel = colls.collections.address;
      rideModel = colls.collections.ride;
      constructorModel = colls.collections.constructor;
      breakDownModel = colls.collections.breakdown;
      departmentModel = colls.collections.department;

      async.series([
        function (callback) {
          companyModel.createEach(companies, callback);
        },
        function (callback) {
          taxiModel.createEach(taxis, callback);
        },
        function (callback) {
          driverModel.createEach(drivers, callback);
        },
        function (callback) {
          rideModel.createEach(rides, callback);
        }, function (callback) {
          addressModel.createEach(addresses, callback);
        },
        function (callback) {
          constructorModel.createEach(constructors, callback);
        },
        function (callback) {
          breakDownModel.createEach(breakDowns, callback);
        },
        function (callback) {
          departmentModel.createEach(departments, callback);
        }
      ], function (err) {
        if (err)
          return done(err);
        done();
      });
    });

  });
  /* no hypothesis can be made on the find result order, so adding sorts in each test */
  it('should deeply populate a branch', function (done) {
    companyModel.find().sort('companyId asc')
            .populate('drivers.taxis',{sort : {taxiId : 1}})
            .populate('drivers.taxis.constructor.departments',{sort : {departmentId : 1}})
            .exec(function (err, companies) {
              if (err)
                return done(err);
              // Root Level
              assert(companies.length === 2 && companies[1].companyName === 'company 2', 'Root criteria not applied.');
              //Level 1
              assert(companies[1].drivers.length === 1, 'Could not populate first level oneToMany collection.');
              assert(companies[1].drivers[0].driverName === 'driver 2', 'First level not correctly populated.');

              //Level 2
              assert(companies[1].drivers[0].taxis.length === 2, 'Could not populate second level manyToMany collection.');
              var taxi1 = companies[1].drivers[0].taxis[0];
              var taxi2 = companies[1].drivers[0].taxis[1];
              assert(taxi1.taxiMatricule === 'taxi_1' && taxi2.taxiMatricule === 'taxi_2', 'Second level not correctly populated.');
              //Level 3
              assert(taxi1.constructor, 'Could not populate third level manyToOne model.');
              var constructor1 = taxi1.constructor;
              var constructor2 = taxi2.constructor;
              assert(constructor1.constructorName === 'constructor 1' && constructor2.constructorName === 'constructor 2',
                      'Third level not correctly populated.');
              //Level 4
              assert(constructor1.departments.length === 2,'Could not populate forth level oneToMany collection.');
              assert(constructor1.departments[0].departmentLabel === 'dep 1' && constructor1.departments[1].departmentLabel === 'dep 2',
                      'Forth level not correctly populated.');
              assert(constructor2.departments.length === 1,'Could not populate forth level oneToMany collection.');
              assert(constructor2.departments[0].departmentLabel === 'dep 3',
                      'Forth level not correctly populated.');
              done();
            });
  });

  it('should populate multiple branchs', function (done) {
    companyModel.find().where({companyName: 'company 2'})
            .populate('drivers.taxis',{sort : {taxiId : 1}})
            .populate('drivers.address')
            .exec(function (err, companies) {
              if (err)
                return done(err);
              // Root Level
              assert(companies.length === 1 && companies[0].companyName === 'company 2', 'Root criteria not applied.');
              //Level 1
              assert(companies[0].drivers.length === 1, 'Could not populate first level oneToMany collection.');
              assert(companies[0].drivers[0].driverName === 'driver 2', 'First level not correctly populated.');
              //Level 2 A
              assert(companies[0].drivers[0].taxis.length === 2, 'Could not populate second level manyToMany collection.');
              var taxi1 = companies[0].drivers[0].taxis[0];
              var taxi2 = companies[0].drivers[0].taxis[1];
              assert(taxi1.taxiMatricule === 'taxi_1' && taxi2.taxiMatricule === 'taxi_2', 'Second level (A) not correctly populated.');
              //Level 2 B
              assert(companies[0].drivers[0].address.addressCity === 'city 2', 'Second level (B) criteria not populated.');
              done();
            });
  });

  it('should apply criteria to current populate path last alias', function (done) {
    companyModel.find().where({companyName: 'company 1'})
            .populate('drivers', {driverName: 'driver 3'})
            .populate('drivers.taxis', {taxiMatricule: 'taxi_3'})
            .populate('drivers.taxis.breakdowns', {where : {breakDownLevel: {'>': 2}}, sort : {breakDownLevel : 1}})
            .exec(function (err, companies) {
              if (err)
                return done(err);
              // Root Level
              assert(companies.length === 1 && companies[0].companyName === 'company 1', 'Root criteria not applied.');
              //Level 1
              assert(companies[0].drivers.length === 1, 'Could not populate first level oneToMany collection.');
              assert(companies[0].drivers[0].driverName === 'driver 3', 'First level criteria not applied.');
              //Level 2
              assert(companies[0].drivers[0].taxis.length === 1, 'Could not populate second level manyToMany collection.');
              var taxi = companies[0].drivers[0].taxis[0];
              assert(taxi.taxiMatricule === 'taxi_3', 'Second level criteria not applied.');
              //Level 3
              assert(taxi.breakdowns.length === 2, 'Could not populate third level oneToMany collection.');
              assert(taxi.breakdowns[0].breakDownLevel === 5 && taxi.breakdowns[1].breakDownLevel  === 8, 'Third level criteria not applied.');

              done();
            });
  });
});
<|endoftext|>


<commit_before>'use strict';
// Projects controller
angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$location', '$window', '$timeout', 'Authentication', 'Projects', 'FileUploader',
	function($scope, $stateParams, $location, $window, $timeout, Authentication, Projects, FileUploader ) {
		$scope.authentication = Authentication;

		// Create file uploader instance
		$scope.uploader = new FileUploader({
			url: '/api/projects/picture'
		});

		$scope.uploaderC = new FileUploader({
			url: '/api/projects/picture'
		});

		// Create new Project
		$scope.create = function() {
			// Create new Project object
			var project = new Projects ({
				name: this.name,
				created: this.created,
				user: this.user,
				status: this.status,
				isPublic: this.isPublic,
				minGrade: this.minGrade,
				maxGrade: this.maxGrade,
				ask: this.ask,
				imagine: this.imagine,
				essentialDetails: this.essentialDetails,
				rating: null
			});

			// Redirect after save
			project.$save(function(response) {

				// Start upload of picture

				$scope.uploaderC.queue[0].url = '/api/projects/picture/' + response._id;
				$scope.uploaderC.uploadAll();

				// Clear form fields
				$scope.name = '';

				$location.path('projects/' + response._id);

			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

		};

		// Remove existing Project
		$scope.remove = function( project ) {
			if ( project ) { project.$remove();

				for (var i in $scope.projects ) {
					if ($scope.projects [i] === project ) {
						$scope.projects.splice(i, 1);
					}
				}
			} else {
				$scope.project.$remove(function() {
					$location.path('projects');
				});
			}
		};

		// Update existing Project
		$scope.update = function() {
			var project = $scope.project;

			project.imagine.plan = '';

			project.$update(function() {

				$location.path('projects/' + project._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			$scope.uploader.queue[0].url = '/api/projects/picture/' + project._id;
			$scope.uploader.uploadAll();
		};

		// Find a list of Projects
		$scope.find = function() {
			$scope.projects = Projects.query();
		};

		// Find existing Project
		$scope.findOne = function() {
			$scope.project = Projects.get({
				projectId: $stateParams.projectId
			});

		};

		// Called after the user selected a new picture file
		$scope.uploader.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.project.imagine.plan = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

		$scope.uploaderC.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.imageURL = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

/*	-------------------------------------Star Rating Stuff-------------------------------------- */

		//an array containing the name of the glyphicon to use for each star
		$scope.glyphs = new Array(
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty'
		);

		/*
			Runs when a star glyphicon is hovered into. It sets all the stars up to the current one
			to have the filled-in star glyphicon.
		*/
		$scope.rating_hover = function(num){
			for(var i = 0; i < num; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star';
			}
			for(i = num; i < 5; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star-empty';
			}
		};

		//Runs when a star glyphicon is hovered out of. Resets the  stars' highlighing to the current rating
		$scope.reset_hover = function(){
			$scope.rating_hover($scope.rating);
		};

		//Prints out user's current rating of the project
		$scope.getMyRating = function(){

			if ($scope.project.rating && $scope.project.rating.ratings ){
				var rater = $scope.project.rating.ratings.filter(isRater)[0];
				console.log(rater);
				if (typeof rater === 'undefined'){
					$scope.rating = 0;	//current rating
					return 'You haven\'t yet rated this project. Give it a couple of stars?';
				}
				$scope.rating = rater.num;
				$scope.reset_hover();
				return ('Your currently rate this project at ' + rater.num + ' stars');
			}
			$scope.rating = 0;	//current rating
			return 'This project has not yet been rated. Give it a couple of stars?';

		};

        // Function to find the current rater
        var isRater = function(value){
			return value.reviewer === $scope.authentication.user._id;
        };

		//Changes the user's rating of the project
		$scope.rate = function(){
			console.log('In $scope.rate');
			if(!$scope.project.rating){
				$scope.project.rating = {
					ratings : [
						{
							num: $scope.rating,
							reviewer: $scope.authentication.user._id
						}
					],
					avg_rating : $scope.rating
				};
			} else {
                var rater = $scope.project.rating.ratings.filter(isRater)[0];
                var length = $scope.project.rating.ratings.length;
				var rateToRemove = 0;

                var newLength = length + 1;

                if(length === 0)
                {
                    $scope.project.rating.avg_rating = 0;
                }

				if(typeof rater !== 'undefined') {
                    rateToRemove = rater.num;
                    var rateIndex = $scope.project.rating.ratings.indexOf(rater);
                    $scope.project.rating.ratings.splice(rateIndex, 1);
                    newLength -= 1;
                }

				$scope.project.rating.avg_rating = ($scope.project.rating.avg_rating * length + $scope.rating - rateToRemove)/(newLength);

				$scope.project.rating.ratings.push({
						num: $scope.rating,
						reviewer: $scope.authentication.user._id
				});
			}
			$scope.update();

		};

	}
]);
<commit_msg>Finished pics<commit_after>'use strict';
// Projects controller
angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$location', '$window', '$timeout', 'Authentication', 'Projects', 'FileUploader',
	function($scope, $stateParams, $location, $window, $timeout, Authentication, Projects, FileUploader ) {
		$scope.authentication = Authentication;

		// Create file uploader instance
		$scope.uploader = new FileUploader({
			url: '/api/projects/picture'
		});

		$scope.uploaderC = new FileUploader({
			url: '/api/projects/picture'
		});

		// Create new Project
		$scope.create = function() {
			// Create new Project object
			var project = new Projects ({
				name: this.name,
				created: this.created,
				user: this.user,
				status: this.status,
				isPublic: this.isPublic,
				minGrade: this.minGrade,
				maxGrade: this.maxGrade,
				ask: this.ask,
				imagine: this.imagine,
				essentialDetails: this.essentialDetails,
				rating: null
			});

			// Redirect after save
			project.$save(function(response) {

				// Start upload of picture

				$scope.uploaderC.queue[0].url = '/api/projects/picture/' + response._id;
				$scope.uploaderC.uploadAll();

				// Clear form fields
				$scope.name = '';

				$location.path('projects/' + response._id);

			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

		};

		// Remove existing Project
		$scope.remove = function( project ) {
			if ( project ) { project.$remove();

				for (var i in $scope.projects ) {
					if ($scope.projects [i] === project ) {
						$scope.projects.splice(i, 1);
					}
				}
			} else {
				$scope.project.$remove(function() {
					$location.path('projects');
				});
			}
		};

		// Update existing Project
		$scope.update = function() {
			var project = $scope.project;

			project.imagine.plan = '';

			project.$update(function() {

				$location.path('projects/' + project._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			$scope.uploader.queue[0].url = '/api/projects/picture/' + project._id;
			$scope.uploader.uploadAll();
		};

		// Find a list of Projects
		$scope.find = function() {
			$scope.projects = Projects.query();
		};

		// Find existing Project
		$scope.findOne = function() {
			$scope.project = Projects.get({
				projectId: $stateParams.projectId
			});

		};

		// Called after the user selected a new picture file
		$scope.uploader.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.project.imagine.plan = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

		$scope.uploaderC.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.imageURL = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

/*	-------------------------------------Star Rating Stuff-------------------------------------- */

		//an array containing the name of the glyphicon to use for each star
		$scope.glyphs = new Array(
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty'
		);

		/*
			Runs when a star glyphicon is hovered into. It sets all the stars up to the current one
			to have the filled-in star glyphicon.
		*/
		$scope.rating_hover = function(num){
			for(var i = 0; i < num; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star';
			}
			for(i = num; i < 5; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star-empty';
			}
		};

		//Runs when a star glyphicon is hovered out of. Resets the  stars' highlighing to the current rating
		$scope.reset_hover = function(){
			$scope.rating_hover($scope.rating);
		};

		//Prints out user's current rating of the project
		$scope.getMyRating = function(){

			if ($scope.project.rating && $scope.project.rating.ratings ){
				var rater = $scope.project.rating.ratings.filter(isRater)[0];
				console.log(rater);
				if (typeof rater === 'undefined'){
					$scope.rating = 0;	//current rating
					return 'You haven\'t yet rated this project. Give it a couple of stars?';
				}
				$scope.rating = rater.num;
				$scope.reset_hover();
				return ('Your currently rate this project at ' + rater.num + ' stars');
			}
			$scope.rating = 0;	//current rating
			return 'This project has not yet been rated. Give it a couple of stars?';

		};

        // Function to find the current rater
        var isRater = function(value){
			return value.reviewer === $scope.authentication.user._id;
        };

		//Changes the user's rating of the project
		$scope.rate = function(){
			console.log('In $scope.rate');
			if(!$scope.project.rating){
				$scope.project.rating = {
					ratings : [
						{
							num: $scope.rating,
							reviewer: $scope.authentication.user._id
						}
					],
					avg_rating : $scope.rating
				};
			} else {
                var rater = $scope.project.rating.ratings.filter(isRater)[0];
                var length = $scope.project.rating.ratings.length;
				var rateToRemove = 0;

                var newLength = length + 1;

                if(length === 0)
                {
                    $scope.project.rating.avg_rating = 0;
                }

				if(typeof rater !== 'undefined') {
                    rateToRemove = rater.num;
                    var rateIndex = $scope.project.rating.ratings.indexOf(rater);
                    $scope.project.rating.ratings.splice(rateIndex, 1);
                    newLength -= 1;
                }

				$scope.project.rating.avg_rating = ($scope.project.rating.avg_rating * length + $scope.rating - rateToRemove)/(newLength);

				$scope.project.rating.ratings.push({
						num: $scope.rating,
						reviewer: $scope.authentication.user._id
				});
			}
			$scope.update();

		};

	}
]);
<|endoftext|>


<commit_before>
$(document).ready(function(){
  function displayResultsRound(results, roundNumber) {
    var endPoint = 10;

    if(results.length < 10){
      endPoint = results.length;
    }

    for(var i = 0; i < endPoint; i++){
      var divGrid = $("

")
      var img = $("");
      var src = results[i]["images"]["original"]["url"];
      $(img).attr("src", src).addClass("result".concat(i));
      $('.pagination').show();
      $('#results' + roundNumber).append(divGrid.append(img));
    }
    $('.pagination').find('[data-id="1"]').addClass("active");
    $('#results1').show();
  }

  // gif
  $('#gif-search').on('change', function(e){
    $('.results-section').empty();
    $('.pagination').empty();
    e.preventDefault();
    var keyword = $('#gif-search').val().replace(/\s/g, '+');
    var url = 'https://api.giphy.com/v1/gifs/search?q=' + keyword + '&api_key=dc6zaTOxFJmzC&limit=100';
    $.ajax({
      url: url,
      type: 'GET',
      dataType: 'json'
    })
    .done(function(responseData) {
      var results = responseData["data"];
      var numberOfRounds = Math.round(results.length / 10);

      for(var i = 1; i <= numberOfRounds; i++) {
        var endPoint = i*10;
        var startPoint = i*10 - 10;
        var range = results.slice(startPoint, endPoint);
        displayResultsRound(range, i);
        var li = $("
 " + i + "
");

        $('.pagination').append(li);
        // $(li).attr({"id", "goto-" + i)};
      }
    })
  });

  $('.pagination').on('click', '.goto', function(){
    var pageNumber = $(this).attr('data-id');
    $('.results-section').hide();

    $('#results' + pageNumber).fadeIn('slow');
    $('.waves-effect').removeClass('active')
    $(this).addClass('active');
  })

  // select gif
  $('.all-gifs').on('click', 'img', function(){
    $('.all-gifs img').css("border", "none").removeClass("selected-gif");
    $(this).css("border", "3px solid #ffdee3").addClass("selected-gif");
  });

  $('#gif-form').on('submit', function(){

    var author = $('.main-gif-section #component_author').val();
    var to_prompt = $('.main-gif-section #to-prompt-gif').is(':checked');
    var prompt_id = $('#component_prompt_id').val();
    var selectedGifUrl = $('.selected-gif').attr('src');

    $.ajax({
      url: '/gifs',
      type: 'post',
      data: {content: selectedGifUrl, author: author, to_prompt: to_prompt, prompt_id: prompt_id},
    })
    .done(function() {
      console.log("success");
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      console.log("complete");
    });
  })
  // user selects the gif they want & it's highlighted
  // user clicks Submit - send that img, author, to_post to the backend
  // save it as a Gif
  // render it in the feed

});

jQuery(window).on('load', function(){
  $('.grid').masonry({
    // set itemSelector so .grid-sizer is not used in layout
    itemSelector: '.grid-item',
    // use element for option
    // columnWidth: '.grid-sizer',
    percentPosition: true
  })
});<commit_msg>AJAX post for gifs redirects to home to clear the query parameters. temp fix<commit_after>
$(document).ready(function(){
  function displayResultsRound(results, roundNumber) {
    var endPoint = 10;

    if(results.length < 10){
      endPoint = results.length;
    }

    for(var i = 0; i < endPoint; i++){
      var divGrid = $("

")
      var img = $("");
      var src = results[i]["images"]["original"]["url"];
      $(img).attr("src", src).addClass("result".concat(i));
      $('.pagination').show();
      $('#results' + roundNumber).append(divGrid.append(img));
    }
    $('.pagination').find('[data-id="1"]').addClass("active");
    $('#results1').show();
  }

  // gif
  $('#gif-search').on('change', function(e){
    $('.results-section').empty();
    $('.pagination').empty();
    e.preventDefault();
    var keyword = $('#gif-search').val().replace(/\s/g, '+');
    var url = 'https://api.giphy.com/v1/gifs/search?q=' + keyword + '&api_key=dc6zaTOxFJmzC&limit=100';
    $.ajax({
      url: url,
      type: 'GET',
      dataType: 'json'
    })
    .done(function(responseData) {
      var results = responseData["data"];
      var numberOfRounds = Math.round(results.length / 10);

      for(var i = 1; i <= numberOfRounds; i++) {
        var endPoint = i*10;
        var startPoint = i*10 - 10;
        var range = results.slice(startPoint, endPoint);
        displayResultsRound(range, i);
        var li = $("
 " + i + "
");

        $('.pagination').append(li);
        // $(li).attr({"id", "goto-" + i)};
      }
    })
  });

  $('.pagination').on('click', '.goto', function(){
    var pageNumber = $(this).attr('data-id');
    $('.results-section').hide();

    $('#results' + pageNumber).fadeIn('slow');
    $('.waves-effect').removeClass('active')
    $(this).addClass('active');
  })

  // select gif
  $('.all-gifs').on('click', 'img', function(){
    $('.all-gifs img').css("border", "none").removeClass("selected-gif");
    $(this).css("border", "3px solid #ffdee3").addClass("selected-gif");
  });

  $('#gif-form').on('submit', function(){

    var author = $('.main-gif-section #component_author').val();
    var to_prompt = $('.main-gif-section #to-prompt-gif').is(':checked');
    var prompt_id = $('#component_prompt_id').val();
    var selectedGifUrl = $('.selected-gif').attr('src');

    $.ajax({
      url: '/gifs',
      type: 'post',
      data: {content: selectedGifUrl, author: author, to_prompt: to_prompt, prompt_id: prompt_id},
    })
    .done(function() {
      window.location.href = '/'
      //temporary fix to clear the query parameters after success
    });
  });
});

jQuery(window).on('load', function(){
  $('.grid').masonry({
    // set itemSelector so .grid-sizer is not used in layout
    itemSelector: '.grid-item',
    // use element for option
    // columnWidth: '.grid-sizer',
    percentPosition: true
  })
});<|endoftext|>


<commit_before>jQuery(document).ready(function($) {

  var $address = $( "#nursing_home_address" );
  if ( $address.length ) {
    // Autocomplete search on SBK's address API
    $( "#nursing_home_address" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: "//xyz.malmo.se/rest/1.0/addresses/",
          dataType: "jsonp",
          data: {
            q: request.term,
            items: 25
          },
          success: function( data ) {
            response( $.map( data.addresses, function( item ) {
              return {
                label: item.name + ", " + item.district,
                value: item.name,
                address: item.name,
                post_code: item.postcode,
                neighborhood: item.district,
                postal_town: item.postal_town,
                east: item.east,
                north: item.north
              };
            }));
          }
        });
      },
      minLength: 2,
      select: function( event, ui ) {
        $('#nursing_home_address').val(ui.item.address);
        $('#nursing_home_post_code').val(ui.item.post_code);
        $('#nursing_home_postal_town').val(ui.item.postal_town);
        $('#nursing_home_neighborhood').val(ui.item.neighborhood);
        $('#nursing_home_geo_position_x').val(ui.item.east);
        $('#nursing_home_geo_position_y').val(ui.item.north);
      },
      open: function() {
        $(this).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $(this).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });

    // Don't submit the form on enter key for this field
    $('#nursing_home_address').keydown( function(event) {
      if (event.which == 13) {
        event.preventDefault();
      }
    });
  }
});
<commit_msg>Street address mapping changes<commit_after>jQuery(document).ready(function($) {

  var $address = $( "#nursing_home_address" );
  if ( $address.length ) {
    // Autocomplete search on SBK's address API
    $( "#nursing_home_address" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: "//xyz.malmo.se/rest/1.0/addresses/",
          dataType: "jsonp",
          data: {
            q: request.term,
            items: 25
          },
          success: function( data ) {
            response( $.map( data.addresses, function( item ) {
              return {
                label: item.name + ", " + item.towndistrict,
                value: item.name,
                address: item.name,
                post_code: item.postcode,
                neighborhood: item.towndistrict,
                postal_town: item.postal_town,
                east: item.east,
                north: item.north
              };
            }));
          }
        });
      },
      minLength: 2,
      select: function( event, ui ) {
        $('#nursing_home_address').val(ui.item.address);
        $('#nursing_home_post_code').val(ui.item.post_code);
        $('#nursing_home_postal_town').val(ui.item.postal_town);
        $('#nursing_home_neighborhood').val(ui.item.neighborhood);
        $('#nursing_home_geo_position_x').val(ui.item.east);
        $('#nursing_home_geo_position_y').val(ui.item.north);
      },
      open: function() {
        $(this).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $(this).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });

    // Don't submit the form on enter key for this field
    $('#nursing_home_address').keydown( function(event) {
      if (event.which == 13) {
        event.preventDefault();
      }
    });
  }
});
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var KssStateGenerator;

  KssStateGenerator = (function() {

    function KssStateGenerator() {
      var idx, idxs, pseudos, replaceRule, rule, stylesheet, _i, _len, _len2, _ref, _ref2;
      pseudos = /(\:hover|\:disabled|\:active|\:visited|\:focus)/g;

      _ref = document.styleSheets;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        stylesheet = _ref[_i];
        idxs = [];
        _ref2 = stylesheet.cssRules || [];
        for (idx = 0, _len2 = _ref2.length; idx < _len2; idx++) {
          rule = _ref2[idx];
          if ((rule.type === CSSRule.STYLE_RULE) && pseudos.test(rule.selectorText)) {
            replaceRule = function(matched) {
              return '.pseudo-class-' + matched.replace(':', '');
            };
            this.insertRule(rule.cssText.replace(pseudos, replaceRule));
          }
        }
      }
    }

    KssStateGenerator.prototype.insertRule = function(rule) {
      var headEl, styleEl;
      headEl = document.getElementsByTagName('head')[0];
      styleEl = document.createElement('style');
      styleEl.type = 'text/css';
      if (styleEl.styleSheet) {
        styleEl.styleSheet.cssText = rule;
      } else {
        styleEl.appendChild(document.createTextNode(rule));
      }
      return headEl.appendChild(styleEl);
    };

    return KssStateGenerator;

  })();

  new KssStateGenerator;

}).call(this);
<commit_msg>Use '()' when calling a constructor<commit_after>(function() {
  'use strict';

  var KssStateGenerator;

  KssStateGenerator = (function() {

    function KssStateGenerator() {
      var idx, idxs, pseudos, replaceRule, rule, stylesheet, _i, _len, _len2, _ref, _ref2;
      pseudos = /(\:hover|\:disabled|\:active|\:visited|\:focus)/g;

      _ref = document.styleSheets;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        stylesheet = _ref[_i];
        idxs = [];
        _ref2 = stylesheet.cssRules || [];
        for (idx = 0, _len2 = _ref2.length; idx < _len2; idx++) {
          rule = _ref2[idx];
          if ((rule.type === CSSRule.STYLE_RULE) && pseudos.test(rule.selectorText)) {
            replaceRule = function(matched) {
              return '.pseudo-class-' + matched.replace(':', '');
            };
            this.insertRule(rule.cssText.replace(pseudos, replaceRule));
          }
        }
      }
    }

    KssStateGenerator.prototype.insertRule = function(rule) {
      var headEl, styleEl;
      headEl = document.getElementsByTagName('head')[0];
      styleEl = document.createElement('style');
      styleEl.type = 'text/css';
      if (styleEl.styleSheet) {
        styleEl.styleSheet.cssText = rule;
      } else {
        styleEl.appendChild(document.createTextNode(rule));
      }
      return headEl.appendChild(styleEl);
    };

    return KssStateGenerator;

  })();

  new KssStateGenerator();

}).call(this);
<|endoftext|>