<commit_before>/*

	tdapp.js

*/
var tdapp = angular.module("tdapp",['satellizer','ngCookies']);

tdapp.config(function($authProvider) {
	$authProvider.baseUrl='/api/todos/';
	$authProvider.loginUrl='login';
	// Satellizer
	/*
	$authProvider.twitter({
		url: 'http://127.0.0.1:5000/auth/twitter', // Satellizer server component on localhost
		authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',
		redirectUri: window.location.origin,
		type: '1.0',
		popupOptions: { width: 495, height: 645 }
	});
	$authProvider.httpInterceptor = false,
	$authProvider.withCredentials = false;
	*/
})

/*
  Server ----------------------------------------
*/
var localserver = "http://localhost:3000/api/todos"; // JSON-Server ressource on localhost
var server = window.location.protocol + "/api/todos";

/*
  Misc ----------------------------------------
*/
var cookiename = "derdr";

/*
  Factories ----------------------------------------
*/
tdapp.factory("CLogger",function(){ // ClientLogger
	service = {};
	service._log = [];
	service.log = function(logtxt){
		service._log.push(logtxt);
		if(service._log.length>32){
			service._log.shift();
		}
	}
	service.getLog = function(){
		return service._log;
	}
	for(i=0;i<32;i++){
		service.log("");
	}
	return service;
});

tdapp.factory("TDMgr",function(){ // ToDoManager
	var service = {};
	service.todos = [];
	service.getTodos = function(){
		return service.todos;
	}
	service.setTodos = function(todolist){
		service.todos = todolist;
	}
	service.clearTodos = function(){
		while(service.todos.length>0){
			service.todos.pop();
		}
	}
	service.getTodoById = function(id){
		var ret = undefined;
		service.todos.forEach(function(obj){
			if(obj.id==id){
				ret = obj;
			}
		});
		return ret;
	}
	service.addTodoObj = function(obj){
		service.todos.unshift(obj);
	}
	service.delTodo = function(item){
		var idx = service.todos.indexOf(item)
		service.todos.splice(idx,1);
	}
	service.togDone = function(item){
		var idx = service.todos.indexOf(item);
		var todo = service.todos[idx];
		if(todo.done){
			todo.done = false;
		} else {
			todo.done = true;
		}
	}
	return service;
});

/*
  Main controller ----------------------------------------
*/
tdapp.controller("MainCtrl",function($scope,$timeout,$interval,$http,$auth,$cookies,TDMgr,CLogger){

	// Init

	$scope.todos = TDMgr.getTodos();
	$scope.log = CLogger.getLog();

	$scope.s_login = 1;
	$scope.s_working = 0;
	$scope.s_list = 0;

	// Communication with server

	function setHTTPDefaulHeader(token){
		$http.defaults.headers.common['auth-token'] = token;
	}

	function errorCallback(response) {
		CLogger.log("Error!");
		CLogger.log("Check browser console for details.");
		console.log(JSON.stringify(response));
	}

	function gettodos(){
		CLogger.log("Sending request (get) to server...");
		$scope.s_working = 1;
		$scope.s_list = 0;
		$http({
			method:"get",
			url: server
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
				CLogger.log("Updating local Todo-List.");
				response.data.forEach(function(o){
					TDMgr.addTodoObj(o);
				});
				CLogger.log("Done.");
				$timeout(function(){
					$scope.s_list = 1;
					$scope.s_working = 0;
				},1000);
				$timeout(function(){
					if(typeof window.orientation == 'undefined'){ // Workaround
						CLogger.log("Desktop browser detected.");
						CLogger.log("Focus New-Todo-Inputfield.");
						$("#todotxta").focus();
					}
				},1128);
			}
			,
			function(response) {
				CLogger.log("Error!");
				CLogger.log("Check browser console for details.");
				console.log(JSON.stringify(response));
				$scope.errormsg="Server not available!";
				$scope.dologout();
			}
		);
	}
	$scope.gettodos = gettodos;

	function posttodo(obj){
		CLogger.log("Sending request (post) to server...");
		$http({
			method:"post",
			url: server,
			header: "application/json",
			data: obj
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
				obj.id=response.data.id;
			}
			,
			errorCallback
		);
	}

	function puttodo(obj){
		CLogger.log("Sending request (put) to server...");
		$http({
			method:"put",
			url: server+"/"+obj.id,
			header: "application/json",
			data: obj
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
			}
			,
			errorCallback
		);
	}

	function deletetodo(obj){
		CLogger.log("Sending request (delete) to server...");
		$http({
			method:"delete",
			url: server+"/"+obj.id,
			header: "application/json",
			data: obj
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
			}
			,
			errorCallback
		);
	}

	function donetodo(obj){
		CLogger.log("Sending request (get; todo is done) to server...");
		$http({
			method:"get",
			url: server+"/"+obj.id+"/done",
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
			}
			,
			errorCallback
		);
	}

	// Satellizer

	$scope.authenticate = function(provider){
		$auth.authenticate(provider)
		.then(function(res){
			if($auth.isAuthenticated){
				var dtok = jwt_decode(res.data.token);
				$scope.user = {};
				$scope.user.id = dtok.sub;
			}
		});
	};

	// Keyboard functions

	$scope.mainKeydown = function(e){
		var k = e.keyCode;
		if(k==27){//esc
			e.preventDefault();
			CLogger.log("Commit logout.");
			$scope.dologout();
		}
	}

	$scope.newtodoKeydown = function(e){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			if($scope.newtodotxt!=""){
				var newtodo = {};
				newtodo.topic=$scope.newtodotxt;
				newtodo.done=false;
				$scope.newtodotxt = "";
				posttodo(newtodo);
				TDMgr.addTodoObj(newtodo);
				window.scrollTo(0,0);
				$("#todotxta").focus();
			}
		} else
		if(k==9){//tab
			e.preventDefault();
		}
	}

	$scope.todolineKeydown = function(e,id){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			CLogger.log("Change Todo (id:"+id+").");
			var currentTodo = $('#todoid'+id);
			currentTodo.blur();
			CLogger.log("Todo unfocused.");
			var obj = TDMgr.getTodoById(id);
			if(obj!=undefined){
				CLogger.log("Done.");
				CLogger.log("Updating data on server.");
				obj.topic = currentTodo.html();
				puttodo(obj);
				CLogger.log("Todo (id:"+id+") updated.");
			} else {
				CLogger.log("Error.");
			}
		}
	}

	$scope.loginKeydown = function(e){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			$scope.dologin();
		}
	}

	// Todo functions

	$scope.seltodoline = function(id){
		$("#todoid"+id).focus();
		CLogger.log("Todo focused.");
	}

	$scope.deltodonow = function(obj){
		obj.deleted = true;
		deletetodo(obj);
		TDMgr.delTodo(obj);
		CLogger.log("ToDo deleted.");
	}

	$scope.deltodo = function(obj){
		//Just some animated testings (wip)
		obj.opac = 1;
		obj.del = false;
		$interval(function(){
			var x = $("#todox"+obj.id);
			obj.opac = obj.opac - 0.05;
			x.css("opacity",obj.opac);
			if(obj.opac<=0 && !obj.deleted){
				obj.deleted = true;
				deletetodo(obj);
				TDMgr.delTodo(obj);
				CLogger.log("ToDo deleted.");
				$timeout(function(){
					$("#todotxta").focus();
				},128);
			}
		},32,32);
		if(TDMgr.getTodos().length==0){
			CLogger.log("Todo-List is empty.");
		}
	}

	$scope.togDone = function(obj){
		TDMgr.togDone(obj);
		donetodo(obj);
		CLogger.log("Todo-Flag changed.");
	}

	$scope.newtodofromconst = function(){
		if($scope.newtodotxt!=undefined){
			if($scope.newtodotxt!=""){
				var newtodo = {};
				newtodo.topic=$scope.newtodotxt;
				newtodo.done=false;
				$scope.newtodotxt = "";
				posttodo(newtodo);
				TDMgr.addTodoObj(newtodo);
				window.scrollTo(0,0);
			}
		}
	}

	// Login & Logout functions

	function logout(){
		$scope.s_login = 0;
		$scope.s_list = 0;
		$scope.s_working = 1;
		TDMgr.clearTodos();
		$timeout(function(){
			$scope.s_working = 0;
			$scope.s_login = 1;
		},1000);
		$timeout(function(){
			$("#liusername").focus();
		},1128);
		CLogger.log("Logged out.");
	}
	$scope.dologout = logout;

	function login(){
		CLogger.log("Commit login.");
		$auth.login($scope.user)
			.then(function(response){
				$cookies.put(cookiename,response.token);
				CLogger.log("Logged in.");
				$scope.errormsg = "";
				$scope.s_login = 0;
				gettodos();
			})
			.catch(function(error){
				$scope.errormsg = "Login-Error.";
				$scope.dologout();
			});
	}
	function locallogin(){ // No basic authentication (for communication with localhost)
		CLogger.log("Commit login.");
		server = localserver;
		$scope.errormsg = "";
		$scope.s_login = 0;
		CLogger.log("Logged in.");
		gettodos();
	}
	$scope.dologin = login; // Change to "locallogin" for working against localhost

	// Finish

	$(".flash").css("visibility","visible");
	$(".working").css("visibility","visible");
	$(".fkts").css("visibility","visible");
	$(".todota").css("visibility","visible");
	$(".todotab").css("visibility","visible");
	$("#liusername").focus()

	CLogger.log("System ready.");

	// Do login if cookie/token is available (WIP)
	console.log("Checking token-based access to backend...");
	var token = $cookies.get(cookiename);
	if (token!=undefined){
		setHTTPDefaulHeader(token);
		$http({
			method:"get",
			url: server
		}).then(
			function successCallback(response) {
				console.log("Token-based access to backend is possible");
			}
			,
			function(response) {
				console.log("Token-based access to backend is not possible");
			}
		);
	} else {
		console.log("No token available.");
	}

});
<commit_msg>Checking the login response.<commit_after>/*

	tdapp.js

*/
var tdapp = angular.module("tdapp",['satellizer','ngCookies']);

tdapp.config(function($authProvider) {
	$authProvider.baseUrl='/api/todos/';
	$authProvider.loginUrl='login';
	// Satellizer
	/*
	$authProvider.twitter({
		url: 'http://127.0.0.1:5000/auth/twitter', // Satellizer server component on localhost
		authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',
		redirectUri: window.location.origin,
		type: '1.0',
		popupOptions: { width: 495, height: 645 }
	});
	$authProvider.httpInterceptor = false,
	$authProvider.withCredentials = false;
	*/
})

/*
  Server ----------------------------------------
*/
var localserver = "http://localhost:3000/api/todos"; // JSON-Server ressource on localhost
var server = window.location.protocol + "/api/todos";

/*
  Misc ----------------------------------------
*/
var cookiename = "derdr";

/*
  Factories ----------------------------------------
*/
tdapp.factory("CLogger",function(){ // ClientLogger
	service = {};
	service._log = [];
	service.log = function(logtxt){
		service._log.push(logtxt);
		if(service._log.length>32){
			service._log.shift();
		}
	}
	service.getLog = function(){
		return service._log;
	}
	for(i=0;i<32;i++){
		service.log("");
	}
	return service;
});

tdapp.factory("TDMgr",function(){ // ToDoManager
	var service = {};
	service.todos = [];
	service.getTodos = function(){
		return service.todos;
	}
	service.setTodos = function(todolist){
		service.todos = todolist;
	}
	service.clearTodos = function(){
		while(service.todos.length>0){
			service.todos.pop();
		}
	}
	service.getTodoById = function(id){
		var ret = undefined;
		service.todos.forEach(function(obj){
			if(obj.id==id){
				ret = obj;
			}
		});
		return ret;
	}
	service.addTodoObj = function(obj){
		service.todos.unshift(obj);
	}
	service.delTodo = function(item){
		var idx = service.todos.indexOf(item)
		service.todos.splice(idx,1);
	}
	service.togDone = function(item){
		var idx = service.todos.indexOf(item);
		var todo = service.todos[idx];
		if(todo.done){
			todo.done = false;
		} else {
			todo.done = true;
		}
	}
	return service;
});

/*
  Main controller ----------------------------------------
*/
tdapp.controller("MainCtrl",function($scope,$timeout,$interval,$http,$auth,$cookies,TDMgr,CLogger){

	// Init

	$scope.todos = TDMgr.getTodos();
	$scope.log = CLogger.getLog();

	$scope.s_login = 1;
	$scope.s_working = 0;
	$scope.s_list = 0;

	// Communication with server

	function setHTTPDefaulHeader(token){
		$http.defaults.headers.common['auth-token'] = token;
	}

	function errorCallback(response) {
		CLogger.log("Error!");
		CLogger.log("Check browser console for details.");
		console.log(JSON.stringify(response));
	}

	function gettodos(){
		CLogger.log("Sending request (get) to server...");
		$scope.s_working = 1;
		$scope.s_list = 0;
		$http({
			method:"get",
			url: server
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
				CLogger.log("Updating local Todo-List.");
				response.data.forEach(function(o){
					TDMgr.addTodoObj(o);
				});
				CLogger.log("Done.");
				$timeout(function(){
					$scope.s_list = 1;
					$scope.s_working = 0;
				},1000);
				$timeout(function(){
					if(typeof window.orientation == 'undefined'){ // Workaround
						CLogger.log("Desktop browser detected.");
						CLogger.log("Focus New-Todo-Inputfield.");
						$("#todotxta").focus();
					}
				},1128);
			}
			,
			function(response) {
				CLogger.log("Error!");
				CLogger.log("Check browser console for details.");
				console.log(JSON.stringify(response));
				$scope.errormsg="Server not available!";
				$scope.dologout();
			}
		);
	}
	$scope.gettodos = gettodos;

	function posttodo(obj){
		CLogger.log("Sending request (post) to server...");
		$http({
			method:"post",
			url: server,
			header: "application/json",
			data: obj
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
				obj.id=response.data.id;
			}
			,
			errorCallback
		);
	}

	function puttodo(obj){
		CLogger.log("Sending request (put) to server...");
		$http({
			method:"put",
			url: server+"/"+obj.id,
			header: "application/json",
			data: obj
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
			}
			,
			errorCallback
		);
	}

	function deletetodo(obj){
		CLogger.log("Sending request (delete) to server...");
		$http({
			method:"delete",
			url: server+"/"+obj.id,
			header: "application/json",
			data: obj
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
			}
			,
			errorCallback
		);
	}

	function donetodo(obj){
		CLogger.log("Sending request (get; todo is done) to server...");
		$http({
			method:"get",
			url: server+"/"+obj.id+"/done",
		}).then(
			function successCallback(response) {
				CLogger.log("Done.");
			}
			,
			errorCallback
		);
	}

	// Satellizer

	$scope.authenticate = function(provider){
		$auth.authenticate(provider)
		.then(function(res){
			if($auth.isAuthenticated){
				var dtok = jwt_decode(res.data.token);
				$scope.user = {};
				$scope.user.id = dtok.sub;
			}
		});
	};

	// Keyboard functions

	$scope.mainKeydown = function(e){
		var k = e.keyCode;
		if(k==27){//esc
			e.preventDefault();
			CLogger.log("Commit logout.");
			$scope.dologout();
		}
	}

	$scope.newtodoKeydown = function(e){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			if($scope.newtodotxt!=""){
				var newtodo = {};
				newtodo.topic=$scope.newtodotxt;
				newtodo.done=false;
				$scope.newtodotxt = "";
				posttodo(newtodo);
				TDMgr.addTodoObj(newtodo);
				window.scrollTo(0,0);
				$("#todotxta").focus();
			}
		} else
		if(k==9){//tab
			e.preventDefault();
		}
	}

	$scope.todolineKeydown = function(e,id){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			CLogger.log("Change Todo (id:"+id+").");
			var currentTodo = $('#todoid'+id);
			currentTodo.blur();
			CLogger.log("Todo unfocused.");
			var obj = TDMgr.getTodoById(id);
			if(obj!=undefined){
				CLogger.log("Done.");
				CLogger.log("Updating data on server.");
				obj.topic = currentTodo.html();
				puttodo(obj);
				CLogger.log("Todo (id:"+id+") updated.");
			} else {
				CLogger.log("Error.");
			}
		}
	}

	$scope.loginKeydown = function(e){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			$scope.dologin();
		}
	}

	// Todo functions

	$scope.seltodoline = function(id){
		$("#todoid"+id).focus();
		CLogger.log("Todo focused.");
	}

	$scope.deltodonow = function(obj){
		obj.deleted = true;
		deletetodo(obj);
		TDMgr.delTodo(obj);
		CLogger.log("ToDo deleted.");
	}

	$scope.deltodo = function(obj){
		//Just some animated testings (wip)
		obj.opac = 1;
		obj.del = false;
		$interval(function(){
			var x = $("#todox"+obj.id);
			obj.opac = obj.opac - 0.05;
			x.css("opacity",obj.opac);
			if(obj.opac<=0 && !obj.deleted){
				obj.deleted = true;
				deletetodo(obj);
				TDMgr.delTodo(obj);
				CLogger.log("ToDo deleted.");
				$timeout(function(){
					$("#todotxta").focus();
				},128);
			}
		},32,32);
		if(TDMgr.getTodos().length==0){
			CLogger.log("Todo-List is empty.");
		}
	}

	$scope.togDone = function(obj){
		TDMgr.togDone(obj);
		donetodo(obj);
		CLogger.log("Todo-Flag changed.");
	}

	$scope.newtodofromconst = function(){
		if($scope.newtodotxt!=undefined){
			if($scope.newtodotxt!=""){
				var newtodo = {};
				newtodo.topic=$scope.newtodotxt;
				newtodo.done=false;
				$scope.newtodotxt = "";
				posttodo(newtodo);
				TDMgr.addTodoObj(newtodo);
				window.scrollTo(0,0);
			}
		}
	}

	// Login & Logout functions

	function logout(){
		$scope.s_login = 0;
		$scope.s_list = 0;
		$scope.s_working = 1;
		TDMgr.clearTodos();
		$timeout(function(){
			$scope.s_working = 0;
			$scope.s_login = 1;
		},1000);
		$timeout(function(){
			$("#liusername").focus();
		},1128);
		CLogger.log("Logged out.");
	}
	$scope.dologout = logout;

	function login(){
		CLogger.log("Commit login.");
		$auth.login($scope.user)
			.then(function(response){
				console.log(response);
				//$cookies.put(cookiename,response.data.token);
				CLogger.log("Logged in.");
				$scope.errormsg = "";
				$scope.s_login = 0;
				gettodos();
			})
			.catch(function(error){
				$scope.errormsg = "Login-Error.";
				$scope.dologout();
			});
	}
	function locallogin(){ // No basic authentication (for communication with localhost)
		CLogger.log("Commit login.");
		server = localserver;
		$scope.errormsg = "";
		$scope.s_login = 0;
		CLogger.log("Logged in.");
		gettodos();
	}
	$scope.dologin = login; // Change to "locallogin" for working against localhost

	// Finish

	$(".flash").css("visibility","visible");
	$(".working").css("visibility","visible");
	$(".fkts").css("visibility","visible");
	$(".todota").css("visibility","visible");
	$(".todotab").css("visibility","visible");
	$("#liusername").focus()

	CLogger.log("System ready.");

	// Do login if cookie/token is available (WIP)
	console.log("Checking token-based access to backend...");
	var token = $cookies.get(cookiename);
	if (token!=undefined){
		setHTTPDefaulHeader(token);
		$http({
			method:"get",
			url: server
		}).then(
			function successCallback(response) {
				console.log("Token-based access to backend is possible");
			}
			,
			function(response) {
				console.log("Token-based access to backend is not possible");
			}
		);
	} else {
		console.log("No token available.");
	}

});
<|endoftext|>


<commit_before>define([
    'flight/lib/component'
], function(defineComponent) {
    'use strict';

    var PRIVILEGES = 'COMMENT EDIT PUBLISH ADMIN'.split(' '),
        Component = defineComponent(Privileges);

    return Component;

    function Privileges() {

        this.workspaceEditable = false;

        this.after('initialize', function() {
            this.workspaceEditable = true;
            this.on('workspaceLoaded', this.onWorkspaceLoaded);
            this.update();
        });

        this.onWorkspaceLoaded = function(event, workspace) {
            this.workspaceEditable = workspace.editable;
            this.workspaceCommentable = workspace.commentable;
            this.update();
        };

        this.update = function() {
            var user = lumifyData.currentUser,
                editable = this.workspaceEditable,
                commentable = this.workspaceCommentable,
                cls = [];

            if (user) {
                $.extend(user, {
                    privilegesHelper: _.indexBy(user.privileges || [])
                });
            }
            PRIVILEGES.forEach(function(p) {
                var missingKey = 'missing' + p;

                if (p === 'ADMIN') {
                    Component[missingKey] = !user || !user.privilegesHelper[p];
                } else if (p === 'COMMENT') {
                    Component[missingKey] = !user || !user.privilegesHelper[p] || !commentable;
                } else {
                    Component[missingKey] = !user || !user.privilegesHelper[p] || !editable;
                }
                Component['can' + p] = !Component[missingKey];

                if (Component[missingKey]) {
                    cls.push('no-privilege-' + p);
                }
            });

            $('html').removePrefixedClasses('no-privilege-').addClass(cls.join(' '));
        };

    }
});
<commit_msg>Fix workspace not changing from readonly to editable until refresh<commit_after>define([
    'flight/lib/component'
], function(defineComponent) {
    'use strict';

    var PRIVILEGES = 'COMMENT EDIT PUBLISH ADMIN'.split(' '),
        Component = defineComponent(Privileges);

    return Component;

    function Privileges() {

        this.workspaceEditable = false;

        this.after('initialize', function() {
            this.workspaceEditable = true;
            this.on('workspaceLoaded', this.onWorkspaceLoaded);
            this.on('workspaceUpdated', this.onWorkspaceUpdated);
            this.update();
        });

        this.onWorkspaceUpdated = function(event, data) {
            var workspace = data.workspace;
            this.workspaceEditable = workspace.editable;
            this.workspaceCommentable = workspace.commentable;
            this.update();
        };

        this.onWorkspaceLoaded = function(event, workspace) {
            this.workspaceEditable = workspace.editable;
            this.workspaceCommentable = workspace.commentable;
            this.update();
        };

        this.update = function() {
            var user = lumifyData.currentUser,
                editable = this.workspaceEditable,
                commentable = this.workspaceCommentable,
                cls = [];

            if (user) {
                $.extend(user, {
                    privilegesHelper: _.indexBy(user.privileges || [])
                });
            }
            PRIVILEGES.forEach(function(p) {
                var missingKey = 'missing' + p;

                if (p === 'ADMIN') {
                    Component[missingKey] = !user || !user.privilegesHelper[p];
                } else if (p === 'COMMENT') {
                    Component[missingKey] = !user || !user.privilegesHelper[p] || !commentable;
                } else {
                    Component[missingKey] = !user || !user.privilegesHelper[p] || !editable;
                }
                Component['can' + p] = !Component[missingKey];

                if (Component[missingKey]) {
                    cls.push('no-privilege-' + p);
                }
            });

            $('html').removePrefixedClasses('no-privilege-').addClass(cls.join(' '));
        };

    }
});
<|endoftext|>


<commit_before>/*global describe, it, before, after, beforeEach, afterEach */
'use strict';
var path = require('path');
var fs = require('fs');
var assert = require('assert');
var shell = require('shelljs');
var sinon = require('sinon');
var Storage = require('../lib/util/storage');

describe('Storage', function () {
  beforeEach(function () {
    this.beforeDir = process.cwd();
    this.storePath = path.join(shell.tempdir(), 'new-config.json');
    this.store = new Storage('test', this.storePath);
    this.store.set('foo', 'bar');
    this.saveSpy = sinon.spy(this.store, 'save');
  });

  afterEach(function () {
    shell.rm('-f', this.storePath);
    process.chdir(this.beforeDir);
    this.saveSpy.restore();
  });

  describe('.constructor()', function () {
    it('require a name parameter', function () {
      assert.throws(function () { new Storage(); });
    });

    it('take a path parameter', function () {
      var store = new Storage('test', path.join(__dirname, './fixtures/config.json'));
      assert.equal(store.get('testFramework'), 'mocha');
      assert.ok(store.existed);
    });
  });

  it('namespace each store sharing the same store file', function () {
    var store = new Storage('foobar', this.storePath);
    store.set('foo', 'something else');
    assert.ok(this.store.get('foo') === 'bar');
  });

  it('defaults store path to `.yo-rc.json`', function (done) {
    var tmp = shell.tempdir();
    process.chdir(tmp);
    var store = new Storage('yo');

    store.on('save', function () {
      var fileContent = JSON.parse(fs.readFileSync(path.join(tmp, '.yo-rc.json')));
      assert.equal(fileContent.yo.foo, 'bar');
      done();
    });

    store.set('foo', 'bar');
  });

  describe('#get()', function () {
    beforeEach(function () {
      this.store.set('testFramework', 'mocha');
      this.store.set('name', 'test');
    });

    it('get values', function () {
      assert.equal(this.store.get('testFramework'), 'mocha');
      assert.equal(this.store.get('name'), 'test');
    });
  });

  describe('#set()', function () {
    it('set values', function () {
      this.store.set('name', 'Yeoman!');
      assert.equal(this.store.get('name'), 'Yeoman!');
    });

    it('set multipe values at once', function () {
      this.store.set({ foo: 'bar', john: 'doe' });
      assert.equal(this.store.get('foo'), 'bar');
      assert.equal(this.store.get('john'), 'doe');
    });

    it('throws when invalid JSON values are passed', function () {
      assert.throws(this.store.set.bind(this, 'foo', function () {}));
    });

    it('save on each changes', function () {
      this.store.set('foo', 'bar');
      assert.equal(this.saveSpy.callCount, 1);
      this.store.set('foo', 'oo');
      assert.equal(this.saveSpy.callCount, 2);
    });

    describe('@return', function () {
      beforeEach(function () {
        this.storePath = path.join(shell.tempdir(), 'setreturn.json');
        this.store = new Storage('test', this.storePath);
      });

      afterEach(function () {
        shell.rm('-f', this.storePath);
      });

      it('the saved value (with key)', function () {
        assert.equal(this.store.set('name', 'Yeoman!'), 'Yeoman!');
      });

      it('the saved value (without key)', function () {
        assert.deepEqual(
          this.store.set({ foo: 'bar', john: 'doe' }),
          { foo: 'bar', john: 'doe' }
        );
      });

      it('the saved value (update values)', function () {
        this.store.set({ foo: 'bar', john: 'doe' });
        assert.deepEqual(
          this.store.set({ foo: 'moo' }),
          { foo: 'moo', john: 'doe' }
        );
      });
    });
  });

  describe('#getAll()', function () {
    beforeEach(function () {
      this.store.set({ foo: 'bar', john: 'doe' });
    });

    it('get all values', function () {
      assert.deepEqual(this.store.getAll(), this.store._store);
    });

    it('does not return a reference to the inner store', function () {
      assert.notEqual(this.store.getAll(), this.store._store);
    });
  });

  describe('#delete()', function () {
    beforeEach(function () {
      this.store.set('name', 'test');
    });

    it('delete value', function () {
      this.store.delete('name');
      assert.equal(this.store.get('name'), undefined);
    });
  });

  describe('#save()', function () {
    beforeEach(function () {
      this.forceSaveSpy = sinon.spy(Storage.prototype, 'forceSave');
      this.storePath = path.join(shell.tempdir(), 'save.json');
      this.store = new Storage('test', this.storePath);
      this.store.set('foo', 'bar');
      this.saveSpy = sinon.spy(this.store, 'save');
    });

    afterEach(function () {
      shell.rm('-f', this.storePath);
      this.forceSaveSpy.restore();
      this.saveSpy.restore();
    });

    it('create storage file if none existed', function (done) {
      this.store.once('save', function () {
        var fileContent = JSON.parse(fs.readFileSync(this.storePath));
        assert.equal(fileContent.test.foo, 'bar');
        assert.ok(!this.store.existed);
        done();
      }.bind(this));

      this.store.save();
    });

    it('debounce multiple calls', function (done) {
      this.store.once('save', function () {
        assert.equal(this.forceSaveSpy.callCount, 1);
        assert.equal(this.saveSpy.callCount, 3);
        done();
      }.bind(this));

      this.store.save();
      this.store.save();
      this.store.save();
    });
  });

  describe('#forceSave()', function () {
    it('save file immediatly', function () {
      this.store.forceSave();
      var fileContent = JSON.parse(fs.readFileSync(this.storePath));
      assert.equal(fileContent.test.foo, 'bar');
    });
  });

  describe('#defaults()', function () {
    beforeEach(function () {
      this.store.set('val1', 1);
    });

    it('set defaults values if not predefined', function () {
      this.store.defaults({ val1: 3, val2: 4 });

      assert.equal(this.store.get('val1'), 1);
      assert.equal(this.store.get('val2'), 4);
    });

    it('require an Object as argument', function () {
      assert.throws(this.store.defaults.bind(this.store, 'foo'));
    });

    describe('@return', function () {
      beforeEach(function () {
        this.storePath = path.join(shell.tempdir(), 'defaultreturn.json');
        this.store = new Storage('test', this.storePath);
        this.store.set('val1', 1);
        this.store.set('foo', 'bar');
      });

      afterEach(function () {
        shell.rm('-f', this.storePath);
      });

      it('the saved value when passed an empty object', function () {
        assert.deepEqual(this.store.defaults({}), { foo: 'bar', val1: 1 });
      });

      it('the saved value when passed the same key', function () {
        assert.deepEqual(
          this.store.defaults({ foo: 'baz' }),
          { foo: 'bar', val1: 1 }
        );
      });

      it('the saved value when passed new key', function () {
        assert.deepEqual(
          this.store.defaults({ food: 'pizza' }),
          { foo: 'bar', val1: 1, food: 'pizza' }
        );
      });
    });
  });

});
<commit_msg>Fix flakey storage test<commit_after>/*global describe, it, before, after, beforeEach, afterEach */
'use strict';
var path = require('path');
var fs = require('fs');
var assert = require('assert');
var shell = require('shelljs');
var sinon = require('sinon');
var Storage = require('../lib/util/storage');

describe('Storage', function () {
  beforeEach(function () {
    this.beforeDir = process.cwd();
    this.storePath = path.join(shell.tempdir(), 'new-config.json');
    this.store = new Storage('test', this.storePath);
    this.store.set('foo', 'bar');
    this.saveSpy = sinon.spy(this.store, 'save');
  });

  afterEach(function () {
    shell.rm('-f', this.storePath);
    process.chdir(this.beforeDir);
    this.saveSpy.restore();
  });

  describe('.constructor()', function () {
    it('require a name parameter', function () {
      assert.throws(function () { new Storage(); });
    });

    it('take a path parameter', function () {
      var store = new Storage('test', path.join(__dirname, './fixtures/config.json'));
      assert.equal(store.get('testFramework'), 'mocha');
      assert.ok(store.existed);
    });
  });

  it('namespace each store sharing the same store file', function () {
    var store = new Storage('foobar', this.storePath);
    store.set('foo', 'something else');
    assert.ok(this.store.get('foo') === 'bar');
  });

  it('defaults store path to `.yo-rc.json`', function (done) {
    var tmp = shell.tempdir();
    process.chdir(tmp);
    var store = new Storage('yo');

    store.on('save', function () {
      var fileContent = JSON.parse(fs.readFileSync(path.join(tmp, '.yo-rc.json')));
      assert.equal(fileContent.yo.foo, 'bar');
      done();
    });

    store.set('foo', 'bar');
  });

  describe('#get()', function () {
    beforeEach(function () {
      this.store.set('testFramework', 'mocha');
      this.store.set('name', 'test');
    });

    it('get values', function () {
      assert.equal(this.store.get('testFramework'), 'mocha');
      assert.equal(this.store.get('name'), 'test');
    });
  });

  describe('#set()', function () {
    it('set values', function () {
      this.store.set('name', 'Yeoman!');
      assert.equal(this.store.get('name'), 'Yeoman!');
    });

    it('set multipe values at once', function () {
      this.store.set({ foo: 'bar', john: 'doe' });
      assert.equal(this.store.get('foo'), 'bar');
      assert.equal(this.store.get('john'), 'doe');
    });

    it('throws when invalid JSON values are passed', function () {
      assert.throws(this.store.set.bind(this, 'foo', function () {}));
    });

    it('save on each changes', function () {
      this.store.set('foo', 'bar');
      assert.equal(this.saveSpy.callCount, 1);
      this.store.set('foo', 'oo');
      assert.equal(this.saveSpy.callCount, 2);
    });

    describe('@return', function () {
      beforeEach(function () {
        this.storePath = path.join(shell.tempdir(), 'setreturn.json');
        this.store = new Storage('test', this.storePath);
      });

      afterEach(function () {
        shell.rm('-f', this.storePath);
      });

      it('the saved value (with key)', function () {
        assert.equal(this.store.set('name', 'Yeoman!'), 'Yeoman!');
      });

      it('the saved value (without key)', function () {
        assert.deepEqual(
          this.store.set({ foo: 'bar', john: 'doe' }),
          { foo: 'bar', john: 'doe' }
        );
      });

      it('the saved value (update values)', function () {
        this.store.set({ foo: 'bar', john: 'doe' });
        assert.deepEqual(
          this.store.set({ foo: 'moo' }),
          { foo: 'moo', john: 'doe' }
        );
      });
    });
  });

  describe('#getAll()', function () {
    beforeEach(function () {
      this.store.set({ foo: 'bar', john: 'doe' });
    });

    it('get all values', function () {
      assert.deepEqual(this.store.getAll(), this.store._store);
    });

    it('does not return a reference to the inner store', function () {
      assert.notEqual(this.store.getAll(), this.store._store);
    });
  });

  describe('#delete()', function () {
    beforeEach(function () {
      this.store.set('name', 'test');
    });

    it('delete value', function () {
      this.store.delete('name');
      assert.equal(this.store.get('name'), undefined);
    });
  });

  describe('#save()', function () {
    beforeEach(function () {
      this.forceSaveSpy = sinon.spy(Storage.prototype, 'forceSave');
      this.storePath = path.join(shell.tempdir(), 'save.json');
      this.store = new Storage('test', this.storePath);
      this.store.set('foo', 'bar');
      this.saveSpy = sinon.spy(this.store, 'save');
    });

    afterEach(function () {
      shell.rm('-f', this.storePath);
      this.forceSaveSpy.restore();
      this.saveSpy.restore();
    });

    it('create storage file if none existed', function (done) {
      this.store.once('save', function () {
        var fileContent = JSON.parse(fs.readFileSync(this.storePath));
        assert.equal(fileContent.test.foo, 'bar');
        assert.ok(!this.store.existed);
        done();
      }.bind(this));

      this.store.save();
    });

    it('debounce multiple calls', function (done) {
      this.store.once('save', function () {
        assert.equal(this.forceSaveSpy.callCount, 1);
        assert.equal(this.saveSpy.callCount, 3);
        done();
      }.bind(this));

      this.store.save();
      this.store.save();
      this.store.save();
    });
  });

  describe('#forceSave()', function () {
    it('save file immediatly', function () {
      this.store.forceSave();
      var fileContent = JSON.parse(fs.readFileSync(this.storePath));
      assert.equal(fileContent.test.foo, 'bar');
    });
  });

  describe('#defaults()', function () {
    beforeEach(function () {
      this.store.set('val1', 1);
    });

    it('set defaults values if not predefined', function () {
      this.store.defaults({ val1: 3, val2: 4 });

      assert.equal(this.store.get('val1'), 1);
      assert.equal(this.store.get('val2'), 4);
    });

    it('require an Object as argument', function () {
      assert.throws(this.store.defaults.bind(this.store, 'foo'));
    });

    describe('@return', function () {
      beforeEach(function (done) {
        this.storePath = path.join(shell.tempdir(), 'defaultreturn.json');
        this.store = new Storage('test', this.storePath);
        this.store.set('val1', 1);
        this.store.set('foo', 'bar');
        this.store.on('save', done);
      });

      afterEach(function () {
        this.store.removeAllListeners('save');
        shell.rm('-f', this.storePath);
      });

      it('the saved value when passed an empty object', function () {
        assert.deepEqual(this.store.defaults({}), { foo: 'bar', val1: 1 });
      });

      it('the saved value when passed the same key', function () {
        assert.deepEqual(
          this.store.defaults({ foo: 'baz' }),
          { foo: 'bar', val1: 1 }
        );
      });

      it('the saved value when passed new key', function () {
        assert.deepEqual(
          this.store.defaults({ food: 'pizza' }),
          { foo: 'bar', val1: 1, food: 'pizza' }
        );
      });
    });
  });

});
<|endoftext|>


<commit_before>addEventListener('load', function(){
	removeEventListener('load', arguments.callee, false);

	let eTLD = Cc["@mozilla.org/network/effective-tld-service;1"]
		.getService(Ci.nsIEffectiveTLDService);
	let baseDomain = eTLD.getBaseDomainFromHost;

	function $(id) document.getElementById(id);
	function unique(array) array.filter(function(e) !((e in this) || (this[e] = null)), {});

	function buildHosts() {
		let hosts = [];
		try {
			let view = PlacesUIUtils.getViewForNode(document.popupNode);
			let node = view.selectedNode;

			function add(aItem) {
				if (PlacesUtils.nodeIsHost(aItem)) {
					let queries = aItem.getQueries({});
					hosts.push(queries[0].domain);
				}
				else if (PlacesUtils.nodeIsContainer(aItem)) {
					for each (let item in PlacesUtils.getURLsForContainerNode(aItem)) {
						arguments.callee(item);
					}
				}
				else if (!aItem.isBookmark){
					try {
						hosts.push(PlacesUtils._uri(aItem.uri).host);
					}
					catch (ex) {}
				}
			}
			for each (let sn in view.getSelectionNodes()) {
				add(sn);
			}
		}
		catch (ex) {
			Components.utils.reportError(ex);
		}
		return hosts;
	}

	function purge(array) {
		unique(array).forEach(function(e) PlacesUIUtils.privateBrowsing.removeDataFromDomain(e));
	}

	$('cmd_massforget_forgetmultiple').addEventListener('command', function() {
		purge(buildHosts());
	}, true);

	$('cmd_massforget_forgetdomains').addEventListener('command', function() {
		purge(buildHosts().map(function(e) baseDomain(e)));
	}, true);

}, false);
<commit_msg>Firefox 4 compat<commit_after>addEventListener('load', function(){
	removeEventListener('load', arguments.callee, false);

	let eTLD = Cc["@mozilla.org/network/effective-tld-service;1"]
		.getService(Ci.nsIEffectiveTLDService);
	let baseDomain = eTLD.getBaseDomainFromHost;

	function $(id) document.getElementById(id);
	function unique(array) array.filter(function(e) !((e in this) || (this[e] = null)), {});

	function buildHosts() {
		let hosts = [];
		try {
			let view = PlacesUIUtils.getViewForNode(document.popupNode);
			let node = view.selectedNode;

			function add(aItem) {
				if (PlacesUtils.nodeIsHost(aItem)) {
					let queries = aItem.getQueries({});
					hosts.push(queries[0].domain);
				}
				else if (PlacesUtils.nodeIsContainer(aItem)) {
					for each (let item in PlacesUtils.getURLsForContainerNode(aItem)) {
						arguments.callee(item);
					}
				}
				else if (!aItem.isBookmark){
					try {
						hosts.push(PlacesUtils._uri(aItem.uri).host);
					}
					catch (ex) {}
				}
			}
			for each (let sn in (view.selectedNodes || view.getSelectionNodes())) {
				add(sn);
			}
		}
		catch (ex) {
			Components.utils.reportError(ex);
		}
		return hosts;
	}

	function purge(array) {
		unique(array).forEach(function(e) PlacesUIUtils.privateBrowsing.removeDataFromDomain(e));
	}

	$('cmd_massforget_forgetmultiple').addEventListener('command', function() {
		purge(buildHosts());
	}, true);

	$('cmd_massforget_forgetdomains').addEventListener('command', function() {
		purge(buildHosts().map(function(e) baseDomain(e)));
	}, true);

}, false);
<|endoftext|>


<commit_before>var kss = require('../index.js'),
	KssStyleguide = kss.KssStyleguide,
	KssSection = kss.KssSection,
	KssModifier = kss.KssModifier,

	path = require('path'),
	assert = require('assert'),

	styleDirectory = path.normalize(__dirname + '/fixtures-styles/'),
	common = require('./common.js')(styleDirectory);

suite('KssSection', function() {
	common.hasMethod(new KssSection({}), 'header');
	common.hasMethod(new KssSection({}), 'description');
	common.hasMethod(new KssSection({}), 'deprecated');
	common.hasMethod(new KssSection({}), 'experimental');
	common.hasMethod(new KssSection({}), 'reference');
	common.hasMethod(new KssSection({}), 'depth');
	common.hasMethod(new KssSection({}), 'encodeReferenceURI');
	common.hasMethod(new KssSection({}), 'referenceURI');
	common.hasMethod(new KssSection({}), 'modifiers');
	common.hasMethod(new KssSection({}), 'firstModifier');

	suite('.header()', function() {
		common.testAllSections('returns section.data.header', '*.less|*.css', function(section) {
			assert.strictEqual(section.header(), section.data.header);
		});
	});

	suite('.description()', function() {
		common.testAllSections('returns section.data.description', '*.less|*.css', function(section) {
			assert.strictEqual(section.description(), section.data.description);
		});
	});

	suite('.deprecated()', function() {
		common.testAllSections('returns section.data.deprecated', '*.less|*.css', function(section) {
			assert.equal(section.deprecated(), section.data.deprecated);
		});
	});

	suite('.experimental()', function() {
		common.testAllSections('returns section.data.experimental', '*.less|*.css', function(section) {
			assert.equal(section.experimental(), section.data.experimental);
		});
	});

	suite('.reference()', function() {
		common.testAllSections('returns section.data.reference', '*.less|*.css', function(section) {
			assert.equal(section.reference(), section.data.reference);
		});
	});

	suite('.depth()', function() {
		common.testAllSections('returns section.data.depth', '*.less|*.css', function(section) {
			assert.equal(section.depth(), section.data.depth);
		});
	});

	suite('.encodeReferenceURI()', function() {
		common.testAllSections('.encodeReferenceURI(section.reference()) equals .referenceURI()', '*.less|*.css', function(section) {
			assert.equal(section.encodeReferenceURI(section.reference()), section.referenceURI());
		});
	});

	suite('.referenceURI()', function() {
		common.testAllSections('returns section.data.referenceURI', '*.less|*.css', function(section) {
			assert.equal(section.referenceURI(), section.data.referenceURI);
		});
	});

	suite('.modifiers()', function() {
		common.testAllSections('() returns section.data.modifiers', '*.less|*.css', function(section) {
			assert.strictEqual(section.modifiers(), section.data.modifiers);
		});

		common.testAllSections('() all returned should be instances of KssModifier', '*.less|*.css', function(section) {
			var modifiers = section.modifiers(),
				i, l = modifiers.length;

			for (i = 0; i < l; i += 1) {
				assert.ok(modifiers[i] instanceof KssModifier);
			}
		});

		common.testAllSections('(n) returns section.data.modifiers[n], or false if non-existent', '*.less|*.css', function(section) {
			var i, j = 5, l = section.data.modifiers.length;

			for (i = 0; i < j || i < l; i++) {
				if (i < l) {
					assert.deepEqual(section.modifiers(i), section.data.modifiers[i]);
				} else {
					assert.equal(section.modifiers(i), false);
				}
			}
		});

		common.testAllSections('("n") coerces to a number if numerical', '*.less|*.css', function(section) {
			var i, j = 5, l = section.data.modifiers.length;

			for (i = 0; i < j || i < l; i++) {
				if (i < l) {
					assert.deepEqual(section.modifiers(i), section.data.modifiers[i]);
				} else {
					assert.equal(section.modifiers(i), false);
				}
			}
		});

		common.testAllSections('("modifier") should search by name', '*.less|*.css', function(section) {
			var i, j, queries = [ '.red', '.yellow', ':hover', ':disabled' ],
				q = queries.length,
				l = section.data.modifiers.length;

			// Each modifier
			for (i = 0; i < l; i += 1) {

				// Each query
				for (j = 0; j < q; j += 1) {
					if (section.data.modifiers[i].data.name === queries[j]) {
						assert.deepEqual(section.modifiers(queries[j]), section.data.modifiers[i]);
					}
				}

			}
		});

		common.testAllSections('("modifier") should only return false if not found', '*.less|*.css', function(section) {
			var i, l = section.data.modifiers.length;
			assert.equal(false, section.modifiers('__should_not_find___'));
			if (l) { assert.ok(section.modifiers(section.modifiers(0).data.name)); }
		});
	});

	suite('.firstModifier()', function() {
		common.testAllSections('returns section.data.modifiers[0], or first if not found', '*.less|*.css', function(section) {
			if (section.data.modifiers.length) {
				assert.equal(section.firstModifier(), section.modifiers(0));
			}
		});
	});
});
<commit_msg>Add better tests for depth().<commit_after>var kss = require('../index.js'),
	KssStyleguide = kss.KssStyleguide,
	KssSection = kss.KssSection,
	KssModifier = kss.KssModifier,

	path = require('path'),
	assert = require('assert'),

	styleDirectory = path.normalize(__dirname + '/fixtures-styles/'),
	common = require('./common.js')(styleDirectory);

suite('KssSection', function() {
	common.hasMethod(new KssSection({}), 'header');
	common.hasMethod(new KssSection({}), 'description');
	common.hasMethod(new KssSection({}), 'deprecated');
	common.hasMethod(new KssSection({}), 'experimental');
	common.hasMethod(new KssSection({}), 'reference');
	common.hasMethod(new KssSection({}), 'depth');
	common.hasMethod(new KssSection({}), 'encodeReferenceURI');
	common.hasMethod(new KssSection({}), 'referenceURI');
	common.hasMethod(new KssSection({}), 'modifiers');
	common.hasMethod(new KssSection({}), 'firstModifier');

	suite('.header()', function() {
		common.testAllSections('returns section.data.header', '*.less|*.css', function(section) {
			assert.strictEqual(section.header(), section.data.header);
		});
	});

	suite('.description()', function() {
		common.testAllSections('returns section.data.description', '*.less|*.css', function(section) {
			assert.strictEqual(section.description(), section.data.description);
		});
	});

	suite('.deprecated()', function() {
		common.testAllSections('returns section.data.deprecated', '*.less|*.css', function(section) {
			assert.equal(section.deprecated(), section.data.deprecated);
		});
	});

	suite('.experimental()', function() {
		common.testAllSections('returns section.data.experimental', '*.less|*.css', function(section) {
			assert.equal(section.experimental(), section.data.experimental);
		});
	});

	suite('.reference()', function() {
		common.testAllSections('returns section.data.reference', '*.less|*.css', function(section) {
			assert.equal(section.reference(), section.data.reference);
		});
	});

	suite('.depth()', function() {
		common.testAllSections('returns section.data.depth', '*.less|*.css', function(section) {
			assert.equal(section.depth(), section.data.depth);
			assert.equal(section.depth(), section.reference().split(/(?:\.|\s+\-\s+)/).length);
		});
	});

	suite('.encodeReferenceURI()', function() {
		common.testAllSections('.encodeReferenceURI(section.reference()) equals .referenceURI()', '*.less|*.css', function(section) {
			assert.equal(section.encodeReferenceURI(section.reference()), section.referenceURI());
		});
	});

	suite('.referenceURI()', function() {
		common.testAllSections('returns section.data.referenceURI', '*.less|*.css', function(section) {
			assert.equal(section.referenceURI(), section.data.referenceURI);
			assert.equal(section.referenceURI(), section.encodeReferenceURI(section.reference()));
		});
	});

	suite('.modifiers()', function() {
		common.testAllSections('() returns section.data.modifiers', '*.less|*.css', function(section) {
			assert.strictEqual(section.modifiers(), section.data.modifiers);
		});

		common.testAllSections('() all returned should be instances of KssModifier', '*.less|*.css', function(section) {
			var modifiers = section.modifiers(),
				i, l = modifiers.length;

			for (i = 0; i < l; i += 1) {
				assert.ok(modifiers[i] instanceof KssModifier);
			}
		});

		common.testAllSections('(n) returns section.data.modifiers[n], or false if non-existent', '*.less|*.css', function(section) {
			var i, j = 5, l = section.data.modifiers.length;

			for (i = 0; i < j || i < l; i++) {
				if (i < l) {
					assert.deepEqual(section.modifiers(i), section.data.modifiers[i]);
				} else {
					assert.equal(section.modifiers(i), false);
				}
			}
		});

		common.testAllSections('("n") coerces to a number if numerical', '*.less|*.css', function(section) {
			var i, j = 5, l = section.data.modifiers.length;

			for (i = 0; i < j || i < l; i++) {
				if (i < l) {
					assert.deepEqual(section.modifiers(i), section.data.modifiers[i]);
				} else {
					assert.equal(section.modifiers(i), false);
				}
			}
		});

		common.testAllSections('("modifier") should search by name', '*.less|*.css', function(section) {
			var i, j, queries = [ '.red', '.yellow', ':hover', ':disabled' ],
				q = queries.length,
				l = section.data.modifiers.length;

			// Each modifier
			for (i = 0; i < l; i += 1) {

				// Each query
				for (j = 0; j < q; j += 1) {
					if (section.data.modifiers[i].data.name === queries[j]) {
						assert.deepEqual(section.modifiers(queries[j]), section.data.modifiers[i]);
					}
				}

			}
		});

		common.testAllSections('("modifier") should only return false if not found', '*.less|*.css', function(section) {
			var i, l = section.data.modifiers.length;
			assert.equal(false, section.modifiers('__should_not_find___'));
			if (l) { assert.ok(section.modifiers(section.modifiers(0).data.name)); }
		});
	});

	suite('.firstModifier()', function() {
		common.testAllSections('returns section.data.modifiers[0], or first if not found', '*.less|*.css', function(section) {
			if (section.data.modifiers.length) {
				assert.equal(section.firstModifier(), section.modifiers(0));
			}
		});
	});
});
<|endoftext|>


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

    var max_seats=35;

    $('table').find('input').each(function() {
	if ($(this).val()!=0){
            $(this).attr('disabled', true);
            $(this).prop('checked', false );
	}
    })

    var hid_prc = ['4','5','6', '7', '299','309', '308' ,'307' ,'306' ,'305' ,'311','310'];
    for (var n=313; n<=345; n++){
	hid_prc.push(n.toString());
    }
    var hid_ID = ['31', '44' ,'35' ,'45' ,'33' ,'46'];
    var hid_promo = ['350','351' ,'353' ,'354', '356', '359', '361', '363' ,'364' ,'365', '366', 'P'];

    HideFields(hid_prc);
    HideFields(hid_ID);
    HideFields(hid_promo);

    var date = new Date();
    var end = new Date('2014/03/30');
    var holidays = [new Date('2014/01/20')];
    var cancelled = [new Date('2014/01/11'), new Date('2014/02/01')];
    var valid_dates = [];

    while (date<=end) {
	var now = new Date(date);
	var day = now.getDay();
	if (((day==6)||(day==0))&&(cancelled.indexOf(now)==-1)) { valid_dates.push(now); }
	date.setDate(date.getDate()+1);
    }

    var tdy = new Date();
    for (var i=0; i<holidays.length; i++) {
	if (tdy<=holidays[i]) { valid_dates.push(holidays[i]); }
    }

    valid_dates.sort(function(a,b){return a-b});

    $('#Field1-1').val(FixMD(valid_dates[0].getMonth()+1));
    $('#Field1-2').val(FixMD(valid_dates[0].getDate()));
    $('#Field1').val(valid_dates[0].getFullYear());

    for(i = 0; i<valid_dates.length; i++) {
	valid_dates[i]=((valid_dates[i].getFullYear()) + '/' + (FixMD(valid_dates[i].getMonth()+1)) + '/' + (FixMD(valid_dates[i].getDate())));
    }

    function HideFields(arr){
        for (var i=0; i<arr.length; i++) {
            $('#foli'+arr[i]).hide();
        }
    }

    function FixMD(e){
        e='0'+e;
        e=e.slice(e.length-2,e.length);
        return e;
    }

    CheckDate();

    function CheckDate() {
	var trav_m = FixMD($('#Field1-1').val());
	var trav_d = FixMD($('#Field1-2').val());
	var trav_y = $('#Field1').val();
	var req_date =  (trav_y + '/' + trav_m + '/' + trav_d);
	var req_day = new Date(req_date).getDay();

 	if (valid_dates.indexOf(req_date)==-1){
	    $('#foli4').show("slow");
            $('#foli6').hide("slow");
            $('#foli7').hide("slow");
	    $('input[name=Field8]:radio').attr('disabled', true);
            $('#Field10 option').each(function(){
		if ($(this).val()>0) { $(this).remove(); }
            })
		$('#Field11 option').each(function(){
		    if ($(this).val()>0) { $(this).remove(); }
		})

		    $('table').find('input').each(function() {
			if ($(this).val()==0) {
			    $(this).prop('checked', true);
			} else {
			    $(this).attr('disabled', true);
			}
		    }) } else {
			$('#foli4').hide( "slow");
			GetWufoo(trav_y,trav_m,trav_d);
		    }
    }

    function NotifyUser(Entries) {

	$('input[name=Field8]:radio').attr('disabled', false);

	var DU_num_booked = 0;
	var WA_num_booked = 0;
	var DU_num_equip = 0;
	var WA_num_equip = 0;

	for (i=0;i<Entries.length;i++ ){
	    if ((Entries[i].Field8=='Downtown, Brooklyn')||(Entries[i].Field8=='Union Square, Manhattan')){
		DU_num_booked += parseFloat(Entries[i].Field10);
		DU_num_equip += parseFloat(Entries[i].Field11);
	    }   else if ((Entries[i].Field8=='Williamsburg, Brooklyn')||(Entries[i].Field8=='Astoria, Queens')){
		WA_num_booked += parseFloat(Entries[i].Field10);
		WA_num_equip += parseFloat(Entries[i].Field11);
	    }
	};

	var DU_rem_seats = max_seats-DU_num_booked;
	var WA_rem_seats = max_seats-WA_num_booked;

	var DU_rem_equip = 20-DU_num_equip;
	var WA_rem_equip = 20-WA_num_equip;

	var dep = $('input[name=Field8]:checked').val();
        var trav_m = FixMD($('#Field1-1').val());
        var trav_d = FixMD($('#Field1-2').val());
        var trav_y = $('#Field1').val();
        var req_date =  (trav_y + '/' + trav_m + '/' + trav_d);

	if (req_date=='2014/02/17') {
	    WA_rem_seats = 0;
	} else if (req_date=='2014/02/15') {
            DU_rem_seats = max_seats*2-DU_num_booked;
	}

	if ((DU_rem_seats<=0)&&(WA_rem_seats<=0)) {
	    $('input[name=Field8]:radio').attr('disabled',true);
            $('input[name=Field8]:radio').prop('checked',false);
            $('#titleSO').text('**ALL BUSES SOLD OUT**');
	    $('#foli7').show( "slow");
	} else if ((req_date=='2014/02/15')&&(DU_rem_seats>0)&&(DU_rem_seats<max_seats)) {
            $('#titleSO').html('Downtown & Union Square pickup **Bus 1 SOLD OUT**
Bus 2 added by popular demand!');
            $('#foli7').show( "slow");
	} else if (DU_rem_seats<=0) {
	    $('#Field8_0').prop('checked', false)
            $('#Field8_3').prop('checked', false);
            $('#Field8_0').attr('disabled', true);
            $('#Field8_3').attr('disabled', true);
	    $('#titleSO').text('Downtown & Union Square pickup -- **SOLD OUT**');
            $('#foli7').show( "slow");
        } else if (WA_rem_seats<=0) {
            $('#Field8_1').prop('checked', false);
            $('#Field8_2').prop('checked', false);
            $('#Field8_1').attr('disabled', true);
            $('#Field8_2').attr('disabled', true);
            $('#titleSO').text('Williamsburg & Astoria pickup -- **SOLD OUT**');
            $('#foli7').show( "slow");
        } else {
	    $('#foli7').hide("slow");
	}

	var rem_seats=0;
	var rem_equip=0;

	if (dep!=undefined) {
	    if ((dep=='Downtown, Brooklyn')||(dep=='Union Square, Manhattan')) {
		rem_seats=Math.max(0,DU_rem_seats);
		rem_equip=Math.max(0,DU_rem_equip);
	    } else if ((dep=='Williamsburg, Brooklyn')||(dep=='Astoria, Queens')) {
		rem_seats=Math.max(0,WA_rem_seats);
		rem_equip=Math.max(0,WA_rem_equip);
	    }
	}
	console.log('DU_rem_seats '+ DU_rem_seats+' / DU_rem_equip '+DU_rem_equip);
        console.log('WA_rem_seats '+ WA_rem_seats+' / WA_rem_equip '+WA_rem_equip);

	if ((rem_seats<4)&&(rem_seats>0)) {
	    $('#titleSL').text((rem_seats+' seats left on this bus!'));
	    if (rem_seats==1) {
                $('#titleSL').text((rem_seats+' seat left on this bus!'));
	    }
	    $('#foli6').show( "slow");
	} else {
	    $('#foli6').hide( "slow");
	}

	var max=0;
	var max_e=0;

	$('#Field10 option').each(function(){
	    max = Math.max($(this).val(), max);
	    if ($(this).val()>rem_seats) { $(this).remove(); }
	})

	    $('#Field11 option').each(function(){
		max_e = Math.max($(this).val(), max_e);
		if ($(this).val()>rem_equip) { $(this).remove();}
	    })

		var limit = Math.min(4,rem_seats);
	for (var i=max+1; i<=limit;i++){
	    $('#Field10').append('<option value="'+i+'">'+i+'</option>');
	}
        var limit_e = Math.min(4,rem_equip);
        for (var i=max_e+1; i<=limit_e;i++){
	    $('#Field11').append('<option value="'+i+'">'+i+'</option>');
        }

	var req_seats=$('#Field10').val();

            $('table').find('input').each(function() {
		if ($(this).val()>req_seats) {
                    $(this).attr('disabled', true);
		}
            })

		var tot = 0;
            $('table').find('input:checked').each(function() {
		tot+= parseFloat($(this).val());
		if ($(this).val()>req_seats) {
                    $('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
                }
            })
		if (tot>req_seats) {
		    $('table').find('input:checked').each(function() {
			$('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
		    })
			}

    }

    function SetSeats(){
	$('table').find('input').each(function() {
            $(this).attr('disabled', false);
	})

	    var req_seats = $(this).val();
	var max=0;

	$('#Field11 option').each(function(){
	    max = Math.max($(this).val(), max);
	    if ($(this).val()>req_seats) { $(this).remove(); }
	})

	    for (var i=max+1; i<=req_seats;i++){
		$('#Field11').append('<option value="'+i+'">'+i+'</option>');
	   }

	if (req_seats>1){
	    $('#foli31').show();
	    $('#foli44').show();
	} else {
            $('#foli31').hide();
            $('#foli44').hide();
	}
	if (req_seats>2) {
	    $('#foli35').show();
	    $('#foli45').show();
	} else {
            $('#foli35').hide();
            $('#foli45').hide();
	}
	if (req_seats>3) {
	    $('#foli33').show();
	    $('#foli46').show();
	} else {
            $('#foli33').hide();
            $('#foli46').hide();
	}

        $('table').find('input').each(function() {
            if ($(this).val()>req_seats) {
                $(this).attr('disabled', true);
            }
        })

            var tot = 0;
        $('table').find('input:checked').each(function() {
            tot+= parseFloat($(this).val());
            if ($(this).val()>req_seats) {
                $('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
            }
        })

            if (tot>req_seats) {
                $('table').find('input:checked').each(function() {
                    $('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
                })
                    }
    }

    function SetTix() {
	var req_seats=$('#Field10').val()
	var tot=0;
	$('table').find('input:checked').each(function() {
	    tot+= parseFloat($(this).val());
	})
            if (tot>req_seats) {
		$('table').find('input:checked').each(function() {
                    $('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
		})
                    }
	$(this).prop('checked',true);
    }

    function ShowPromo() {
	if ($(this).val()=='Brokelyn') {
	    $('#foliP').show("slow");
	} else {
	    $('#foliP').hide("slow");
	}
    }

    function GetWufoo(y,m,d){
        var date = y+'-'+m+'-'+d;
        $.get('api/wufoo',{filter:date},NotifyUser);
    }

    function FmtDate(dateText, inst) {
	var pieces = dateText.split('/');
	$('input[name=Field1-1]').val(pieces[0]);
	$('input[name=Field1-2]').val(pieces[1]);
	$('input[name=Field1]').val(pieces[2]);
	CheckDate();
    }

    $('#cal').datepicker({
	showOn: "button",
	buttonImage: "images/calendar.png",
	buttonImageOnly: true,
	buttonText: "",
	onSelect: FmtDate})

    $('input[name=Field8]:radio').change(CheckDate);
    $('div[name=Depart]').mouseenter(CheckDate);
    $('#Field1-1').change(CheckDate);
    $('#Field1-2').change(CheckDate);
    $('#Field1').change(CheckDate);
    $('#Field10').change(SetSeats);
    var table_fld = ['165', '166', '167', '168', '169', '170', '171', '172'];
    for (var f=0; f<table_fld.length; f++) {
	$('input[name="Field'+table_fld[f]+'"]:radio').change(SetTix);
    }

    $('#Field347').keyup(ShowPromo);
});

$(function() {
    $(document).tooltip();
});
<commit_msg>no console<commit_after>
$(document).ready(function(){

    var max_seats=35;

    $('table').find('input').each(function() {
	if ($(this).val()!=0){
            $(this).attr('disabled', true);
            $(this).prop('checked', false );
	}
    })

    var hid_prc = ['4','5','6', '7', '299','309', '308' ,'307' ,'306' ,'305' ,'311','310'];
    for (var n=313; n<=345; n++){
	hid_prc.push(n.toString());
    }
    var hid_ID = ['31', '44' ,'35' ,'45' ,'33' ,'46'];
    var hid_promo = ['350','351' ,'353' ,'354', '356', '359', '361', '363' ,'364' ,'365', '366', 'P'];

    HideFields(hid_prc);
    HideFields(hid_ID);
    HideFields(hid_promo);

    var date = new Date();
    var end = new Date('2014/03/30');
    var holidays = [new Date('2014/01/20')];
    var cancelled = [new Date('2014/01/11'), new Date('2014/02/01')];
    var valid_dates = [];

    while (date<=end) {
	var now = new Date(date);
	var day = now.getDay();
	if (((day==6)||(day==0))&&(cancelled.indexOf(now)==-1)) { valid_dates.push(now); }
	date.setDate(date.getDate()+1);
    }

    var tdy = new Date();
    for (var i=0; i<holidays.length; i++) {
	if (tdy<=holidays[i]) { valid_dates.push(holidays[i]); }
    }

    valid_dates.sort(function(a,b){return a-b});

    $('#Field1-1').val(FixMD(valid_dates[0].getMonth()+1));
    $('#Field1-2').val(FixMD(valid_dates[0].getDate()));
    $('#Field1').val(valid_dates[0].getFullYear());

    for(i = 0; i<valid_dates.length; i++) {
	valid_dates[i]=((valid_dates[i].getFullYear()) + '/' + (FixMD(valid_dates[i].getMonth()+1)) + '/' + (FixMD(valid_dates[i].getDate())));
    }

    function HideFields(arr){
        for (var i=0; i<arr.length; i++) {
            $('#foli'+arr[i]).hide();
        }
    }

    function FixMD(e){
        e='0'+e;
        e=e.slice(e.length-2,e.length);
        return e;
    }

    CheckDate();

    function CheckDate() {
	var trav_m = FixMD($('#Field1-1').val());
	var trav_d = FixMD($('#Field1-2').val());
	var trav_y = $('#Field1').val();
	var req_date =  (trav_y + '/' + trav_m + '/' + trav_d);
	var req_day = new Date(req_date).getDay();

 	if (valid_dates.indexOf(req_date)==-1){
	    $('#foli4').show("slow");
            $('#foli6').hide("slow");
            $('#foli7').hide("slow");
	    $('input[name=Field8]:radio').attr('disabled', true);
            $('#Field10 option').each(function(){
		if ($(this).val()>0) { $(this).remove(); }
            })
		$('#Field11 option').each(function(){
		    if ($(this).val()>0) { $(this).remove(); }
		})

		    $('table').find('input').each(function() {
			if ($(this).val()==0) {
			    $(this).prop('checked', true);
			} else {
			    $(this).attr('disabled', true);
			}
		    }) } else {
			$('#foli4').hide( "slow");
			GetWufoo(trav_y,trav_m,trav_d);
		    }
    }

    function NotifyUser(Entries) {

	$('input[name=Field8]:radio').attr('disabled', false);

	var DU_num_booked = 0;
	var WA_num_booked = 0;
	var DU_num_equip = 0;
	var WA_num_equip = 0;

	for (i=0;i<Entries.length;i++ ){
	    if ((Entries[i].Field8=='Downtown, Brooklyn')||(Entries[i].Field8=='Union Square, Manhattan')){
		DU_num_booked += parseFloat(Entries[i].Field10);
		DU_num_equip += parseFloat(Entries[i].Field11);
	    }   else if ((Entries[i].Field8=='Williamsburg, Brooklyn')||(Entries[i].Field8=='Astoria, Queens')){
		WA_num_booked += parseFloat(Entries[i].Field10);
		WA_num_equip += parseFloat(Entries[i].Field11);
	    }
	};

	var DU_rem_seats = max_seats-DU_num_booked;
	var WA_rem_seats = max_seats-WA_num_booked;

	var DU_rem_equip = 20-DU_num_equip;
	var WA_rem_equip = 20-WA_num_equip;

	var dep = $('input[name=Field8]:checked').val();
        var trav_m = FixMD($('#Field1-1').val());
        var trav_d = FixMD($('#Field1-2').val());
        var trav_y = $('#Field1').val();
        var req_date =  (trav_y + '/' + trav_m + '/' + trav_d);

	if (req_date=='2014/02/17') {
	    WA_rem_seats = 0;
	} else if (req_date=='2014/02/15') {
            DU_rem_seats = max_seats*2-DU_num_booked;
	}

	if ((DU_rem_seats<=0)&&(WA_rem_seats<=0)) {
	    $('input[name=Field8]:radio').attr('disabled',true);
            $('input[name=Field8]:radio').prop('checked',false);
            $('#titleSO').text('**ALL BUSES SOLD OUT**');
	    $('#foli7').show( "slow");
	} else if ((req_date=='2014/02/15')&&(DU_rem_seats>0)&&(DU_rem_seats<max_seats)) {
            $('#titleSO').html('Downtown & Union Square pickup **Bus 1 SOLD OUT**
Bus 2 added by popular demand!');
            $('#foli7').show( "slow");
	} else if (DU_rem_seats<=0) {
	    $('#Field8_0').prop('checked', false)
            $('#Field8_3').prop('checked', false);
            $('#Field8_0').attr('disabled', true);
            $('#Field8_3').attr('disabled', true);
	    $('#titleSO').text('Downtown & Union Square pickup -- **SOLD OUT**');
            $('#foli7').show( "slow");
        } else if (WA_rem_seats<=0) {
            $('#Field8_1').prop('checked', false);
            $('#Field8_2').prop('checked', false);
            $('#Field8_1').attr('disabled', true);
            $('#Field8_2').attr('disabled', true);
            $('#titleSO').text('Williamsburg & Astoria pickup -- **SOLD OUT**');
            $('#foli7').show( "slow");
        } else {
	    $('#foli7').hide("slow");
	}

	var rem_seats=0;
	var rem_equip=0;

	if (dep!=undefined) {
	    if ((dep=='Downtown, Brooklyn')||(dep=='Union Square, Manhattan')) {
		rem_seats=Math.max(0,DU_rem_seats);
		rem_equip=Math.max(0,DU_rem_equip);
	    } else if ((dep=='Williamsburg, Brooklyn')||(dep=='Astoria, Queens')) {
		rem_seats=Math.max(0,WA_rem_seats);
		rem_equip=Math.max(0,WA_rem_equip);
	    }
	}
	// console.log('DU_rem_seats '+ DU_rem_seats+' / DU_rem_equip '+DU_rem_equip);
        // console.log('WA_rem_seats '+ WA_rem_seats+' / WA_rem_equip '+WA_rem_equip);

	if ((rem_seats<4)&&(rem_seats>0)) {
	    $('#titleSL').text((rem_seats+' seats left on this bus!'));
	    if (rem_seats==1) {
                $('#titleSL').text((rem_seats+' seat left on this bus!'));
	    }
	    $('#foli6').show( "slow");
	} else {
	    $('#foli6').hide( "slow");
	}

	var max=0;
	var max_e=0;

	$('#Field10 option').each(function(){
	    max = Math.max($(this).val(), max);
	    if ($(this).val()>rem_seats) { $(this).remove(); }
	})

	    $('#Field11 option').each(function(){
		max_e = Math.max($(this).val(), max_e);
		if ($(this).val()>rem_equip) { $(this).remove();}
	    })

		var limit = Math.min(4,rem_seats);
	for (var i=max+1; i<=limit;i++){
	    $('#Field10').append('<option value="'+i+'">'+i+'</option>');
	}
        var limit_e = Math.min(4,rem_equip);
        for (var i=max_e+1; i<=limit_e;i++){
	    $('#Field11').append('<option value="'+i+'">'+i+'</option>');
        }

	var req_seats=$('#Field10').val();

            $('table').find('input').each(function() {
		if ($(this).val()>req_seats) {
                    $(this).attr('disabled', true);
		}
            })

		var tot = 0;
            $('table').find('input:checked').each(function() {
		tot+= parseFloat($(this).val());
		if ($(this).val()>req_seats) {
                    $('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
                }
            })
		if (tot>req_seats) {
		    $('table').find('input:checked').each(function() {
			$('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
		    })
			}

    }

    function SetSeats(){
	$('table').find('input').each(function() {
            $(this).attr('disabled', false);
	})

	    var req_seats = $(this).val();
	var max=0;

	$('#Field11 option').each(function(){
	    max = Math.max($(this).val(), max);
	    if ($(this).val()>req_seats) { $(this).remove(); }
	})

	    for (var i=max+1; i<=req_seats;i++){
		$('#Field11').append('<option value="'+i+'">'+i+'</option>');
	   }

	if (req_seats>1){
	    $('#foli31').show();
	    $('#foli44').show();
	} else {
            $('#foli31').hide();
            $('#foli44').hide();
	}
	if (req_seats>2) {
	    $('#foli35').show();
	    $('#foli45').show();
	} else {
            $('#foli35').hide();
            $('#foli45').hide();
	}
	if (req_seats>3) {
	    $('#foli33').show();
	    $('#foli46').show();
	} else {
            $('#foli33').hide();
            $('#foli46').hide();
	}

        $('table').find('input').each(function() {
            if ($(this).val()>req_seats) {
                $(this).attr('disabled', true);
            }
        })

            var tot = 0;
        $('table').find('input:checked').each(function() {
            tot+= parseFloat($(this).val());
            if ($(this).val()>req_seats) {
                $('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
            }
        })

            if (tot>req_seats) {
                $('table').find('input:checked').each(function() {
                    $('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
                })
                    }
    }

    function SetTix() {
	var req_seats=$('#Field10').val()
	var tot=0;
	$('table').find('input:checked').each(function() {
	    tot+= parseFloat($(this).val());
	})
            if (tot>req_seats) {
		$('table').find('input:checked').each(function() {
                    $('input[name="'+$(this).attr('name')+'"][value="0"]' ).prop('checked', true);
		})
                    }
	$(this).prop('checked',true);
    }

    function ShowPromo() {
	if ($(this).val()=='Brokelyn') {
	    $('#foliP').show("slow");
	} else {
	    $('#foliP').hide("slow");
	}
    }

    function GetWufoo(y,m,d){
        var date = y+'-'+m+'-'+d;
        $.get('api/wufoo',{filter:date},NotifyUser);
    }

    function FmtDate(dateText, inst) {
	var pieces = dateText.split('/');
	$('input[name=Field1-1]').val(pieces[0]);
	$('input[name=Field1-2]').val(pieces[1]);
	$('input[name=Field1]').val(pieces[2]);
	CheckDate();
    }

    $('#cal').datepicker({
	showOn: "button",
	buttonImage: "images/calendar.png",
	buttonImageOnly: true,
	buttonText: "",
	onSelect: FmtDate})

    $('input[name=Field8]:radio').change(CheckDate);
    $('div[name=Depart]').mouseenter(CheckDate);
    $('#Field1-1').change(CheckDate);
    $('#Field1-2').change(CheckDate);
    $('#Field1').change(CheckDate);
    $('#Field10').change(SetSeats);
    var table_fld = ['165', '166', '167', '168', '169', '170', '171', '172'];
    for (var f=0; f<table_fld.length; f++) {
	$('input[name="Field'+table_fld[f]+'"]:radio').change(SetTix);
    }

    $('#Field347').keyup(ShowPromo);
});

$(function() {
    $(document).tooltip();
});
<|endoftext|>


<commit_before>import { shallowMount, mount } from '@vue/test-utils';
import CdrModal from 'componentdir/modal/CdrModal';
import Vue from 'vue';
// import packageJson from '../../../../package.json';
import CdrButton from 'componentdir/button/CdrButton';

describe('CdrModal.vue', () => {
  it('default open, scrolling', (done) => {
    const mockMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "Label is the modal title"
      },
      slots: {
        default: 'Sticky content',
      },
      computed: {
        scrolling: () => true,
      },
      methods: {
        measureContent: mockMeasureContent
      },
      attachToDocument: true,
    });

   expect(wrapper.element).toMatchSnapshot();
   expect(wrapper.find('.cdr-modal__text-fade').exists()).toBe(true);

    Vue.nextTick(() => {
      wrapper.setProps({ opened: false });

      setTimeout(() => {
        expect(wrapper.vm.reallyClosed).toBe(true);
        wrapper.destroy();
        done();
      }, 500);
    });
  });

  it('leaves optional slots empty, handleOpened', (done) => {
    const mockMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: false,
        label: "Label is the modal title"
      },
      slots: {
        default: 'Main content',
      },
      methods: {
        measureContent: mockMeasureContent
      },
      attachToDocument: true,
    });

    wrapper.setProps({ opened: true });
    Vue.nextTick(() => {
      expect(wrapper.element).toMatchSnapshot();

      setTimeout(() => {
        expect(mockMeasureContent).toHaveBeenCalled();
        wrapper.destroy();
        done();
      }, 300);
    });
  });

  it('handleKeyDown', () => {
    const mockMeasureContent = jest.fn();
    const spyOnClick = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "Label is the modal title"
      },
      slots: {
        default: 'Main content',
      },
      methods: {
        onClick: spyOnClick,
        measureContent: mockMeasureContent,
      },
      attachToDocument: true,
    });

    Vue.nextTick(() => {
      wrapper.trigger('keydown', {
        key: 'a'
      });
      expect(spyOnClick).not.toHaveBeenCalled();

      wrapper.trigger('keydown', {
        key: 'Esc',
      });

      wrapper.trigger('keydown', {
        key: 'Escape',
      });

      expect(spyOnClick).toHaveBeenCalledTimes(2);
      wrapper.destroy();
    });
  });

  it('scrolling and fullscreen snapshot', () => {
    const mockMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "Label is the modal title"
      },
      data() {
        return {
          offsetHeight: 400,
          scrollHeight: 500,
          fullscreen: true,
        };
      },
      methods: {
        measureContent: mockMeasureContent,
      },
      slots: {
        scrollingContentSlot: 'Main content',
      },
      attachToDocument: true,
    });

    expect(wrapper.vm.scrolling).toBe(true);
    expect(wrapper.element).toMatchSnapshot();
    wrapper.destroy();
  });

  it('removeNoScroll', () => {
    const mockMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "My Modal Label",
      },
      methods: {
        measureContent: mockMeasureContent,
      },
      slots: {
        scrollingContentSlot: 'Main content',
      },
      attachToDocument: true,
    });
    const { documentElement, body } = document;
    wrapper.vm.removeNoScroll();

    expect(documentElement.classList.contains('noscroll')).toBeFalsy();
    expect(body.classList.contains('noscroll')).toBeFalsy();

    wrapper.destroy();
  });

  it('handleFocus', () => {
    const mockMeasureContent = jest.fn();
    const wrapper = mount(CdrModal, {
      propsData: {
        opened: true,
        label: "My Modal Label",
      },
      methods: {
        measureContent: mockMeasureContent,
      },
      attachToDocument: true,
    });

    const button = wrapper.find('button').element;
    button.focus();
    expect(button).toBe(document.activeElement);

    wrapper.vm.handleFocus({ target: document.createElement('a') });
    expect(document.scrollTop).toBe(undefined);
    expect(document.scrollLeft).toBe(undefined);
    wrapper.destroy();
  });

  it('handleClosed', (done) => {
    global.scrollTo = jest.fn();
    const spyMeasureContent = jest.fn();
    const spyHandleOpened = jest.fn();

    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "My Modal Label",
      },
      data() {
        return {
          offset: { x: 0, y: 0 }
        };
      },
      methods: {
        measureContent: spyMeasureContent,
        handleOpened: spyHandleOpened,
      },
      attachToDocument: true,
    });

    wrapper.vm.handleClosed();

    Vue.nextTick(() => {
      setTimeout(() => {
        expect(wrapper.vm.reallyClosed).toBe(true);
        expect(wrapper.vm.unsubscribe).toBe(null);
        done();
      }, 500);
    });
  });

});<commit_msg>test(modal): update tests<commit_after>import { shallowMount, mount } from '@vue/test-utils';
import CdrModal from 'componentdir/modal/CdrModal';
import Vue from 'vue';
// import packageJson from '../../../../package.json';
import CdrButton from 'componentdir/button/CdrButton';

describe('CdrModal.vue', () => {
  it('default open, scrolling', (done) => {
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "Label is the modal title"
      },
      slots: {
        default: 'Sticky content',
      },
      computed: {
        scrolling: () => true,
      },
      attachToDocument: true,
    });

    expect(wrapper.element).toMatchSnapshot();
    expect(wrapper.find('.cdr-modal__text-fade').exists()).toBe(true);

    Vue.nextTick(() => {
      wrapper.setProps({ opened: false });

      setTimeout(() => {
        expect(wrapper.vm.reallyClosed).toBe(true);
        wrapper.destroy();
        done();
      }, 500);
    });
  });

  it('leaves optional slots empty, handleOpened', (done) => {
    const mockMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: false,
        label: "Label is the modal title"
      },
      slots: {
        default: 'Main content',
      },
      methods: {
        measureContent: mockMeasureContent
      },
      attachToDocument: true,
    });

    wrapper.setProps({ opened: true });
    Vue.nextTick(() => {
      expect(wrapper.element).toMatchSnapshot();

      setTimeout(() => {
        expect(mockMeasureContent).toHaveBeenCalled();
        wrapper.destroy();
        done();
      }, 300);
    });
  });

  it('handleKeyDown', () => {
    const mockMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "Label is the modal title"
      },
      slots: {
        default: 'Main content',
      },
      methods: {
        measureContent: mockMeasureContent,
      },
      attachToDocument: true,
    });

    Vue.nextTick(() => {
      wrapper.trigger('keydown', {
        key: 'a'
      });

      wrapper.trigger('keydown', {
        key: 'Esc',
      });

      wrapper.trigger('keydown', {
        key: 'Escape',
      });

      expect(wrapper.emitted().closed.length).toBe(2);
      wrapper.destroy();
    });
  });

  it('scrolling and fullscreen snapshot', () => {
    const mockMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "Label is the modal title"
      },
      data() {
        return {
          offsetHeight: 400,
          scrollHeight: 500,
          fullscreen: true,
        };
      },
      methods: {
        measureContent: mockMeasureContent,
      },
      slots: {
        scrollingContentSlot: 'Main content',
      },
      attachToDocument: true,
    });

    expect(wrapper.vm.scrolling).toBe(true);
    expect(wrapper.element).toMatchSnapshot();
    wrapper.destroy();
  });

  it('removeNoScroll', () => {
    const mockMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "My Modal Label",
      },
      methods: {
        measureContent: mockMeasureContent,
      },
      slots: {
        scrollingContentSlot: 'Main content',
      },
      attachToDocument: true,
    });
    const { documentElement, body } = document;
    wrapper.vm.removeNoScroll();

    expect(documentElement.classList.contains('noscroll')).toBeFalsy();
    expect(body.classList.contains('noscroll')).toBeFalsy();

    wrapper.destroy();
  });

  it('handleFocus', () => {
    const mockMeasureContent = jest.fn();
    const wrapper = mount(CdrModal, {
      propsData: {
        opened: true,
        label: "My Modal Label",
      },
      methods: {
        measureContent: mockMeasureContent,
      },
      attachToDocument: true,
    });

    const button = wrapper.find('button').element;
    button.focus();
    expect(button).toBe(document.activeElement);

    wrapper.vm.handleFocus({ target: document.createElement('a') });
    expect(document.scrollTop).toBe(undefined);
    expect(document.scrollLeft).toBe(undefined);
    wrapper.destroy();
  });

  it('handleClosed', (done) => {
    global.scrollTo = jest.fn();
    const spyMeasureContent = jest.fn();
    const spyHandleOpened = jest.fn();

    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "My Modal Label",
      },
      data() {
        return {
          offset: { x: 0, y: 0 }
        };
      },
      methods: {
        measureContent: spyMeasureContent,
        handleOpened: spyHandleOpened,
      },
      attachToDocument: true,
    });

    wrapper.vm.handleClosed();

    Vue.nextTick(() => {
      setTimeout(() => {
        expect(wrapper.vm.reallyClosed).toBe(true);
        expect(wrapper.vm.unsubscribe).toBe(null);
        done();
      }, 500);
    });
  });

  it('resize event', (done) => {
    const spyMeasureContent = jest.fn();
    const wrapper = shallowMount(CdrModal, {
      propsData: {
        opened: true,
        label: "Label is the modal title"
      },
      slots: {
        default: 'Sticky content',
      },
      methods: {
        measureContent: spyMeasureContent,
      },
      attachToDocument: true,
    });

    window.dispatchEvent(new Event('resize'));

    setTimeout(() => {
      expect(spyMeasureContent).toHaveBeenCalled();
      wrapper.destroy();
      done();
    }, 500);
  });
});<|endoftext|>


<commit_before>function downloadCSV(isAdmin) {
    // Init CSV array.
    var csv = [
            ['data:text/csv;charset=utf-8,DATE,LOCATION,PEDESTRIAN NUMBER,AUTOMOBILE NUMBER,' +
            'BICYCLE NUMBER,OTHER NUMBER,DESCRIPTION,INJURIES,LICENSE PLATES,PICTURE URL']
    ];
    if (isAdmin) {
        csv.push('CONTACT NAME');
        csv.push('CONTACT PHONE');
        csv.push('CONTACT EMAIL');
    }
    markersDisplayedOnMap.forEach(function(marker) {
        var license_plates = marker.license_plates.split(',').join(';');
        var line = [marker.incidentDate, marker.locationName, marker.pedestrianNum,
                    marker.automobileNum, marker.bicycleNum, marker.otherNum,
                    marker.description, marker.injuries, license_plates,
                    marker.pictureUrl];
        if (isAdmin) {
            line.push(marker.contactName);
            line.push(marker.contactPhone);
            line.push(marker.contactEmail);
        }

        csv.push(line.join(','));
    });
    var csvString = csv.join('\n');

    var encodedUri = encodeURI(csvString);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    document.body.appendChild(link); // Required for FF

    // Download the data file.
    link.click();
}
<commit_msg>Made sure headings are all on top line<commit_after>function downloadCSV(isAdmin) {
    // Init CSV array.
    var csv = [
            ['data:text/csv;charset=utf-8,DATE,LOCATION,PEDESTRIAN NUMBER,AUTOMOBILE NUMBER,' +
            'BICYCLE NUMBER,OTHER NUMBER,DESCRIPTION,INJURIES,LICENSE PLATES,PICTURE URL']
    ];
    if (isAdmin) {
        csv[0] = csv[0] + ',CONTACT NAME';
        csv[0] = csv[0] + ',CONTACT PHONE';
        csv[0] = csv[0] + ',CONTACT EMAIL';
    }
    markersDisplayedOnMap.forEach(function(marker) {
        var license_plates = marker.license_plates.split(',').join(';');
        var line = [marker.incidentDate, marker.locationName, marker.pedestrianNum,
                    marker.automobileNum, marker.bicycleNum, marker.otherNum,
                    marker.description, marker.injuries, license_plates,
                    marker.pictureUrl];
        if (isAdmin) {
            line.push(marker.contactName);
            line.push(marker.contactPhone);
            line.push(marker.contactEmail);
        }

        csv.push(line.join(','));
    });
    var csvString = csv.join('\n');

    var encodedUri = encodeURI(csvString);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    document.body.appendChild(link); // Required for FF

    // Download the data file.
    link.click();
}
<|endoftext|>


<commit_before>'use strict';

var Class       = require( 'uberclass' )
  , path        = require( 'path' )
  , packageJson = require( path.resolve( __dirname + '/../../' ) + '/package.json' )
  , fs          = require( 'fs' )
  , async       = require( 'async' )
  , debug       = require( 'debug' )( 'ModuleLoader' )
  , i           = require( 'i' )()
  , injector    = require( 'injector' )
  , Module;

var ModuleLoader = module.exports = Class.extend(
{
    instance: null,

    getInstance: function() {
        if ( this.instance === null ) {
            this.instance = new this();
        }
        return this.instance;
    }
},
{
    modules: null,

    modulesLoaded: null,

    routesInitialized: null,

    shutdown: function() {
        this.modules.forEach( this.proxy( 'preShutdownHook' ) );
        debug( 'Shutdown complete, if your app hangs one of your modules has not closed all its connections/resources.' );
    },

    preShutdownHook: function( module ) {
        if ( module instanceof Module.Class && typeof module.preShutdown === 'function' ) {
            module.debug( 'Module.preShutdown() hook...' );
            module.preShutdown();
        }
    },

    init: function() {
        this.modules = [];
        this.modulesLoaded = false;
        this.routesInitialized = false;
    },

    moduleIsEnabled: function( moduleName ) {
        return packageJson.bundledDependencies.indexOf( moduleName ) !== -1;
    },

    loadModules: function( env ) {
        Module = injector.getInstance( 'Module' );

        var self = this;

        if ( this.modulesLoaded === false ) {
            debug( 'Loading modules...' );

            // Load each of our modules
            packageJson.bundledDependencies.forEach( this.proxy( 'loadModule', env ) );

            // Fire the configureApp hook on each of our modules giving them a chance to configure the express app
            this.modules.forEach( this.proxy( 'configureAppHook' ) );

            // Load each modules resources
            this.modules.forEach( this.proxy( 'preResourcesHook' ) );

            // Load each modules resources
            this.modules.forEach( this.proxy( 'loadModuleResources' ) );

            // Fire the modulesLoadedHook hook on each of our modules letting them know that all modules have finished loading
            this.modules.forEach( this.proxy( 'modulesLoadedHook' ) );

            // Let the module loader know we have already loaded our modules
            this.modulesLoaded = true;
        } else {
            debug( 'Warning: All modules have already been loaded.' );
        }
    },

    loadModule: function( env, moduleName ) {
        if (typeof env !== "undefined" && env !== null) {
            process.env = env;
        }

        debug( [ 'Loading the', moduleName, 'module' ].join( ' ' ) + '...' );
        var module = require( moduleName );

        var moduleLowerCamelCase = i.camelize( moduleName.replace( /\-/ig, '_' ), false );

        debug( [ 'Adding the', moduleLowerCamelCase, 'module to the injector' ].join( ' ' ) + '...' );
        injector.instance( moduleLowerCamelCase, module );

        // Add the module into our modules array so we can keep track of them internally and call hooks in their module.js file
        this.modules.push( module );
    },

    configureAppHook: function( module ) {
        if ( module instanceof Module.Class && typeof module.configureApp === 'function' ) {
            module.debug( 'Module.configureApp() hook...' );

            injector.getInstance( 'app' ).configure( module.proxy( 'configureApp', injector.getInstance( 'app' ), injector.getInstance( 'express' ) ) );
        }
    },

    preResourcesHook: function( module ) {
        if ( module instanceof Module.Class && typeof module.preResources === 'function' ) {
            module.debug( 'Module.preResources() hook...' );

            module.hook( 'preResources' );
        }
    },

    loadModuleResources: function( module ) {
        if ( module instanceof Module.Class && typeof module.loadResources === 'function' ) {
            module.debug( 'Module.loadResources() hook...' );
            debug( [ 'loadResources for module', module.name ].join( ' ' ) );

            module.loadResources();
        }
    },

    modulesLoadedHook: function( module ) {
        if ( module instanceof Module.Class && typeof module.modulesLoaded === 'function' ) {
            module.debug( 'Module.modulesLoaded() hook...' );

            module.hook( 'modulesLoaded' );
        }
    },

    initializeRoutes: function() {
        if ( this.routesInitialized === false ) {
            // Give the modules notice that we are about to add our routes to the app
            this.modules.forEach( this.proxy( 'preRouteHook' ) );

            debug( 'Initializing routes...' );
            this.modules.forEach( this.proxy( 'initializeModuleRoutes' ) );

            // We only want to do this once
            this.routesInitialized = true;
        } else {
            debug( 'Warning: All modules routes have been initialized already.' );
        }
    },

    preRouteHook: function( module ) {
        if ( module instanceof Module.Class && typeof module.preRoute === 'function' ) {
            module.debug( 'Module.configureApp() hook...' );
            module.preRoute();
        }
    },

    initializeModuleRoutes: function( module ) {
        if ( module instanceof Module.Class ) {
            module.debug( [ 'Initializing routes...' ].join( ' ' ) );
            module.initRoutes();
        }
    }
});<commit_msg>feature(modules): Loader implementation for EventEmitter<commit_after>'use strict';

var injector    = require( 'injector' )
  , async       = require( 'async' )
  , path        = require( 'path' )
  , fs          = require( 'fs' )
  , async       = require( 'async' )
  , Class       = require( 'classes' ).Class
  , packageJson = injector.getInstance( 'packageJson' )
  , debug       = require( 'debug' )( 'ModuleLoader' )
  , i           = require( 'i' )()
  , Module;

var ModuleLoader = module.exports = Class.extend(
{
    instance: null,

    getInstance: function() {
        if ( this.instance === null ) {
            this.instance = new this();
        }
        return this.instance;
    }
},
{
    modules: null,

    modulesLoaded: null,

    modulesLoading: false,

    routesInitialized: null,

    hookOrder: [
        'configureAppHook',
        'preResourcesHook',
        'loadModuleResources',
        'modulesLoadedHook'
    ],

    shutdown: function() {
        this.modules.forEach( this.proxy( 'preShutdownHook' ) );
        debug( 'Shutdown complete, if your app hangs one of your modules has not closed all its connections/resources.' );
    },

    preShutdownHook: function( module ) {
        if ( module instanceof Module.Class && typeof module.preShutdown === 'function' ) {
            module.debug( 'Module.preShutdown() hook...' );
            module.preShutdown();
        }
    },

    init: function() {
        this.modules = [];
        this.modulesLoaded = false;
        this.routesInitialized = false;
    },

    moduleIsEnabled: function( moduleName ) {
        return packageJson.bundledDependencies.indexOf( moduleName ) !== -1;
    },

    loadModules: function( env ) {
        var deps = packageJson.bundledDependencies
          , modules = this.modules
          , loader = this;

        Module = injector.getInstance( 'Module' );

        this.emit( 'preLoadModules' );

        if ( !this.modulesLoading && !this.modulesLoaded ) {
            debug( 'Loading modules...' );

            async.waterfall(
                [
                    function load( callback ) {
                        async.forEach( deps, loader.proxy( 'loadModule', env ), callback );
                    },

                    function runHooks( hooksCallback ) {
                        async.forEach(
                            loader.hookOrder,
                            function runHook( hookName, hookCallback ) {
                                async.forEach(
                                    modules,
                                    loader.proxy( hookName ),
                                    hookCallback
                                );
                            },
                            hooksCallback
                        );
                    }
                ],
                function loadComplete( err ) {
                    if ( !!err ) {
                        throw new Error( 'Error loading modules: ' + err );
                    } else {
                        loader.modulesLoaded = true;
                        loader.emit( 'modulesLoaded' );
                    }
                }
            );
        } else if ( !!this.modulesLoading ) {
            debug( 'Modules are already loading...' );
        } else {
            debug( 'Warning: All modules have already been loaded.' );
        }
    },

    loadModule: function( env, moduleName, callback ) {
        if ( typeof env !== "undefined" && env !== null ) {
            process.env = env;
        }

        debug( [ 'Loading the', moduleName, 'module' ].join( ' ' ) + '...' );
        var module = require( moduleName );
        var moduleLowerCamelCase = i.camelize( moduleName.replace( /\-/ig, '_' ), false );

        debug( [ 'Adding the', moduleLowerCamelCase, 'module to the injector' ].join( ' ' ) + '...' );
        injector.instance( moduleLowerCamelCase, module );

        this.modules.push( module );

        callback( null );
    },

    configureAppHook: function( module, callback ) {
        if ( module instanceof Module.Class && typeof module.configureApp === 'function' ) {
            module.debug( 'Module.configureApp() hook...' );

            module.on( 'appReady', callback );
            injector.getInstance( 'app' ).configure( module.proxy( 'configureApp', injector.getInstance( 'app' ), injector.getInstance( 'express' ) ) );
        } else {
            callback( null );
        }
    },

    preResourcesHook: function( module, callback ) {
        if ( module instanceof Module.Class && typeof module.preResources === 'function' ) {
            module.debug( 'Module.preResources() hook...' );

            module.on( 'resourcesReady', callback );
            module.hook( 'preResources' );
        } else {
            callback( null );
        }
    },

    loadModuleResources: function( module, callback ) {
        if ( module instanceof Module.Class && typeof module.loadResources === 'function' ) {
            module.debug( 'Module.loadResources() hook...' );
            debug( [ 'loadResources for module', module.name ].join( ' ' ) );

            module.on( 'resourcesLoaded', callback );
            module.loadResources();
        } else {
            callback( null );
        }
    },

    modulesLoadedHook: function( module, callback ) {
        if ( module instanceof Module.Class && typeof module.modulesLoaded === 'function' ) {
            module.debug( 'Module.modulesLoaded() hook...' );

            module.on( 'ready', callback );
            module.hook( 'modulesLoaded' );
        } else {
            callback( null );
        }
    },

    // @TODO make this support async
    initializeRoutes: function() {
        if ( this.routesInitialized === false ) {
            // Give the modules notice that we are about to add our routes to the app
            this.modules.forEach( this.proxy( 'preRouteHook' ) );

            debug( 'Initializing routes...' );
            this.modules.forEach( this.proxy( 'initializeModuleRoutes' ) );

            // We only want to do this once
            this.routesInitialized = true;

            this.emit( 'routesInitialized' );
        } else {
            debug( 'Warning: All modules routes have been initialized already.' );
        }
    },

    preRouteHook: function( module ) {
        if ( module instanceof Module.Class && typeof module.preRoute === 'function' ) {
            module.debug( 'Module.configureApp() hook...' );
            module.preRoute();
        }
    },

    initializeModuleRoutes: function( module ) {
        if ( module instanceof Module.Class ) {
            module.debug( [ 'Initializing routes...' ].join( ' ' ) );
            module.initRoutes();
        }
    }
});<|endoftext|>


<commit_before>var $module=(function($B){

var mod = {
    dis:function(src){
        $B.$py_module_path['__main__'] = $B.brython_path
        return __BRYTHON__.py2js(src,'__main__','__main__',
            $B.builtins_scope).to_js()
    }
}
return mod

})(__BRYTHON__)<commit_msg>Add flags to stdlib module dis<commit_after>var $module=(function($B){

var mod = {
    dis:function(src){
        $B.$py_module_path['__main__'] = $B.brython_path
        return __BRYTHON__.py2js(src,'__main__','__main__',
            $B.builtins_scope).to_js()
    },
    OPTIMIZED: 1,
    NEWLOCALS: 2,
    VARARGS: 4,
    VARKEYWORDS: 8,
    NESTED: 16,
    GENERATOR: 32,
    NOFREE: 64,
    COROUTINE: 128,
    ITERABLE_COROUTINE: 256,
    ASYNC_GENERATOR: 512
}
return mod

})(__BRYTHON__)<|endoftext|>


<commit_before><commit_msg>oops, inverted test...<commit_after><|endoftext|>