<commit_before>
var publishedBestiaryCtrl = function ($scope,bestiary,bestiaries,owner,$routeParams,PublishedBestiary,PublishedBestiaryCreaturePager,PublishedBestiaryPager,UserPublishedBestiaryPager,SearchPublishedBestiaryPager,CreatureFilter,CreatureAPI,CreatureClipboard,$mdMedia,$mdDialog,Auth,$location,Bestiary,Creature,$window,Mongo) {
	$scope.bestiary = bestiary;
	$scope.bestiaries = bestiaries;
	$scope.owner = owner;
	$scope.commentEdits = {};
	if(bestiaries && bestiaries.length>0){
		if($routeParams.userId)
			$scope.bestiaryPager = new UserPublishedBestiaryPager($routeParams.userId,bestiaries,2);
		else if(!$routeParams.bestiaryType)
			$scope.bestiaryPager = new SearchPublishedBestiaryPager(bestiaries,1);
		else
			$scope.bestiaryPager = new PublishedBestiaryPager($routeParams.bestiaryType,bestiaries,2);
	}
	if($routeParams.bestiaryType && PublishedBestiary.listConstants[$routeParams.bestiaryType])
		$scope.bestiaryType = PublishedBestiary.listConstants[$routeParams.bestiaryType].name;

	$scope.bestiary.creaturesLoading = true;

	//Recursively loads all creatures
	function loadNextPage(){
		$scope.bestiaryCreaturePager.loadNextPage(loadNextPage);
	}

	var loadCreatures = function(){
		if($scope.bestiary._id){
			Creature.getAllForPublishedBestiary($scope.bestiary._id,1,function(data){
				$scope.bestiary.creaturesLoading = false;
				$scope.bestiary.creatures = data;
				$scope.bestiaryCreaturePager = new PublishedBestiaryCreaturePager($scope.bestiary._id,$scope.bestiary.creatures,2);
				loadNextPage();
				if(!$scope.$$phase)
					$scope.$digest();
			});
		}
	}
	loadCreatures();

	$scope.canInteract = function(){
		return(Auth.user!=null);
	}

	$scope.getStatBlockSize = function(index){
		if($scope.bestiary.creatures && $scope.bestiary.creatures.length>24){
			return("mini");
		}
		else
			return("");
	}

	$scope.creatureFilter = new CreatureFilter();
	$scope.bestiaryListTypes = function(){
		var bestiaryListTypes = [];
		for(var key in PublishedBestiary.listConstants){
			if (PublishedBestiary.listConstants.hasOwnProperty(key)){
				if(!PublishedBestiary.listConstants[key].loginRequired || $scope.canInteract()){
					var listType = angular.copy(PublishedBestiary.listConstants[key]);
					bestiaryListTypes.push(listType);
				}
			}
		}
		return(bestiaryListTypes);
	}();
	$scope.getCurrentBestiaryListType = function(){
		return(PublishedBestiary.listConstants[$routeParams.bestiaryType]);
	}

	var creatureApiOptions = {
		copy: true,
		export: true
	}
	$scope.creatureApi = new CreatureAPI(creatureApiOptions);

	$scope.CreatureClipboard = CreatureClipboard;

	$scope.getPublishedBestiaryListPath = function(){
		return("/#/publishedbestiary/list/recent");
	}

	$scope.getBestiaryPath = function(bestiary){
		if(bestiary)
			return("/#/publishedbestiary/view/"+bestiary._id);
		else
			return("");
	}

	$scope.getUserBestiaryListPath = function(user){
		if(user)
			return("/#/user/"+user._id+"/publishedbestiaries");
		else
			return("");
	}

	$scope.goToSearchPage = function(){
		$location.path("/publishedbestiary/search");
	}

	$scope.bestiarySortFunction = function(bestiary) {
		if($routeParams.bestiaryType=="popular")
			return(-1*bestiary.popularity);
		else
			return(-1*parseInt("0x"+bestiary._id));
	}

	$scope.goBack = function(){
		$window.history.back();
	}

	$scope.editPublishedBestiary = function(ev){
		var useFullScreen = ($mdMedia('sm') || $mdMedia('xs'));
    $mdDialog.show({
      controller: publishBestiaryCtrl,
      templateUrl: '/assets/partials/publishedBestiary/edit.html',
      parent: angular.element(document.body),
      targetEvent: ev,
      clickOutsideToClose:true,
      locals: {
      	'baseBestiary': undefined,
      	'publishedBestiary': $scope.bestiary
      },
      fullscreen: useFullScreen
    }).then(function(updatedBestiary){
    	$scope.bestiary.name = updatedBestiary.name;
    	$scope.bestiary.description = updatedBestiary.description;
    });
	}

	$scope.deletePublishedBestiary = function(ev){
    var confirm = $mdDialog.confirm()
			.title("Confirm Deletion")
			.textContent("This published bestiary will be permanently deleted. Would you like to proceed?")
			.ariaLabel("Confirm Delete")
			.targetEvent(ev)
			.ok("Delete")
			.cancel("Cancel");
		$mdDialog.show(confirm).then(function() {
			PublishedBestiary.delete($scope.bestiary._id);
			//Don't wait for delete to actually finish so that the UI feels more responsive.
			$location.url("/bestiary/list");
		});
	}

	var copyCreaturesToBestiary = function(createdBestiary){
		var copiedCount = 0;
		var totalToCopy = $scope.bestiary.creatures.length;
		var finishedCreatingCreature = function(){
			copiedCount = copiedCount + 1;
			if(copiedCount==totalToCopy){
				$location.url("/bestiary/view/"+createdBestiary._id);
			}
		}
		for(var i=0;i<$scope.bestiary.creatures.length;i++){
			var newCreature = angular.copy($scope.bestiary.creatures[i]);
			newCreature._id = undefined;
			newCreature.bestiaryId = createdBestiary._id;
			newCreature.publishedBestiaryId = undefined;
			Creature.create(newCreature,finishedCreatingCreature,finishedCreatingCreature);
		}
	}

	$scope.copyBestiary = function(){
		var newBestiary = Bestiary.generateNewBestiary(Auth.user._id);
		newBestiary.name = $scope.bestiary.name;
		newBestiary.description = $scope.bestiary.description;
		Bestiary.create(newBestiary,function(data){
			copyCreaturesToBestiary(data);
		},function(err){
			console.log("error: "+err);
		});
	}

	$scope.isOwner = function(){
		return(Auth.user && Auth.user._id == $scope.bestiary.owner._id);
	}

	$scope.isLiked = function(){
		if($scope.bestiary.likes){
			for(var i=0;i<$scope.bestiary.likes.length;i++){
				if($scope.bestiary.likes[i].userId == Auth.user._id)
					return true;
			}
		}
		return false;
	}

	$scope.toggleLike = function(){
		if($scope.isLiked())
			PublishedBestiary.unlike($scope.bestiary._id,function(data){
				$scope.bestiary.likes = data.likes;
			});
		else
			PublishedBestiary.like($scope.bestiary._id,function(data){
				$scope.bestiary.likes = data.likes;
			});
	}

	$scope.isFavorite = function(){
		if($scope.bestiary.favorites){
			for(var i=0;i<$scope.bestiary.favorites.length;i++){
				if($scope.bestiary.favorites[i].userId == Auth.user._id)
					return true;
			}
		}
		return false;
	}

	$scope.toggleFavorite = function(){
		if($scope.isFavorite())
			PublishedBestiary.unfavorite($scope.bestiary._id,function(data){
				$scope.bestiary.favorites = data.favorites;
			});
		else
			PublishedBestiary.favorite($scope.bestiary._id,function(data){
				$scope.bestiary.favorites = data.favorites;
			});
	}

	function resetNewComment(){
		$scope.newComment = {
			text: ""
		}
	}
	resetNewComment();
	$scope.postComment = function(){
		if($scope.newComment.text.length>0){
			$scope.newComment.author = Auth.user._id;
			$scope.postingComment = true;
			PublishedBestiary.addComment($scope.bestiary._id,$scope.newComment,function(data){
				resetNewComment();
				$scope.bestiary.comments = data.comments;
				$scope.postingComment = false;
			},function(err){
				$scope.postingComment = false;
			});
		}
	}

	function resetCommentEdits(comment){
		if($scope.commentEdits[comment._id])
			delete $scope.commentEdits[comment._id];
	}

	$scope.editComment = function(comment){
		$scope.commentEdits[comment._id] = {
			text: comment.text
		}
	}

	$scope.cancelCommentEdits = function(comment){
		resetCommentEdits(comment);
	}

	$scope.saveCommentEdits = function(comment){
		//Take effect immediately before we actually talk to the server
		comment.text = $scope.commentEdits[comment._id].text;
		resetCommentEdits(comment);
		PublishedBestiary.updateComment($scope.bestiary._id,comment._id,comment,function(data){
			$scope.bestiary.comments = data.comments;
		});
	}

	$scope.deleteComment = function(ev,id){
		var confirm = $mdDialog.confirm()
			.title("Confirm Deletion")
			.textContent("This comment will be permanently deleted. Would you like to proceed?")
			.ariaLabel("Confirm Delete")
			.targetEvent(ev)
			.ok("Delete")
			.cancel("Cancel");
		$mdDialog.show(confirm).then(function() {
			PublishedBestiary.deleteComment($scope.bestiary._id,id,function(data){
				$scope.bestiary.comments = data.comments;
			});
		});
	}

	$scope.getCommentsHeader = function(){
		if($scope.bestiary && $scope.bestiary.comments){
			var header = $scope.bestiary.comments.length + " comment";
			if($scope.bestiary.comments.length != 1)
				header = header + "s";
			return(header);
		}
		else
			return "0 comments";
	}

	$scope.search = {
		name: ""
	}
	$scope.searching = false;

	$scope.runSearch = function(){
		var searchCopy = angular.copy($scope.search);
		$scope.searching = true;
		PublishedBestiary.search(searchCopy,1,function(data){
			$scope.searching = false;
			$scope.bestiaries = data;
			$scope.bestiaryPager = new SearchPublishedBestiaryPager(searchCopy,$scope.bestiaries,2);
		});
	}

	$scope.getCreationDate = Mongo.getTimestamp;

};

//don't load controller until we've gotten the data from the server
publishedBestiaryCtrl.resolve = {
	bestiary: ['PublishedBestiary','$q','$route','Auth',function(PublishedBestiary, $q, $route, Auth){
			if($route.current.params.bestiaryId){
				var deferred = $q.defer();
				Auth.executeOnLogin(function(){
					PublishedBestiary.get($route.current.params.bestiaryId,function(data) {
						deferred.resolve(data);
					}, function(errorData) {
						deferred.reject();
					});
				});
				return deferred.promise;
			}
			else
				return {};
		}],
	bestiaries: ['PublishedBestiary','$q','$route','Auth',function(PublishedBestiary, $q, $route, Auth){
			if($route.current.params.bestiaryType){
				var deferred = $q.defer();
				Auth.executeOnLogin(function(){
					var type = $route.current.params.bestiaryType;
					if(PublishedBestiary.listConstants[type]){
						var retrievalFunction = PublishedBestiary.listConstants[type].retrievalFunction;
						var page = $route.current.params.page || 1;
						retrievalFunction(page,function(data) {
							deferred.resolve(data);
						}, function(errorData) {
							deferred.reject();
						});
					}
					else
						deferred.reject();
				});
				return deferred.promise;
			}
			else if($route.current.params.userId){
				var deferred = $q.defer();
				var page = $route.current.params.page || 1;
				PublishedBestiary.getByUser($route.current.params.userId,page,function(data) {
					deferred.resolve(data);
				}, function(errorData) {
					deferred.reject();
				});
				return deferred.promise;
			}
			else
				return undefined;
		}],
	owner: ['User','$q','$route','Auth',function(User, $q, $route, Auth){
			if($route.current.params.userId){
				var deferred = $q.defer();
				Auth.executeOnLogin(function(){
					var userId = $route.current.params.userId;
					User.getPublic(userId,function(data) {
						deferred.resolve(data);
					}, function(errorData) {
						deferred.reject();
					});
				});
				return deferred.promise;
			}
			else
				return undefined;
		}]
}

angular.module('myApp').controller('publishedBestiaryCtrl',publishedBestiaryCtrl);
<commit_msg>fixed sorting order of popular published bestiaries<commit_after>
var publishedBestiaryCtrl = function ($scope,bestiary,bestiaries,owner,$routeParams,PublishedBestiary,PublishedBestiaryCreaturePager,PublishedBestiaryPager,UserPublishedBestiaryPager,SearchPublishedBestiaryPager,CreatureFilter,CreatureAPI,CreatureClipboard,$mdMedia,$mdDialog,Auth,$location,Bestiary,Creature,$window,Mongo) {
	$scope.bestiary = bestiary;
	$scope.bestiaries = bestiaries;
	$scope.owner = owner;
	$scope.commentEdits = {};
	if(bestiaries && bestiaries.length>0){
		if($routeParams.userId)
			$scope.bestiaryPager = new UserPublishedBestiaryPager($routeParams.userId,bestiaries,2);
		else if(!$routeParams.bestiaryType)
			$scope.bestiaryPager = new SearchPublishedBestiaryPager(bestiaries,1);
		else
			$scope.bestiaryPager = new PublishedBestiaryPager($routeParams.bestiaryType,bestiaries,2);
	}
	if($routeParams.bestiaryType && PublishedBestiary.listConstants[$routeParams.bestiaryType])
		$scope.bestiaryType = PublishedBestiary.listConstants[$routeParams.bestiaryType].name;

	$scope.bestiary.creaturesLoading = true;

	//Recursively loads all creatures
	function loadNextPage(){
		$scope.bestiaryCreaturePager.loadNextPage(loadNextPage);
	}

	var loadCreatures = function(){
		if($scope.bestiary._id){
			Creature.getAllForPublishedBestiary($scope.bestiary._id,1,function(data){
				$scope.bestiary.creaturesLoading = false;
				$scope.bestiary.creatures = data;
				$scope.bestiaryCreaturePager = new PublishedBestiaryCreaturePager($scope.bestiary._id,$scope.bestiary.creatures,2);
				loadNextPage();
				if(!$scope.$$phase)
					$scope.$digest();
			});
		}
	}
	loadCreatures();

	$scope.canInteract = function(){
		return(Auth.user!=null);
	}

	$scope.getStatBlockSize = function(index){
		if($scope.bestiary.creatures && $scope.bestiary.creatures.length>24){
			return("mini");
		}
		else
			return("");
	}

	$scope.creatureFilter = new CreatureFilter();
	$scope.bestiaryListTypes = function(){
		var bestiaryListTypes = [];
		for(var key in PublishedBestiary.listConstants){
			if (PublishedBestiary.listConstants.hasOwnProperty(key)){
				if(!PublishedBestiary.listConstants[key].loginRequired || $scope.canInteract()){
					var listType = angular.copy(PublishedBestiary.listConstants[key]);
					bestiaryListTypes.push(listType);
				}
			}
		}
		return(bestiaryListTypes);
	}();
	$scope.getCurrentBestiaryListType = function(){
		return(PublishedBestiary.listConstants[$routeParams.bestiaryType]);
	}

	var creatureApiOptions = {
		copy: true,
		export: true
	}
	$scope.creatureApi = new CreatureAPI(creatureApiOptions);

	$scope.CreatureClipboard = CreatureClipboard;

	$scope.getPublishedBestiaryListPath = function(){
		return("/#/publishedbestiary/list/recent");
	}

	$scope.getBestiaryPath = function(bestiary){
		if(bestiary)
			return("/#/publishedbestiary/view/"+bestiary._id);
		else
			return("");
	}

	$scope.getUserBestiaryListPath = function(user){
		if(user)
			return("/#/user/"+user._id+"/publishedbestiaries");
		else
			return("");
	}

	$scope.goToSearchPage = function(){
		$location.path("/publishedbestiary/search");
	}

	$scope.bestiarySortFunction = function(bestiary) {
		if($routeParams.bestiaryType=="popular")
			return(bestiary.popularity);
		else
			return(-1*parseInt("0x"+bestiary._id));
	}

	$scope.goBack = function(){
		$window.history.back();
	}

	$scope.editPublishedBestiary = function(ev){
		var useFullScreen = ($mdMedia('sm') || $mdMedia('xs'));
    $mdDialog.show({
      controller: publishBestiaryCtrl,
      templateUrl: '/assets/partials/publishedBestiary/edit.html',
      parent: angular.element(document.body),
      targetEvent: ev,
      clickOutsideToClose:true,
      locals: {
      	'baseBestiary': undefined,
      	'publishedBestiary': $scope.bestiary
      },
      fullscreen: useFullScreen
    }).then(function(updatedBestiary){
    	$scope.bestiary.name = updatedBestiary.name;
    	$scope.bestiary.description = updatedBestiary.description;
    });
	}

	$scope.deletePublishedBestiary = function(ev){
    var confirm = $mdDialog.confirm()
			.title("Confirm Deletion")
			.textContent("This published bestiary will be permanently deleted. Would you like to proceed?")
			.ariaLabel("Confirm Delete")
			.targetEvent(ev)
			.ok("Delete")
			.cancel("Cancel");
		$mdDialog.show(confirm).then(function() {
			PublishedBestiary.delete($scope.bestiary._id);
			//Don't wait for delete to actually finish so that the UI feels more responsive.
			$location.url("/bestiary/list");
		});
	}

	var copyCreaturesToBestiary = function(createdBestiary){
		var copiedCount = 0;
		var totalToCopy = $scope.bestiary.creatures.length;
		var finishedCreatingCreature = function(){
			copiedCount = copiedCount + 1;
			if(copiedCount==totalToCopy){
				$location.url("/bestiary/view/"+createdBestiary._id);
			}
		}
		for(var i=0;i<$scope.bestiary.creatures.length;i++){
			var newCreature = angular.copy($scope.bestiary.creatures[i]);
			newCreature._id = undefined;
			newCreature.bestiaryId = createdBestiary._id;
			newCreature.publishedBestiaryId = undefined;
			Creature.create(newCreature,finishedCreatingCreature,finishedCreatingCreature);
		}
	}

	$scope.copyBestiary = function(){
		var newBestiary = Bestiary.generateNewBestiary(Auth.user._id);
		newBestiary.name = $scope.bestiary.name;
		newBestiary.description = $scope.bestiary.description;
		Bestiary.create(newBestiary,function(data){
			copyCreaturesToBestiary(data);
		},function(err){
			console.log("error: "+err);
		});
	}

	$scope.isOwner = function(){
		return(Auth.user && Auth.user._id == $scope.bestiary.owner._id);
	}

	$scope.isLiked = function(){
		if($scope.bestiary.likes){
			for(var i=0;i<$scope.bestiary.likes.length;i++){
				if($scope.bestiary.likes[i].userId == Auth.user._id)
					return true;
			}
		}
		return false;
	}

	$scope.toggleLike = function(){
		if($scope.isLiked())
			PublishedBestiary.unlike($scope.bestiary._id,function(data){
				$scope.bestiary.likes = data.likes;
			});
		else
			PublishedBestiary.like($scope.bestiary._id,function(data){
				$scope.bestiary.likes = data.likes;
			});
	}

	$scope.isFavorite = function(){
		if($scope.bestiary.favorites){
			for(var i=0;i<$scope.bestiary.favorites.length;i++){
				if($scope.bestiary.favorites[i].userId == Auth.user._id)
					return true;
			}
		}
		return false;
	}

	$scope.toggleFavorite = function(){
		if($scope.isFavorite())
			PublishedBestiary.unfavorite($scope.bestiary._id,function(data){
				$scope.bestiary.favorites = data.favorites;
			});
		else
			PublishedBestiary.favorite($scope.bestiary._id,function(data){
				$scope.bestiary.favorites = data.favorites;
			});
	}

	function resetNewComment(){
		$scope.newComment = {
			text: ""
		}
	}
	resetNewComment();
	$scope.postComment = function(){
		if($scope.newComment.text.length>0){
			$scope.newComment.author = Auth.user._id;
			$scope.postingComment = true;
			PublishedBestiary.addComment($scope.bestiary._id,$scope.newComment,function(data){
				resetNewComment();
				$scope.bestiary.comments = data.comments;
				$scope.postingComment = false;
			},function(err){
				$scope.postingComment = false;
			});
		}
	}

	function resetCommentEdits(comment){
		if($scope.commentEdits[comment._id])
			delete $scope.commentEdits[comment._id];
	}

	$scope.editComment = function(comment){
		$scope.commentEdits[comment._id] = {
			text: comment.text
		}
	}

	$scope.cancelCommentEdits = function(comment){
		resetCommentEdits(comment);
	}

	$scope.saveCommentEdits = function(comment){
		//Take effect immediately before we actually talk to the server
		comment.text = $scope.commentEdits[comment._id].text;
		resetCommentEdits(comment);
		PublishedBestiary.updateComment($scope.bestiary._id,comment._id,comment,function(data){
			$scope.bestiary.comments = data.comments;
		});
	}

	$scope.deleteComment = function(ev,id){
		var confirm = $mdDialog.confirm()
			.title("Confirm Deletion")
			.textContent("This comment will be permanently deleted. Would you like to proceed?")
			.ariaLabel("Confirm Delete")
			.targetEvent(ev)
			.ok("Delete")
			.cancel("Cancel");
		$mdDialog.show(confirm).then(function() {
			PublishedBestiary.deleteComment($scope.bestiary._id,id,function(data){
				$scope.bestiary.comments = data.comments;
			});
		});
	}

	$scope.getCommentsHeader = function(){
		if($scope.bestiary && $scope.bestiary.comments){
			var header = $scope.bestiary.comments.length + " comment";
			if($scope.bestiary.comments.length != 1)
				header = header + "s";
			return(header);
		}
		else
			return "0 comments";
	}

	$scope.search = {
		name: ""
	}
	$scope.searching = false;

	$scope.runSearch = function(){
		var searchCopy = angular.copy($scope.search);
		$scope.searching = true;
		PublishedBestiary.search(searchCopy,1,function(data){
			$scope.searching = false;
			$scope.bestiaries = data;
			$scope.bestiaryPager = new SearchPublishedBestiaryPager(searchCopy,$scope.bestiaries,2);
		});
	}

	$scope.getCreationDate = Mongo.getTimestamp;

};

//don't load controller until we've gotten the data from the server
publishedBestiaryCtrl.resolve = {
	bestiary: ['PublishedBestiary','$q','$route','Auth',function(PublishedBestiary, $q, $route, Auth){
			if($route.current.params.bestiaryId){
				var deferred = $q.defer();
				Auth.executeOnLogin(function(){
					PublishedBestiary.get($route.current.params.bestiaryId,function(data) {
						deferred.resolve(data);
					}, function(errorData) {
						deferred.reject();
					});
				});
				return deferred.promise;
			}
			else
				return {};
		}],
	bestiaries: ['PublishedBestiary','$q','$route','Auth',function(PublishedBestiary, $q, $route, Auth){
			if($route.current.params.bestiaryType){
				var deferred = $q.defer();
				Auth.executeOnLogin(function(){
					var type = $route.current.params.bestiaryType;
					if(PublishedBestiary.listConstants[type]){
						var retrievalFunction = PublishedBestiary.listConstants[type].retrievalFunction;
						var page = $route.current.params.page || 1;
						retrievalFunction(page,function(data) {
							deferred.resolve(data);
						}, function(errorData) {
							deferred.reject();
						});
					}
					else
						deferred.reject();
				});
				return deferred.promise;
			}
			else if($route.current.params.userId){
				var deferred = $q.defer();
				var page = $route.current.params.page || 1;
				PublishedBestiary.getByUser($route.current.params.userId,page,function(data) {
					deferred.resolve(data);
				}, function(errorData) {
					deferred.reject();
				});
				return deferred.promise;
			}
			else
				return undefined;
		}],
	owner: ['User','$q','$route','Auth',function(User, $q, $route, Auth){
			if($route.current.params.userId){
				var deferred = $q.defer();
				Auth.executeOnLogin(function(){
					var userId = $route.current.params.userId;
					User.getPublic(userId,function(data) {
						deferred.resolve(data);
					}, function(errorData) {
						deferred.reject();
					});
				});
				return deferred.promise;
			}
			else
				return undefined;
		}]
}

angular.module('myApp').controller('publishedBestiaryCtrl',publishedBestiaryCtrl);
<|endoftext|>


<commit_before>// ==UserScript==
// @name         youtube-auto-pause
// @version      0.1.0
// @description  always pause youtube videos on page load
// @namespace    http://kafene.org
// @copyright    2014 kafene software <http://kafene.org/>
// @include      http://www.youtube.com/*
// @include      https://www.youtube.com/*
// @include      http://youtube.com/*
// @include      https://youtube.com/*
// @include      http://www.youtube-nocookie.com/*
// @include      https://www.youtube-nocookie.com/*
// @include      http://youtube-nocookie.com/*
// @include      https://youtube-nocookie.com/*
// @run-at       document-start
// @grant        none
// @license      MIT <https://raw.githubusercontent.com/kafene/userscripts/mater/LICENSE>
// @require      https://raw.githubusercontent.com/ded/domready/master/src/ready.js
// @downloadURL  https://raw.githubusercontent.com/kafene/userscripts/master/youtube-auto-pause.user.js
// @updateURL    https://raw.githubusercontent.com/kafene/userscripts/master/youtube-auto-pause.user.js
// ==/UserScript==

domready(function () {
    var buttons = document.querySelectorAll(".ytp-button-pause");
    [].forEach.call(buttons, function (b) { b.click && b.click(); });
});

new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        if (mutation.addedNodes) {
            Array.from(mutation.addedNodes).forEach(function (node) {
                if (node && node.matches && node.matches(".ytp-button-pause")) {
                    setTimeout(function () { node.click && node.click(); });
                }
            });
        }
    });
}).observe(document, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
});
<commit_msg>bump version<commit_after>// ==UserScript==
// @name         youtube-auto-pause
// @version      0.2.0
// @description  always pause youtube videos on page load
// @namespace    http://kafene.org
// @copyright    2014 kafene software <http://kafene.org/>
// @include      http://www.youtube.com/*
// @include      https://www.youtube.com/*
// @include      http://youtube.com/*
// @include      https://youtube.com/*
// @include      http://www.youtube-nocookie.com/*
// @include      https://www.youtube-nocookie.com/*
// @include      http://youtube-nocookie.com/*
// @include      https://youtube-nocookie.com/*
// @run-at       document-start
// @grant        none
// @license      MIT <https://raw.githubusercontent.com/kafene/userscripts/mater/LICENSE>
// @require      https://raw.githubusercontent.com/ded/domready/master/src/ready.js
// @downloadURL  https://raw.githubusercontent.com/kafene/userscripts/master/youtube-auto-pause.user.js
// @updateURL    https://raw.githubusercontent.com/kafene/userscripts/master/youtube-auto-pause.user.js
// ==/UserScript==

domready(function () {
    var buttons = document.querySelectorAll(".ytp-button-pause");
    [].forEach.call(buttons, function (b) { b.click && b.click(); });
});

new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        if (mutation.addedNodes) {
            Array.from(mutation.addedNodes).forEach(function (node) {
                if (node && node.matches && node.matches(".ytp-button-pause")) {
                    setTimeout(function () { node.click && node.click(); });
                }
            });
        }
    });
}).observe(document, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var muon = require('./../module');
muon.ready(function(){
    var repl = require("repl").start('>');
    var context = repl.context;
    context.m = muon;
    require('repl.history')(repl, process.env.HOME + '/.node_history');
    repl.on('exit', function () { process.exit(); });
});
//context.underscore = require('underscore');

<commit_msg>temp commit<commit_after>#!/usr/bin/env node

var muon = require('./../module');
muon.ready(function(){
    var repl = require("repl").start('> ');
    var context = repl.context;
    context.m = muon;
    require('repl.history')(repl, process.env.HOME + '/.node_history');
    repl.on('exit', function () { process.exit(); });
});
//context.underscore = require('underscore');

<|endoftext|>


<commit_before>"use strict";

const ReactDOM = require("react-dom/server");
const Helmet = require("react-helmet");
const Router = require("react-router");
const defaultTemplate = require("./defaultTemplate.js");

const radium = require("react-wildcat-radium");
const matchMediaMock = require("match-media-mock").create();

const getClientSize = require("./getClientSize.js");
const serverContext = require("./serverContext.js");

const match = Router.match;

radium.setMatchMedia(matchMediaMock);

module.exports = function serverRender(cfg) {
    const cookies = cfg.cookies;
    const request = cfg.request;
    const wildcatConfig = cfg.wildcatConfig;

    return new Promise((resolve) => {
        match(cfg, (error, redirectLocation, renderProps) => {
            let result = {};

            if (redirectLocation) {
                result = {
                    redirect: true,
                    redirectLocation,
                    status: 301
                };
            } else if (error) {
                result = {
                    error,
                    status: 500
                };
            } else if (!renderProps) {
                result = {
                    error: "Not found",
                    status: 404
                };
            } else {
                const clientSize = getClientSize(cookies, request.query);

                matchMediaMock.setConfig({
                    type: "screen",
                    height: clientSize.height,
                    width: clientSize.width
                });

                const initialData = {};

                return Promise.all(
                    renderProps.components
                        .filter(component => component.prefetch)
                        .map(component => {
                            const prefetch = component.prefetch;
                            const key = prefetch.getKey();

                            return prefetch.run(renderProps).then(props => {
                                initialData[key] = prefetch[key] = props;
                            });
                        })
                ).then(() => {
                    const reactMarkup = ReactDOM.renderToString(
                        serverContext(request, renderProps)
                    );

                    const head = Object.assign({
                        link: "",
                        meta: "",
                        title: ""
                    }, Helmet.rewind());

                    const htmlTemplate = wildcatConfig.serverSettings.htmlTemplate || defaultTemplate;

                    const html = htmlTemplate({
                        data: initialData,
                        head: head,
                        html: reactMarkup,
                        wildcatConfig: wildcatConfig
                    });

                    result = Object.assign({}, result, {
                        html: html
                    });

                    return resolve(result);
                });
            }

            return resolve(result);
        });
    });
};
<commit_msg>fix(react-wildcat-handoff): send 200 status<commit_after>"use strict";

const ReactDOM = require("react-dom/server");
const Helmet = require("react-helmet");
const Router = require("react-router");
const defaultTemplate = require("./defaultTemplate.js");

const radium = require("react-wildcat-radium");
const matchMediaMock = require("match-media-mock").create();

const getClientSize = require("./getClientSize.js");
const serverContext = require("./serverContext.js");

const match = Router.match;

radium.setMatchMedia(matchMediaMock);

module.exports = function serverRender(cfg) {
    const cookies = cfg.cookies;
    const request = cfg.request;
    const wildcatConfig = cfg.wildcatConfig;

    return new Promise((resolve) => {
        match(cfg, (error, redirectLocation, renderProps) => {
            let result = {};

            if (redirectLocation) {
                result = {
                    redirect: true,
                    redirectLocation,
                    status: 301
                };
            } else if (error) {
                result = {
                    error,
                    status: 500
                };
            } else if (!renderProps) {
                result = {
                    error: "Not found",
                    status: 404
                };
            } else {
                const clientSize = getClientSize(cookies, request.query);

                matchMediaMock.setConfig({
                    type: "screen",
                    height: clientSize.height,
                    width: clientSize.width
                });

                const initialData = {};

                return Promise.all(
                    renderProps.components
                        .filter(component => component.prefetch)
                        .map(component => {
                            const prefetch = component.prefetch;
                            const key = prefetch.getKey();

                            return prefetch.run(renderProps).then(props => {
                                initialData[key] = prefetch[key] = props;
                            });
                        })
                ).then(() => {
                    const reactMarkup = ReactDOM.renderToString(
                        serverContext(request, renderProps)
                    );

                    const head = Object.assign({
                        link: "",
                        meta: "",
                        title: ""
                    }, Helmet.rewind());

                    const htmlTemplate = wildcatConfig.serverSettings.htmlTemplate || defaultTemplate;

                    const html = htmlTemplate({
                        data: initialData,
                        head: head,
                        html: reactMarkup,
                        wildcatConfig: wildcatConfig
                    });

                    result = Object.assign({}, result, {
                        html: html,
                        status: 200
                    });

                    return resolve(result);
                });
            }

            return resolve(result);
        });
    });
};
<|endoftext|>


<commit_before>'use strict';

var unserializeValue = require('dbjs/_setup/unserialize/value')
  , serializeValue   = require('dbjs/_setup/serialize/value')
  , normalizeOptions = require('es5-ext/object/normalize-options')
  , getDbSet         = require('eregistrations/server/utils/get-db-set')
  , deferred         = require('deferred')
  , aFrom            = require('es5-ext/array/from')
  , debug            = require('debug-ext')('auto-assign');

module.exports = function (businessProcessStorage, counterStorage, officials, step/*, options*/) {
	var options = normalizeOptions(arguments[4])
	  , id      = step.shortPath
	  , path    = step.__id__.slice(step.master.__id__.length + 1)
	  , officialsArray, lastIndex;

	officialsArray = officials.toArray();

	var addAssignee = function (businessProcessId) {
		var recordId = businessProcessId + '/' + path + '/assignee';
		return businessProcessStorage.get(recordId)(function (data) {
			var officialId;
			if (data && data.value[0] === '7') return;
			lastIndex = officialsArray[lastIndex + 1] ? lastIndex + 1 : 0;
			officialId = officialsArray[lastIndex];
			debug('for %s assigned id: %s, to %s', id, officialId, businessProcessId);
			return deferred(
				businessProcessStorage.store(businessProcessId + '/' + path + '/assignee',
					'7' + officialId),
				counterStorage.store('processingStepAutoAssignLastIndex/' + id, serializeValue(lastIndex))
			)(function () {
				if (options.onAssign) return options.onAssign(officialId);
			});
		});
	};

	return counterStorage.get('processingStepAutoAssignLastIndex/' + id)(function (data) {
		return (data && unserializeValue(data.value)) || 0;
	}).then(function (index) {
		lastIndex = index;
		return getDbSet(
			businessProcessStorage,
			'computed',
			path + '/status',
			serializeValue('pending')
		)(function (businessProcesses) {
			var listener = function (ev) {
				if (ev.type === 'delete') return;
				if (ev.type === 'add') {
					addAssignee(ev.value).done();
					return;
				}
				if (ev.type === 'batch') {
					if (!ev.added) return;
					deferred.map(aFrom(ev.added), addAssignee).done();
					return;
				}

				throw new Error("Unsupported event: " + ev.type);
			};
			var activate = function () {
				businessProcesses.on('change', listener);
				return deferred.map(aFrom(businessProcesses), addAssignee);
			};
			var deactivate = function () {
				businessProcesses.off('change', listener);
			};
			if (officials.size) return activate();
			officials._size.on('change', function (event) {
				if (event.newValue) {
					if (!event.oldValue) activate().done();
				} else if (event.oldValue) {
					deactivate();
				}
			});
		});
	});
};
<commit_msg>Improve service logs<commit_after>'use strict';

var unserializeValue = require('dbjs/_setup/unserialize/value')
  , serializeValue   = require('dbjs/_setup/serialize/value')
  , normalizeOptions = require('es5-ext/object/normalize-options')
  , getDbSet         = require('eregistrations/server/utils/get-db-set')
  , deferred         = require('deferred')
  , aFrom            = require('es5-ext/array/from')
  , debug            = require('debug-ext')('auto-assign');

module.exports = function (businessProcessStorage, counterStorage, officials, step/*, options*/) {
	var options = normalizeOptions(arguments[4])
	  , id      = step.shortPath
	  , path    = step.__id__.slice(step.master.__id__.length + 1)
	  , officialsArray, lastIndex;

	officialsArray = officials.toArray();

	var addAssignee = function (businessProcessId) {
		var recordId = businessProcessId + '/' + path + '/assignee';
		return businessProcessStorage.get(recordId)(function (data) {
			var officialId;
			if (data && data.value[0] === '7') return;
			lastIndex = officialsArray[lastIndex + 1] ? lastIndex + 1 : 0;
			officialId = officialsArray[lastIndex];
			debug('for %s assigned official: %s, to process: %s', id, officialId, businessProcessId);
			return deferred(
				businessProcessStorage.store(businessProcessId + '/' + path + '/assignee',
					'7' + officialId),
				counterStorage.store('processingStepAutoAssignLastIndex/' + id, serializeValue(lastIndex))
			)(function () {
				if (options.onAssign) return options.onAssign(officialId);
			});
		});
	};

	return counterStorage.get('processingStepAutoAssignLastIndex/' + id)(function (data) {
		return (data && unserializeValue(data.value)) || 0;
	}).then(function (index) {
		lastIndex = index;
		return getDbSet(
			businessProcessStorage,
			'computed',
			path + '/status',
			serializeValue('pending')
		)(function (businessProcesses) {
			var listener = function (ev) {
				if (ev.type === 'delete') return;
				if (ev.type === 'add') {
					addAssignee(ev.value).done();
					return;
				}
				if (ev.type === 'batch') {
					if (!ev.added) return;
					deferred.map(aFrom(ev.added), addAssignee).done();
					return;
				}

				throw new Error("Unsupported event: " + ev.type);
			};
			var activate = function () {
				businessProcesses.on('change', listener);
				return deferred.map(aFrom(businessProcesses), addAssignee);
			};
			var deactivate = function () {
				businessProcesses.off('change', listener);
			};
			if (officials.size) return activate();
			officials._size.on('change', function (event) {
				if (event.newValue) {
					if (!event.oldValue) activate().done();
				} else if (event.oldValue) {
					deactivate();
				}
			});
		});
	});
};
<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>"About Mutability edit"<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe("Smith, John");
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe("John");
    expect(aPerson.getLastName()).toBe("Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe("Andrews, Penny");
  });

});
<|endoftext|>


<commit_before>import './utils/polyfills';
import './components/pl-nav/pl-nav';
import './components/pl-logo/pl-logo';
import './components/pl-layout/pl-layout';
import './components/pl-controls/pl-controls';
import './components/pl-drawer/pl-drawer';
import './components/pl-header/pl-header';
import './components/pl-viewport/pl-viewport';
import './components/pl-toggle-info/pl-toggle-info';
import './components/pl-toggle-layout/pl-toggle-layout';
import './components/pl-toggle-theme/pl-toggle-theme';
import './components/pl-tools-menu/pl-tools-menu';
import './components/pl-search/pl-search';

loadPolyfills.then(() => {
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-layout' */ './components/pl-layout/pl-layout'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-controls' */ './components/pl-controls/pl-controls'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-drawer' */ './components/pl-drawer/pl-drawer'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-header' */ './components/pl-header/pl-header'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-iframe' */ './components/pl-viewport/pl-viewport'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-nav' */ './components/pl-nav/pl-nav'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-search' */ './components/pl-search/pl-search'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-toggle-info' */ './components/pl-toggle-info/pl-toggle-info'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-toggle-layout' */ './components/pl-toggle-layout/pl-toggle-layout'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-toggle-theme' */ './components/pl-toggle-theme/pl-toggle-theme'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-tools-menu' */ './components/pl-tools-menu/pl-tools-menu'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-styleguide' */ './components/styleguide'
  );
  import(
    /* webpackMode: 'lazy', webpackChunkName: 'pl-modal-viewer' */ './components/modal-viewer'
  );
});

import(
  /* webpackChunkName: "pl-modal-viewer" */
  /* webpackMode: "lazy" */
  /* webpackPrefetch: true */
  './components/modal-viewer'
);

// Add hook to auto re-render the root component.
if (typeof module.hot === 'object') {
  module.hot.accept(err => {
    if (err) {
      console.error('Cannot apply HMR update.', err);
    }
  });
}
<commit_msg>fix: update Javascript to address merge conflict issue with previous PR merge / recent release<commit_after>import './utils/polyfills';
import './components/pl-nav/pl-nav';
import './components/pl-logo/pl-logo';
import './components/pl-layout/pl-layout';
import './components/pl-controls/pl-controls';
import './components/pl-drawer/pl-drawer';
import './components/pl-header/pl-header';
import './components/pl-viewport/pl-viewport';
import './components/pl-toggle-info/pl-toggle-info';
import './components/pl-toggle-layout/pl-toggle-layout';
import './components/pl-toggle-theme/pl-toggle-theme';
import './components/pl-tools-menu/pl-tools-menu';
import './components/pl-search/pl-search';

import(
  /* webpackChunkName: "pl-viewport-sizes" */
  /* webpackMode: "lazy" */
  /* webpackPrefetch: true */
  './components/pl-viewport-size-list/pl-viewport-size-list'
);

import(
  /* webpackChunkName: "pl-modal-viewer" */
  /* webpackMode: "lazy" */
  /* webpackPrefetch: true */
  './components/modal-viewer'
);

// Add hook to auto re-render the root component.
if (typeof module.hot === 'object') {
  module.hot.accept(err => {
    if (err) {
      console.error('Cannot apply HMR update.', err);
    }
  });
}
<|endoftext|>


<commit_before>define((require) => {

    describe('class_selector', () => {
        beforeEach(() => {
            require('app/views/teacher/modules/class_selector');
        });

        describe('>ClassSelectorInit_Teacher', () => {
            it('should be defined', () => {
                expect(ClassSelectorInit_Teacher).toBeDefined();
            });

            it('>should call sortClasses and set UpdateManagementButtons as an event listener for class_selector changing', () => {
                const mock_element = {
                    addEventListener: () => undefined
                };

                const spy_sortClasses = spyOn(window, 'sortClasses').and.returnValue(undefined);
                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_element);
                const spy_addEventListener = spyOn(mock_element, 'addEventListener').and.callThrough();

                expect(ClassSelectorInit_Teacher()).toBeUndefined();

                expect(spy_sortClasses.calls.count()).toEqual(1);
                expect(spy_sortClasses.calls.argsFor(0)).toEqual([]);

                expect(spy_querySelector.calls.count()).toEqual(1);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#class_selector']);

                expect(spy_addEventListener.calls.count()).toEqual(1);
                expect(spy_addEventListener.calls.argsFor(0)).toEqual(['change', UpdateManagementButtons]);
            });
        });

        describe('>UpdateManagementButtons', () => {
            it('should be defined', () => {
                expect(UpdateManagementButtons).toBeDefined()
            });

            it('should enable the buttons iff one class is selected', () => {
                const mock_button = {
                    removeAttribute: () => undefined,
                    setAttribute: () => undefined,
                    classList: {
                        remove: () => undefined,
                        add: () => undefined
                    }
                };

                const mock_link_element = {
                    setAttribute: () => undefined
                };

                const spy_getSelectedClassId = spyOn(window, 'getSelectedClassId').and.returnValue('selected_id');
                const spy_querySelectorAll = spyOn(document, 'querySelectorAll').and.returnValues(['one_option'], [mock_button, mock_button]);
                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_link_element);
                const spy_removeAttribute = spyOn(mock_button, 'removeAttribute').and.callThrough();
                const spy_setAttribute_button = spyOn(mock_button, 'setAttribute').and.callThrough();
                const spy_remove = spyOn(mock_button.classList, 'remove').and.callThrough();
                const spy_add = spyOn(mock_button.classList, 'add').and.callThrough();
                const spy_setAttribute_link = spyOn(mock_link_element, 'setAttribute').and.callThrough();

                expect(UpdateManagementButtons()).toBeUndefined();

                expect(spy_getSelectedClassId.calls.count()).toEqual(1);
                expect(spy_getSelectedClassId.calls.argsFor(0)).toEqual([]);

                expect(spy_querySelectorAll.calls.count()).toEqual(2);
                expect(spy_querySelectorAll.calls.argsFor(0)).toEqual(['#class_selector option:checked']);
                expect(spy_querySelectorAll.calls.argsFor(1)).toEqual(['.management_button']);

                expect(spy_querySelector.calls.count()).toEqual(2);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#ar_history_link']);
                expect(spy_querySelector.calls.argsFor(1)).toEqual(['#hp_history_link']);

                expect(spy_removeAttribute.calls.count()).toEqual(2);
                expect(spy_removeAttribute.calls.argsFor(0)).toEqual(['disabled']);
                expect(spy_removeAttribute.calls.argsFor(1)).toEqual(['disabled']);

                expect(spy_setAttribute_button.calls.count()).toEqual(0);

                expect(spy_remove.calls.count()).toEqual(2);
                expect(spy_remove.calls.argsFor(0)).toEqual(['disabled']);
                expect(spy_remove.calls.argsFor(1)).toEqual(['disabled']);

                expect(spy_add.calls.count()).toEqual(0);

                expect(spy_setAttribute_link.calls.count()).toEqual(2);
                expect(spy_setAttribute_link.calls.argsFor(0)).toEqual(['href', '/teacher/history/assistancerequest/selected_id']);
                expect(spy_setAttribute_link.calls.argsFor(1)).toEqual(['href', '/teacher/history/hallpass/selected_id']);
            });
        });

        describe('>UpdateManagementButtons', () => {
            it('should be defined', () => {
                expect(UpdateManagementButtons).toBeDefined()
            });

            it('should disable the buttons if no class is selected', () => {
                const mock_button = {
                    removeAttribute: () => undefined,
                    setAttribute: () => undefined,
                    classList: {
                        remove: () => undefined,
                        add: () => undefined
                    }
                };

                const mock_link_element = {
                    setAttribute: () => undefined
                };

                const spy_getSelectedClassId = spyOn(window, 'getSelectedClassId').and.returnValue('selected_id');
                const spy_querySelectorAll = spyOn(document, 'querySelectorAll').and.returnValues([/**no options selected */], [mock_button, mock_button]);
                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_link_element);
                const spy_removeAttribute = spyOn(mock_button, 'removeAttribute').and.callThrough();
                const spy_setAttribute_button = spyOn(mock_button, 'setAttribute').and.callThrough();
                const spy_remove = spyOn(mock_button.classList, 'remove').and.callThrough();
                const spy_add = spyOn(mock_button.classList, 'add').and.callThrough();
                const spy_setAttribute_link = spyOn(mock_link_element, 'setAttribute').and.callThrough();

                expect(UpdateManagementButtons()).toBeUndefined();

                expect(spy_getSelectedClassId.calls.count()).toEqual(0);

                expect(spy_querySelectorAll.calls.count()).toEqual(2);
                expect(spy_querySelectorAll.calls.argsFor(0)).toEqual(['#class_selector option:checked']);
                expect(spy_querySelectorAll.calls.argsFor(1)).toEqual(['.management_button']);

                expect(spy_querySelector.calls.count()).toEqual(2);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#ar_history_link']);
                expect(spy_querySelector.calls.argsFor(1)).toEqual(['#hp_history_link']);

                expect(spy_removeAttribute.calls.count()).toEqual(0);

                expect(spy_setAttribute_button.calls.count()).toEqual(2);
                expect(spy_setAttribute_button.calls.argsFor(0)).toEqual(['disabled', 'disabled']);
                expect(spy_setAttribute_button.calls.argsFor(1)).toEqual(['disabled', 'disabled']);

                expect(spy_remove.calls.count()).toEqual(0);

                expect(spy_add.calls.count()).toEqual(2);
                expect(spy_add.calls.argsFor(0)).toEqual(['disabled']);
                expect(spy_add.calls.argsFor(1)).toEqual(['disabled']);

                expect(spy_setAttribute_link.calls.count()).toEqual(2);
                expect(spy_setAttribute_link.calls.argsFor(0)).toEqual(['href', 'javascript:;']);
                expect(spy_setAttribute_link.calls.argsFor(1)).toEqual(['href', 'javascript:;']);
            });
        });

        describe('>UpdateManagementButtons', () => {
            it('should be defined', () => {
                expect(UpdateManagementButtons).toBeDefined()
            });

            it('should disable the buttons if more than one class is selected', () => {
                const mock_button = {
                    removeAttribute: () => undefined,
                    setAttribute: () => undefined,
                    classList: {
                        remove: () => undefined,
                        add: () => undefined
                    }
                };

                const mock_link_element = {
                    setAttribute: () => undefined
                };

                const spy_getSelectedClassId = spyOn(window, 'getSelectedClassId').and.returnValue('selected_id');
                const spy_querySelectorAll = spyOn(document, 'querySelectorAll').and.returnValues(['selection 1', 'selection 2'], [mock_button, mock_button]);
                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_link_element);
                const spy_removeAttribute = spyOn(mock_button, 'removeAttribute').and.callThrough();
                const spy_setAttribute_button = spyOn(mock_button, 'setAttribute').and.callThrough();
                const spy_remove = spyOn(mock_button.classList, 'remove').and.callThrough();
                const spy_add = spyOn(mock_button.classList, 'add').and.callThrough();
                const spy_setAttribute_link = spyOn(mock_link_element, 'setAttribute').and.callThrough();

                expect(UpdateManagementButtons()).toBeUndefined();

                expect(spy_getSelectedClassId.calls.count()).toEqual(0);

                expect(spy_querySelectorAll.calls.count()).toEqual(2);
                expect(spy_querySelectorAll.calls.argsFor(0)).toEqual(['#class_selector option:checked']);
                expect(spy_querySelectorAll.calls.argsFor(1)).toEqual(['.management_button']);

                expect(spy_querySelector.calls.count()).toEqual(2);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#ar_history_link']);
                expect(spy_querySelector.calls.argsFor(1)).toEqual(['#hp_history_link']);

                expect(spy_removeAttribute.calls.count()).toEqual(0);

                expect(spy_setAttribute_button.calls.count()).toEqual(2);
                expect(spy_setAttribute_button.calls.argsFor(0)).toEqual(['disabled', 'disabled']);
                expect(spy_setAttribute_button.calls.argsFor(1)).toEqual(['disabled', 'disabled']);

                expect(spy_remove.calls.count()).toEqual(0);

                expect(spy_add.calls.count()).toEqual(2);
                expect(spy_add.calls.argsFor(0)).toEqual(['disabled']);
                expect(spy_add.calls.argsFor(1)).toEqual(['disabled']);

                expect(spy_setAttribute_link.calls.count()).toEqual(2);
                expect(spy_setAttribute_link.calls.argsFor(0)).toEqual(['href', 'javascript:;']);
                expect(spy_setAttribute_link.calls.argsFor(1)).toEqual(['href', 'javascript:;']);
            });
        });

        describe('>AddClass', () => {
            it('should be defined', () => {
                expect(AddClass).toBeDefined();
            });

            it('should create a new option, append it to the select element, and call sortClasses', () => {
                const mock_element = {
                    appendChild: () => undefined
                };

                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_element);
                const spy_appendChild = spyOn(mock_element, 'appendChild').and.callThrough();
                const spy_sortClasses = spyOn(window, 'sortClasses').and.returnValue(undefined);

                expect(AddClass('test_id', 'test_name')).toBeUndefined();

                expect(spy_querySelector.calls.count()).toEqual(1);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#class_selector']);

                expect(spy_appendChild.calls.count()).toEqual(1);
                expect(spy_appendChild.calls.argsFor(0)).toEqual([new Option('test_name', 'test_id')]);

                expect(spy_sortClasses.calls.count()).toEqual(1);
                expect(spy_sortClasses.calls.argsFor(0)).toEqual([]);
            });
        });

        describe('>getSelectedClassIds', () => {
            it('should be defined', () => {
                expect(getSelectedClassId).toBeDefined();
            });

            [{options: [], expected: []},
             {options: [{'value': 'v1'}], expected: ['v1']},
             {options: [{'value': 'v1'}, {'value': 'v2', 'other_attr': 'v3'}], expected: ['v1', 'v2']}].forEach(testCase => {
                const {options, expected} = testCase;

                it('>should return the value of each of the selected options', () => {
                    const spy_querySelectorAll = spyOn(document, 'querySelectorAll').and.returnValue(options);

                    expect(getSelectedClassIds()).toEqual(expected);

                    expect(spy_querySelectorAll.calls.count()).toEqual(1);
                    expect(spy_querySelectorAll.calls.argsFor(0)).toEqual(['#class_selector option:checked']);
                });
             });
        });

        describe('>RemoveClass', () => {
            it('should be defined', () => {
                expect(RemoveClass).toBeDefined();
            });

            ['a', 'xyz'].forEach(id => {
                it('should find the option for the given id and remove it from the class selector', () => {
                    const mock_element = {
                        removeChild: () => undefined
                    };

                    const spy_querySelector = spyOn(document, 'querySelector').and.returnValues(`option_value${id}`, mock_element);
                    const spy_removeChild = spyOn(mock_element, 'removeChild').and.callThrough();

                    expect(RemoveClass(id)).toBeUndefined();

                    expect(spy_querySelector.calls.count()).toEqual(2);
                    expect(spy_querySelector.calls.argsFor(0)).toEqual([`option[value=${id}]`]);
                    expect(spy_querySelector.calls.argsFor(1)).toEqual(['#class_selector']);

                    expect(spy_removeChild.calls.count()).toEqual(1);
                    expect(spy_removeChild.calls.argsFor(0)).toEqual([`option_value${id}`]);
                });
            });
        });
    });
});<commit_msg>Test RenameClass<commit_after>define((require) => {

    describe('class_selector', () => {
        beforeEach(() => {
            require('app/views/teacher/modules/class_selector');
        });

        describe('>ClassSelectorInit_Teacher', () => {
            it('should be defined', () => {
                expect(ClassSelectorInit_Teacher).toBeDefined();
            });

            it('>should call sortClasses and set UpdateManagementButtons as an event listener for class_selector changing', () => {
                const mock_element = {
                    addEventListener: () => undefined
                };

                const spy_sortClasses = spyOn(window, 'sortClasses').and.returnValue(undefined);
                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_element);
                const spy_addEventListener = spyOn(mock_element, 'addEventListener').and.callThrough();

                expect(ClassSelectorInit_Teacher()).toBeUndefined();

                expect(spy_sortClasses.calls.count()).toEqual(1);
                expect(spy_sortClasses.calls.argsFor(0)).toEqual([]);

                expect(spy_querySelector.calls.count()).toEqual(1);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#class_selector']);

                expect(spy_addEventListener.calls.count()).toEqual(1);
                expect(spy_addEventListener.calls.argsFor(0)).toEqual(['change', UpdateManagementButtons]);
            });
        });

        describe('>UpdateManagementButtons', () => {
            it('should be defined', () => {
                expect(UpdateManagementButtons).toBeDefined()
            });

            it('should enable the buttons iff one class is selected', () => {
                const mock_button = {
                    removeAttribute: () => undefined,
                    setAttribute: () => undefined,
                    classList: {
                        remove: () => undefined,
                        add: () => undefined
                    }
                };

                const mock_link_element = {
                    setAttribute: () => undefined
                };

                const spy_getSelectedClassId = spyOn(window, 'getSelectedClassId').and.returnValue('selected_id');
                const spy_querySelectorAll = spyOn(document, 'querySelectorAll').and.returnValues(['one_option'], [mock_button, mock_button]);
                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_link_element);
                const spy_removeAttribute = spyOn(mock_button, 'removeAttribute').and.callThrough();
                const spy_setAttribute_button = spyOn(mock_button, 'setAttribute').and.callThrough();
                const spy_remove = spyOn(mock_button.classList, 'remove').and.callThrough();
                const spy_add = spyOn(mock_button.classList, 'add').and.callThrough();
                const spy_setAttribute_link = spyOn(mock_link_element, 'setAttribute').and.callThrough();

                expect(UpdateManagementButtons()).toBeUndefined();

                expect(spy_getSelectedClassId.calls.count()).toEqual(1);
                expect(spy_getSelectedClassId.calls.argsFor(0)).toEqual([]);

                expect(spy_querySelectorAll.calls.count()).toEqual(2);
                expect(spy_querySelectorAll.calls.argsFor(0)).toEqual(['#class_selector option:checked']);
                expect(spy_querySelectorAll.calls.argsFor(1)).toEqual(['.management_button']);

                expect(spy_querySelector.calls.count()).toEqual(2);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#ar_history_link']);
                expect(spy_querySelector.calls.argsFor(1)).toEqual(['#hp_history_link']);

                expect(spy_removeAttribute.calls.count()).toEqual(2);
                expect(spy_removeAttribute.calls.argsFor(0)).toEqual(['disabled']);
                expect(spy_removeAttribute.calls.argsFor(1)).toEqual(['disabled']);

                expect(spy_setAttribute_button.calls.count()).toEqual(0);

                expect(spy_remove.calls.count()).toEqual(2);
                expect(spy_remove.calls.argsFor(0)).toEqual(['disabled']);
                expect(spy_remove.calls.argsFor(1)).toEqual(['disabled']);

                expect(spy_add.calls.count()).toEqual(0);

                expect(spy_setAttribute_link.calls.count()).toEqual(2);
                expect(spy_setAttribute_link.calls.argsFor(0)).toEqual(['href', '/teacher/history/assistancerequest/selected_id']);
                expect(spy_setAttribute_link.calls.argsFor(1)).toEqual(['href', '/teacher/history/hallpass/selected_id']);
            });
        });

        describe('>UpdateManagementButtons', () => {
            it('should be defined', () => {
                expect(UpdateManagementButtons).toBeDefined()
            });

            it('should disable the buttons if no class is selected', () => {
                const mock_button = {
                    removeAttribute: () => undefined,
                    setAttribute: () => undefined,
                    classList: {
                        remove: () => undefined,
                        add: () => undefined
                    }
                };

                const mock_link_element = {
                    setAttribute: () => undefined
                };

                const spy_getSelectedClassId = spyOn(window, 'getSelectedClassId').and.returnValue('selected_id');
                const spy_querySelectorAll = spyOn(document, 'querySelectorAll').and.returnValues([/**no options selected */], [mock_button, mock_button]);
                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_link_element);
                const spy_removeAttribute = spyOn(mock_button, 'removeAttribute').and.callThrough();
                const spy_setAttribute_button = spyOn(mock_button, 'setAttribute').and.callThrough();
                const spy_remove = spyOn(mock_button.classList, 'remove').and.callThrough();
                const spy_add = spyOn(mock_button.classList, 'add').and.callThrough();
                const spy_setAttribute_link = spyOn(mock_link_element, 'setAttribute').and.callThrough();

                expect(UpdateManagementButtons()).toBeUndefined();

                expect(spy_getSelectedClassId.calls.count()).toEqual(0);

                expect(spy_querySelectorAll.calls.count()).toEqual(2);
                expect(spy_querySelectorAll.calls.argsFor(0)).toEqual(['#class_selector option:checked']);
                expect(spy_querySelectorAll.calls.argsFor(1)).toEqual(['.management_button']);

                expect(spy_querySelector.calls.count()).toEqual(2);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#ar_history_link']);
                expect(spy_querySelector.calls.argsFor(1)).toEqual(['#hp_history_link']);

                expect(spy_removeAttribute.calls.count()).toEqual(0);

                expect(spy_setAttribute_button.calls.count()).toEqual(2);
                expect(spy_setAttribute_button.calls.argsFor(0)).toEqual(['disabled', 'disabled']);
                expect(spy_setAttribute_button.calls.argsFor(1)).toEqual(['disabled', 'disabled']);

                expect(spy_remove.calls.count()).toEqual(0);

                expect(spy_add.calls.count()).toEqual(2);
                expect(spy_add.calls.argsFor(0)).toEqual(['disabled']);
                expect(spy_add.calls.argsFor(1)).toEqual(['disabled']);

                expect(spy_setAttribute_link.calls.count()).toEqual(2);
                expect(spy_setAttribute_link.calls.argsFor(0)).toEqual(['href', 'javascript:;']);
                expect(spy_setAttribute_link.calls.argsFor(1)).toEqual(['href', 'javascript:;']);
            });
        });

        describe('>UpdateManagementButtons', () => {
            it('should be defined', () => {
                expect(UpdateManagementButtons).toBeDefined()
            });

            it('should disable the buttons if more than one class is selected', () => {
                const mock_button = {
                    removeAttribute: () => undefined,
                    setAttribute: () => undefined,
                    classList: {
                        remove: () => undefined,
                        add: () => undefined
                    }
                };

                const mock_link_element = {
                    setAttribute: () => undefined
                };

                const spy_getSelectedClassId = spyOn(window, 'getSelectedClassId').and.returnValue('selected_id');
                const spy_querySelectorAll = spyOn(document, 'querySelectorAll').and.returnValues(['selection 1', 'selection 2'], [mock_button, mock_button]);
                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_link_element);
                const spy_removeAttribute = spyOn(mock_button, 'removeAttribute').and.callThrough();
                const spy_setAttribute_button = spyOn(mock_button, 'setAttribute').and.callThrough();
                const spy_remove = spyOn(mock_button.classList, 'remove').and.callThrough();
                const spy_add = spyOn(mock_button.classList, 'add').and.callThrough();
                const spy_setAttribute_link = spyOn(mock_link_element, 'setAttribute').and.callThrough();

                expect(UpdateManagementButtons()).toBeUndefined();

                expect(spy_getSelectedClassId.calls.count()).toEqual(0);

                expect(spy_querySelectorAll.calls.count()).toEqual(2);
                expect(spy_querySelectorAll.calls.argsFor(0)).toEqual(['#class_selector option:checked']);
                expect(spy_querySelectorAll.calls.argsFor(1)).toEqual(['.management_button']);

                expect(spy_querySelector.calls.count()).toEqual(2);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#ar_history_link']);
                expect(spy_querySelector.calls.argsFor(1)).toEqual(['#hp_history_link']);

                expect(spy_removeAttribute.calls.count()).toEqual(0);

                expect(spy_setAttribute_button.calls.count()).toEqual(2);
                expect(spy_setAttribute_button.calls.argsFor(0)).toEqual(['disabled', 'disabled']);
                expect(spy_setAttribute_button.calls.argsFor(1)).toEqual(['disabled', 'disabled']);

                expect(spy_remove.calls.count()).toEqual(0);

                expect(spy_add.calls.count()).toEqual(2);
                expect(spy_add.calls.argsFor(0)).toEqual(['disabled']);
                expect(spy_add.calls.argsFor(1)).toEqual(['disabled']);

                expect(spy_setAttribute_link.calls.count()).toEqual(2);
                expect(spy_setAttribute_link.calls.argsFor(0)).toEqual(['href', 'javascript:;']);
                expect(spy_setAttribute_link.calls.argsFor(1)).toEqual(['href', 'javascript:;']);
            });
        });

        describe('>AddClass', () => {
            it('should be defined', () => {
                expect(AddClass).toBeDefined();
            });

            it('should create a new option, append it to the select element, and call sortClasses', () => {
                const mock_element = {
                    appendChild: () => undefined
                };

                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_element);
                const spy_appendChild = spyOn(mock_element, 'appendChild').and.callThrough();
                const spy_sortClasses = spyOn(window, 'sortClasses').and.returnValue(undefined);

                expect(AddClass('test_id', 'test_name')).toBeUndefined();

                expect(spy_querySelector.calls.count()).toEqual(1);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['#class_selector']);

                expect(spy_appendChild.calls.count()).toEqual(1);
                expect(spy_appendChild.calls.argsFor(0)).toEqual([new Option('test_name', 'test_id')]);

                expect(spy_sortClasses.calls.count()).toEqual(1);
                expect(spy_sortClasses.calls.argsFor(0)).toEqual([]);
            });
        });

        describe('>getSelectedClassIds', () => {
            it('should be defined', () => {
                expect(getSelectedClassId).toBeDefined();
            });

            [{options: [], expected: []},
             {options: [{'value': 'v1'}], expected: ['v1']},
             {options: [{'value': 'v1'}, {'value': 'v2', 'other_attr': 'v3'}], expected: ['v1', 'v2']}].forEach(testCase => {
                const {options, expected} = testCase;

                it('>should return the value of each of the selected options', () => {
                    const spy_querySelectorAll = spyOn(document, 'querySelectorAll').and.returnValue(options);

                    expect(getSelectedClassIds()).toEqual(expected);

                    expect(spy_querySelectorAll.calls.count()).toEqual(1);
                    expect(spy_querySelectorAll.calls.argsFor(0)).toEqual(['#class_selector option:checked']);
                });
             });
        });

        describe('>RemoveClass', () => {
            it('should be defined', () => {
                expect(RemoveClass).toBeDefined();
            });

            ['a', 'xyz'].forEach(id => {
                it('should find the option for the given id and remove it from the class selector', () => {
                    const mock_element = {
                        removeChild: () => undefined
                    };

                    const spy_querySelector = spyOn(document, 'querySelector').and.returnValues(`option_value${id}`, mock_element);
                    const spy_removeChild = spyOn(mock_element, 'removeChild').and.callThrough();

                    expect(RemoveClass(id)).toBeUndefined();

                    expect(spy_querySelector.calls.count()).toEqual(2);
                    expect(spy_querySelector.calls.argsFor(0)).toEqual([`option[value=${id}]`]);
                    expect(spy_querySelector.calls.argsFor(1)).toEqual(['#class_selector']);

                    expect(spy_removeChild.calls.count()).toEqual(1);
                    expect(spy_removeChild.calls.argsFor(0)).toEqual([`option_value${id}`]);
                });
            });
        });

        describe('>RenameClass', () => {
            it('should be defined', () => {
                expect(RenameClass).toBeDefined();
            });

            it('should update the corresponding option\'s text, sort the classes, and update the management buttons', () => {
                const mock_element = {innerHTML: 'original_name'};

                const spy_querySelector = spyOn(document, 'querySelector').and.returnValue(mock_element);

                const spy_sortClasses = jasmine.createSpy('sortClasses').and.stub();
                const spy_UpdateManagementButtons = jasmine.createSpy('UpdateManagementButtons').and.stub();

                const original_sortClasses = sortClasses;
                const original_UpdateManagementButtons = UpdateManagementButtons;

                sortClasses = spy_sortClasses;
                UpdateManagementButtons = spy_UpdateManagementButtons;

                expect(RenameClass('test_id', 'test_name')).toBeUndefined();

                expect(spy_querySelector.calls.count()).toEqual(1);
                expect(spy_querySelector.calls.argsFor(0)).toEqual(['option[value=test_id]']);

                expect(spy_sortClasses.calls.count()).toEqual(1);
                expect(spy_sortClasses.calls.argsFor(0)).toEqual([]);

                expect(spy_UpdateManagementButtons.calls.count()).toEqual(1);
                expect(spy_UpdateManagementButtons.calls.argsFor(0)).toEqual([]);

                expect(mock_element.innerHTML).toEqual('test_name');

                sortClasses = original_sortClasses;
                UpdateManagementButtons = original_UpdateManagementButtons;
            });
        });
    });
});<|endoftext|>


<commit_before>'use strict';

var includes         = require('es5-ext/array/#/contains')
  , assign           = require('es5-ext/object/assign')
  , ensureObject     = require('es5-ext/object/valid-object')
  , ensureCallable   = require('es5-ext/object/valid-callable')
  , deferred         = require('deferred')
  , memoize          = require('memoizee')
  , ensureDatabase   = require('dbjs/valid-dbjs')
  , unserializeValue = require('dbjs/_setup/unserialize/value')
  , ensureDriver     = require('dbjs-persistence/ensure-driver')
  , getData          = require('./map');

var getProcessorAndProcessingTime = memoize(function (data) {
	var result = {};
	return deferred(
		data.storage.get(data.id + '/' + data.stepFullPath + '/processor')(
			function (processorData) {
				if (!processorData || processorData.value[0] !== '7') return;
				result.processor = processorData.value.slice(1);
			}
		),
		data.storage.get(data.id + '/' + data.stepFullPath + '/correctionTime')(
			function (correctionTimeData) {
				if (!correctionTimeData || correctionTimeData.value[0] !== '2') return;
				result.correctionTime =
					unserializeValue(correctionTimeData.value);
			}
		),
		data.storage.get(data.id + '/' + data.stepFullPath + '/processingTime')(
			function (processingTimeData) {
				if (!processingTimeData || processingTimeData.value[0] !== '2') return;
				result.processingTime =
					unserializeValue(processingTimeData.value);
			}
		)
	)(result);
}, {
	normalizer: function (args) { return args[0].id + args[0].stepFullPath; },
	// One hour
	maxAge: 1000 * 60 * 60
});
/**
	*
	* @param data
	* driver                  - Database driver
	* processingStepsMeta     - map of processing steps
	* db                      - dbjs database
	* query (optional)        - query past from controller
	* customFilter (optional) - function used to filter by system specific parameters
	* @returns {Object}
*/
module.exports = function (data) {
	var driver = ensureDriver(ensureObject(data).driver)
	  , processingStepsMeta = ensureObject(data.processingStepsMeta)
	  , db = ensureDatabase(data.db)
	  , query = data.query || {}
	  , customFilter = data.customFilter ? ensureCallable(data.customFilter) : null;

	var result = {};

	// 1. Get data for all processing steps from all services
	return getData(driver, processingStepsMeta, db)(function (businessProcessesByStepsMap) {
		return deferred.map(Object.keys(businessProcessesByStepsMap), function (stepShortPath) {
			var entries = businessProcessesByStepsMap[stepShortPath];

			// 2. Filter by step
			if (query.step && query.step !== stepShortPath) return;

			// 3. Filter by service
			if (query.service) {
				if (!includes.call(processingStepsMeta[stepShortPath]._services, query.service)) {
					return;
				}
				if (processingStepsMeta[stepShortPath]._services.length > 1) {
					entries = businessProcessesByStepsMap[stepShortPath].filter(function (entry) {
						return entry.serviceName === query.service;
					});
				}
			}
			if (!entries.length) return;

			// 4. Filter by date range
			if (query.dateFrom) {
				entries = entries.filter(function (data) {
					return data.date >= query.dateFrom;
				});
			}
			if (query.dateTo) {
				entries = entries.filter(function (data) {
					return data.date <= query.dateTo;
				});
			}

			// 5. Custom filter
			if (customFilter) {
				entries = deferred.map(entries, function (entry) {
					return customFilter(entry, query)(function (isOK) { return isOK ? entry : null; });
				}).invoke('filter', Boolean);
			}
			return deferred(entries)(function (filteredEntries) {
				entries = filteredEntries;

				// 6. Get extra data for each entry
				return deferred.map(entries, function (data) {
					return getProcessorAndProcessingTime(data)(function (result) {
						assign(data, result);
					});
				});
			})(function () { result[stepShortPath] = entries; });
		});
	})(result);
};
<commit_msg>Cleanup after update to map.js<commit_after>'use strict';

var includes         = require('es5-ext/array/#/contains')
  , assign           = require('es5-ext/object/assign')
  , ensureObject     = require('es5-ext/object/valid-object')
  , ensureCallable   = require('es5-ext/object/valid-callable')
  , deferred         = require('deferred')
  , memoize          = require('memoizee')
  , ensureDatabase   = require('dbjs/valid-dbjs')
  , unserializeValue = require('dbjs/_setup/unserialize/value')
  , ensureDriver     = require('dbjs-persistence/ensure-driver')
  , getData          = require('./map');

var getProcessorAndProcessingTime = memoize(function (data) {
	var result = {};
	return deferred(
		data.storage.get(data.id + '/' + data.stepFullPath + '/processor')(
			function (processorData) {
				if (!processorData || processorData.value[0] !== '7') return;
				result.processor = processorData.value.slice(1);
			}
		),
		data.storage.get(data.id + '/' + data.stepFullPath + '/correctionTime')(
			function (correctionTimeData) {
				if (!correctionTimeData || correctionTimeData.value[0] !== '2') return;
				result.correctionTime =
					unserializeValue(correctionTimeData.value);
			}
		),
		data.storage.get(data.id + '/' + data.stepFullPath + '/processingTime')(
			function (processingTimeData) {
				if (!processingTimeData || processingTimeData.value[0] !== '2') return;
				result.processingTime =
					unserializeValue(processingTimeData.value);
			}
		)
	)(result);
}, {
	normalizer: function (args) { return args[0].id + args[0].stepFullPath; },
	// One hour
	maxAge: 1000 * 60 * 60
});
/**
	*
	* @param data
	* driver                  - Database driver
	* processingStepsMeta     - map of processing steps
	* db                      - dbjs database
	* query (optional)        - query past from controller
	* customFilter (optional) - function used to filter by system specific parameters
	* @returns {Object}
*/
module.exports = function (data) {
	var driver = ensureDriver(ensureObject(data).driver)
	  , processingStepsMeta = ensureObject(data.processingStepsMeta)
	  , query = data.query || {}
	  , customFilter = data.customFilter ? ensureCallable(data.customFilter) : null;

	var result = {};

	// 1. Get data for all processing steps from all services
	return getData(driver, processingStepsMeta)(function (businessProcessesByStepsMap) {
		return deferred.map(Object.keys(businessProcessesByStepsMap), function (stepShortPath) {
			var entries = businessProcessesByStepsMap[stepShortPath];

			// 2. Filter by step
			if (query.step && query.step !== stepShortPath) return;

			// 3. Filter by service
			if (query.service) {
				if (!includes.call(processingStepsMeta[stepShortPath]._services, query.service)) {
					return;
				}
				if (processingStepsMeta[stepShortPath]._services.length > 1) {
					entries = businessProcessesByStepsMap[stepShortPath].filter(function (entry) {
						return entry.serviceName === query.service;
					});
				}
			}
			if (!entries.length) return;

			// 4. Filter by date range
			if (query.dateFrom) {
				entries = entries.filter(function (data) {
					return data.date >= query.dateFrom;
				});
			}
			if (query.dateTo) {
				entries = entries.filter(function (data) {
					return data.date <= query.dateTo;
				});
			}

			// 5. Custom filter
			if (customFilter) {
				entries = deferred.map(entries, function (entry) {
					return customFilter(entry, query)(function (isOK) { return isOK ? entry : null; });
				}).invoke('filter', Boolean);
			}
			return deferred(entries)(function (filteredEntries) {
				entries = filteredEntries;

				// 6. Get extra data for each entry
				return deferred.map(entries, function (data) {
					return getProcessorAndProcessingTime(data)(function (result) {
						assign(data, result);
					});
				});
			})(function () { result[stepShortPath] = entries; });
		});
	})(result);
};
<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>Practice more to test.<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<|endoftext|>