<commit_before>/*******************************************
* Darrel Kathan - 10/6/2015
*******************************************/
'use strict';

var cluster = require('cluster'),
	url = require('url'),
	fs = require('fs'),
	vm = require('vm'),
	os = require('os'),
	util = require('util'),
	path = require('path'),
	express = require('express'),
	cookieParser = require('cookie-parser'),
	app = express(),
	config_name = 'js-cgi.config',
	config = {},
	error = function(err) {
		console.error('Error:'+err);
	};

/*******************************************
* Funnel console.log and console.error
* input to log file.
*******************************************/
console.log = function(){
	var d = new Date(),
		log_msg = d.toString()+' - ('+process.pid+'): ',
		stack = new Error().stack;

	this._stdout.write(log_msg + util.format.apply(this, arguments) + stack + '\n');
	if(config.output_log){
		fs.appendFile(config.output_log, log_msg + util.format.apply(this, arguments) + '\n', function(){return;});
	}
};

console.error = function(msg, stack){
	var d = new Date(),
		log_msg = d.toString()+' - ('+process.pid+'): '+msg;
	util.error(log_msg, stack);
	if(config.output_log){
		fs.appendFile(config.output_log, log_msg+'\n', function(){});
		fs.appendFile(config.output_log, stack+'\n', function(){return;});
	}
};

/*******************************************
* Prepare web server to handle cookies and
* format JSON.
*******************************************/
app.use(cookieParser());
app.set('json spaces', 4);

config.output_log = path.dirname(process.argv[1])+'/js-cgi.log';
//console.log(config.output_log);
if(fs.existsSync(path.join(__dirname, config_name))){
	//Load the congfig file
	console.log('Loading '+config_name+'...');
	config = require('./'+config_name);
}else{
	//Use the default congfig
	console.log('Loading default config...');
	config.port = 3000;
	config.localhostOnly = true;
	//config.workers = 2;
	config.timeout = 30000;
	config.workers = (os.cpus().length/2)-1;//For some reason cpus.length is reports twice as many cores than actual.
}

/*******************************************
* Override the "require" function to watch
* if required files have change and expire
* them from cache when they do.
*******************************************/
var assert = require('assert').ok,
	Module = require('module');
if(typeof Module._watching !== 'object'){
	Module._watching = {};
}
function watchRequired(fn){
	/*var fs = require('fs')
		console = console;*/
	//console.log(fn);
	if(Module._watching && !Module._watching.hasOwnProperty(fn)){
		if(fs.existsSync(fn)){
			console.log('Watching '+fn);
			Module._watching[fn] = fs.watch(fn, function(event,f){
			//Module._watching[fn] = fs.watchFile(fn, function(curr, prev){
				console.log(fn, event);

				if(Module._cache.hasOwnProperty(fn)){
					console.log('Expiring '+fn);
					return delete Module._cache[fn];
					//fs.unwatch(fn, function(){return;});
				}
				return;
			});
		}
	}
}

Module.prototype.require = function(path) {
  assert(path, 'missing path');
  assert((typeof path === 'string'), 'path must be a string');
  watchRequired(Module._resolveFilename(path, this));
  return Module._load(path, this);
};

/*******************************************
* Start up the server node.
*******************************************/
if (cluster.isMaster) {
	cluster.globals = {};
	cluster.fork();//At least one worker is required.

	for(var w = 2; w <= config.workers;w++){
		cluster.fork().on('error', error);
	}

	cluster.on('disconnect', function(worker) {
		console.error('disconnect!');
		cluster.fork().on('error', error);
	});
} else {
	// the worker
	var domain = require('domain'),
		server,
		d = domain.create();

	d.on('error', function(er) {
		console.error('error', er.stack);
		try {
			// make sure we close down if it times out
			var killtimer = setTimeout(function() {
				console.error('Killing process. Timeout expired ('+config.timeout+' ms)');
				return process.exit(1);
			}, config.timeout);
			// But don't keep the process open just for that!
			killtimer.unref();

			// stop taking new requests.
			server.close();

			// Let the master know we're dead.  This will trigger a
			// 'disconnect' in the cluster master, and then it will fork
			// a new worker.
			cluster.worker.disconnect();
		} catch (er2) {
			// oh well, not much we can do at this point.
			console.error(er2.stack);
		}
	});

    /*******************************************
    * Now run the handler function in the domain.
    *******************************************/
    d.run(function() {
		console.log('Listening on '+config.port);

		server = app.listen(config.port);

		app.all('*', function(req, res){
			//console.log('req');
			return handleRequest(req, res);
		});
	});
}

function setRequiredCacheTimestamp(name){
	if(require.cache[process.execPath][name]){
		return require.cache[process.execPath][name];
	}
}

/*******************************************
* This is where all of the web requests are
* handled.
*******************************************/
function handleRequest(req, res) {
	var url_obj = url.parse(req.url, true),
		file_path;
	/*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
		//res.writeHead(401);
		res.end(401);
	}*/

	if(req.headers.path_translated && url_obj.pathname){
		file_path = req.headers.path_translated+url_obj.pathname;
	}else{
		file_path = url_obj.pathname;
	}

	//console.log('file_path:'+file_path);
	function resolveModule(module) {
		if (module.charAt(0) !== '.'){
			//console.log('No need to resolve '+module);
			return module;
		}
		//console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
		return path.resolve(path.dirname(file_path), module);
	}

	//If the requested file exists...
	fs.exists(file_path, function(exists){
		if(exists){
			fs.readFile(file_path, function (err, source) {
				if(err){
					//Error reading file
					console.error(err, err.stack);
					res.writeHead(500, err);
					return res.send(err.toString());
				}
				try{
					console.log('Request: '+file_path);
					//console.log(require.cache);
					var sandbox = {
						//globals: globals,
						console: console,
						setImmediate: setImmediate,
						require: function(name) {
							var mod_path = resolveModule(name);
							//watchRequired(mod_path);
							return require(mod_path);
						},
						req: req,
						res: res
					};
					var c = vm.createContext(sandbox);
            		//return vm.runInContext(source, c, {displayErrors: true});
					return vm.runInContext('(function() {try{'+source+'}catch(e){console.log(e);res.status(500).send(e.toString());}})();', c, {displayErrors: true});
				}catch(err){
					console.error(err, err.stack);
					//res.writeHead(500);
					return res.status(500).send(err.toString());
				}
			});
		}else{
			//File does not exist
			//res.writeHead(404, 'File not found.');
			return res.status(404).send('File not found.');
		}
	});
}

/*******************************************
* The following handleRequest options were
* less successful.
*******************************************/
function handleRequestScript(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }

  function resolveModule(module) {
    if (module.charAt(0) !== '.'){
      //console.log('No need to resolve '+module);
      return module;
    }
    //console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
    return path.resolve(path.dirname(file_path), module);
  }

  function myRequire(name) {
    return require(resolveModule(name));
  }

  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
    	fs.readFile(file_path, function(err, content){
	      try{
	      	var path_dir = file_path.split("/");
	      	path_dir.pop();
	      	path_dir = path_dir.join('/');
	      	//console.log(path_dir);
	      	process.chdir(path_dir);
	      	//console.log(process.cwd());
	      	var script = Function('req', 'res', 'globals', 'require', content);
	      	//console.log(script.toString());
	      	console.log(file_path);
	      	script(req, res, cluster.globals, myRequire);

	      }catch(err){
	      	res.writeHead(500);
	      	console.error(err.stack)
	      	res.end(err+' in '+file_path);
	      }
	    });
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      res.end('File '+file_path+' not found.');
    }
  });
}

function handleRequestRequire(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }

  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
      var script = require(file_path);
      if(typeof script === 'function'){
      	script(req, res, cluster.globals);
      }else{
      	res.writeHead(500);
      	return res.send('Script is not configured correctly.');
      }
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      return res.send('File '+file_path+' not found.');
    }
  });
}

function handleRequestRIC(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }
  //console.log('file_path:'+file_path);
  function resolveModule(module) {
    if (module.charAt(0) !== '.'){
      //console.log('No need to resolve '+module);
      return module;
    }
    //console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
    return path.resolve(path.dirname(file_path), module);
  }
  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
      fs.readFile(file_path, function (err, source) {
        if(err){
          //Error reading file
          console.error(err, err.stack);
          res.writeHead(500, err);
          return res.send(err.toString());
        }
        try{
          //console.log('filename:'+file_path);

          //var script = vm.createScript('try{\n'+source+'\n}catch(err){console.error(err, err.stack);res.writeHead(500);res.end(err.toString());}');
          var script = vm.createScript(source);
          //console.log('pre execute:'+g);
          var sandbox = {
                  //globals: globals,
                  console: console,
                  require: function(name) {
                           return require(resolveModule(name));
                       },
                req: req,
                res: res,
                displayErrors: true
            };

          return script.runInNewContext(sandbox);

        }catch(err){
          console.error(err, err.stack);
          res.writeHead(500);
          return res.send(err.toString());
        }
      });
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      return res.send('File not found.');
    }
  });
}<commit_msg>CI Tue Oct  6 12:16:31 CDT 2015<commit_after>/*******************************************
* js-cgi.js
* Copyright (c) 2015, Darrel Kathan
* Licensed under the MIT license.
*
* A current version and some documentation is available at
*    https://github.com/kathan/js-cgi
*
* @summary     Javascript CGI process manager
* @description js-cgi is a javascript CGI process manager, similar to php-fpm, for executing node.js/io.js compatible scripts behind NGINX or Apache.
* @file        js-cgi.js
* @version     0.1.0
* @author      Darrel Kathan
* @license     MIT
*******************************************/
'use strict';

var cluster = require('cluster'),
	url = require('url'),
	fs = require('fs'),
	vm = require('vm'),
	os = require('os'),
	util = require('util'),
	path = require('path'),
	express = require('express'),
	cookieParser = require('cookie-parser'),
	app = express(),
	config_name = 'js-cgi.config',
	config = {},
	error = function(err) {
		console.error('Error:'+err);
	};

/*******************************************
* Funnel console.log and console.error
* input to log file.
*******************************************/
console.log = function(){
	var d = new Date(),
		log_msg = d.toString()+' - ('+process.pid+'): ',
		stack = new Error().stack;

	this._stdout.write(log_msg + util.format.apply(this, arguments) + stack + '\n');
	if(config.output_log){
		fs.appendFile(config.output_log, log_msg + util.format.apply(this, arguments) + '\n', function(){return;});
	}
};

console.error = function(msg, stack){
	var d = new Date(),
		log_msg = d.toString()+' - ('+process.pid+'): '+msg;
	util.error(log_msg, stack);
	if(config.output_log){
		fs.appendFile(config.output_log, log_msg+'\n', function(){});
		fs.appendFile(config.output_log, stack+'\n', function(){return;});
	}
};

/*******************************************
* Prepare web server to handle cookies and
* format JSON.
*******************************************/
app.use(cookieParser());
app.set('json spaces', 4);

config.output_log = path.dirname(process.argv[1])+'/js-cgi.log';
//console.log(config.output_log);
if(fs.existsSync(path.join(__dirname, config_name))){
	//Load the congfig file
	console.log('Loading '+config_name+'...');
	config = require('./'+config_name);
}else{
	//Use the default congfig
	console.log('Loading default config...');
	config.port = 3000;
	config.localhostOnly = true;
	//config.workers = 2;
	config.timeout = 30000;
	config.workers = (os.cpus().length/2)-1;//For some reason cpus.length is reports twice as many cores than actual.
}

/*******************************************
* Override the "require" function to watch
* if required files have change and expire
* them from cache when they do.
*******************************************/
var assert = require('assert').ok,
	Module = require('module');
if(typeof Module._watching !== 'object'){
	Module._watching = {};
}
function watchRequired(fn){
	/*var fs = require('fs')
		console = console;*/
	//console.log(fn);
	if(Module._watching && !Module._watching.hasOwnProperty(fn)){
		if(fs.existsSync(fn)){
			console.log('Watching '+fn);
			Module._watching[fn] = fs.watch(fn, function(event,f){
			//Module._watching[fn] = fs.watchFile(fn, function(curr, prev){
				console.log(fn, event);

				if(Module._cache.hasOwnProperty(fn)){
					console.log('Expiring '+fn);
					return delete Module._cache[fn];
					//fs.unwatch(fn, function(){return;});
				}
				return;
			});
		}
	}
}

Module.prototype.require = function(path) {
  assert(path, 'missing path');
  assert((typeof path === 'string'), 'path must be a string');
  watchRequired(Module._resolveFilename(path, this));
  return Module._load(path, this);
};

/*******************************************
* Start up the server node.
*******************************************/
if (cluster.isMaster) {
	cluster.globals = {};
	cluster.fork();//At least one worker is required.

	for(var w = 2; w <= config.workers;w++){
		cluster.fork().on('error', error);
	}

	cluster.on('disconnect', function(worker) {
		console.error('disconnect!');
		cluster.fork().on('error', error);
	});
} else {
	// the worker
	var domain = require('domain'),
		server,
		d = domain.create();

	d.on('error', function(er) {
		console.error('error', er.stack);
		try {
			// make sure we close down if it times out
			var killtimer = setTimeout(function() {
				console.error('Killing process. Timeout expired ('+config.timeout+' ms)');
				return process.exit(1);
			}, config.timeout);
			// But don't keep the process open just for that!
			killtimer.unref();

			// stop taking new requests.
			server.close();

			// Let the master know we're dead.  This will trigger a
			// 'disconnect' in the cluster master, and then it will fork
			// a new worker.
			cluster.worker.disconnect();
		} catch (er2) {
			// oh well, not much we can do at this point.
			console.error(er2.stack);
		}
	});

    /*******************************************
    * Now run the handler function in the domain.
    *******************************************/
    d.run(function() {
		console.log('Listening on '+config.port);

		server = app.listen(config.port);

		app.all('*', function(req, res){
			//console.log('req');
			return handleRequest(req, res);
		});
	});
}

function setRequiredCacheTimestamp(name){
	if(require.cache[process.execPath][name]){
		return require.cache[process.execPath][name];
	}
}

/*******************************************
* This is where all of the web requests are
* handled.
*******************************************/
function handleRequest(req, res) {
	var url_obj = url.parse(req.url, true),
		file_path;
	/*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
		//res.writeHead(401);
		res.end(401);
	}*/

	if(req.headers.path_translated && url_obj.pathname){
		file_path = req.headers.path_translated+url_obj.pathname;
	}else{
		file_path = url_obj.pathname;
	}

	//console.log('file_path:'+file_path);
	function resolveModule(module) {
		if (module.charAt(0) !== '.'){
			//console.log('No need to resolve '+module);
			return module;
		}
		//console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
		return path.resolve(path.dirname(file_path), module);
	}

	//If the requested file exists...
	fs.exists(file_path, function(exists){
		if(exists){
			fs.readFile(file_path, function (err, source) {
				if(err){
					//Error reading file
					console.error(err, err.stack);
					res.writeHead(500, err);
					return res.send(err.toString());
				}
				try{
					console.log('Request: '+file_path);
					//console.log(require.cache);
					var sandbox = {
						//globals: globals,
						console: console,
						setImmediate: setImmediate,
						require: function(name) {
							var mod_path = resolveModule(name);
							//watchRequired(mod_path);
							return require(mod_path);
						},
						req: req,
						res: res
					};
					var c = vm.createContext(sandbox);
            		//return vm.runInContext(source, c, {displayErrors: true});
					return vm.runInContext('(function() {try{'+source+'}catch(e){console.log(e);res.status(500).send(e.toString());}})();', c, {displayErrors: true});
				}catch(err){
					console.error(err, err.stack);
					//res.writeHead(500);
					return res.status(500).send(err.toString());
				}
			});
		}else{
			//File does not exist
			//res.writeHead(404, 'File not found.');
			return res.status(404).send('File not found.');
		}
	});
}

/*******************************************
* The following handleRequest options were
* less successful.
*******************************************/
function handleRequestScript(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }

  function resolveModule(module) {
    if (module.charAt(0) !== '.'){
      //console.log('No need to resolve '+module);
      return module;
    }
    //console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
    return path.resolve(path.dirname(file_path), module);
  }

  function myRequire(name) {
    return require(resolveModule(name));
  }

  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
    	fs.readFile(file_path, function(err, content){
	      try{
	      	var path_dir = file_path.split("/");
	      	path_dir.pop();
	      	path_dir = path_dir.join('/');
	      	//console.log(path_dir);
	      	process.chdir(path_dir);
	      	//console.log(process.cwd());
	      	var script = Function('req', 'res', 'globals', 'require', content);
	      	//console.log(script.toString());
	      	console.log(file_path);
	      	script(req, res, cluster.globals, myRequire);

	      }catch(err){
	      	res.writeHead(500);
	      	console.error(err.stack)
	      	res.end(err+' in '+file_path);
	      }
	    });
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      res.end('File '+file_path+' not found.');
    }
  });
}

function handleRequestRequire(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }

  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
      var script = require(file_path);
      if(typeof script === 'function'){
      	script(req, res, cluster.globals);
      }else{
      	res.writeHead(500);
      	return res.send('Script is not configured correctly.');
      }
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      return res.send('File '+file_path+' not found.');
    }
  });
}

function handleRequestRIC(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }
  //console.log('file_path:'+file_path);
  function resolveModule(module) {
    if (module.charAt(0) !== '.'){
      //console.log('No need to resolve '+module);
      return module;
    }
    //console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
    return path.resolve(path.dirname(file_path), module);
  }
  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
      fs.readFile(file_path, function (err, source) {
        if(err){
          //Error reading file
          console.error(err, err.stack);
          res.writeHead(500, err);
          return res.send(err.toString());
        }
        try{
          //console.log('filename:'+file_path);

          //var script = vm.createScript('try{\n'+source+'\n}catch(err){console.error(err, err.stack);res.writeHead(500);res.end(err.toString());}');
          var script = vm.createScript(source);
          //console.log('pre execute:'+g);
          var sandbox = {
                  //globals: globals,
                  console: console,
                  require: function(name) {
                           return require(resolveModule(name));
                       },
                req: req,
                res: res,
                displayErrors: true
            };

          return script.runInNewContext(sandbox);

        }catch(err){
          console.error(err, err.stack);
          res.writeHead(500);
          return res.send(err.toString());
        }
      });
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      return res.send('File not found.');
    }
  });
}<|endoftext|>


<commit_before>/**
 * MPL: A library for parsing and evaluating modal propositional logic.
 *
 * @author  Ross Kirsling
 * @version 1.0.0
 */

var MPL = (function() {
  'use strict';

  // sub-regexes
  var beginPart         = '^\\(',
      unaryPart         = '(?:~|\\[\\]|<>)',
      propOrBinaryPart  = '(?:\\w+|\\(.*\\))',
      subwffPart        = unaryPart + '*' + propOrBinaryPart,
      endPart           = '\\)$';

  // binary operator regexes
  var conjRegEx = new RegExp(beginPart + '(' + subwffPart + ')&('   + subwffPart + ')' + endPart), // (p&q)
      disjRegEx = new RegExp(beginPart + '(' + subwffPart + ')\\|(' + subwffPart + ')' + endPart), // (p|q)
      implRegEx = new RegExp(beginPart + '(' + subwffPart + ')->('  + subwffPart + ')' + endPart), // (p->q)
      equiRegEx = new RegExp(beginPart + '(' + subwffPart + ')<->(' + subwffPart + ')' + endPart); // (p<->q)

  // proposition regex
  var propRegEx = /^\w+$/;

  // regex to check if wff DOESN'T need outer parentheses;
  // i.e., wff is prop, is parenthesized, or starts with unary operator
  var parenCheckRegEx = new RegExp('^' + propOrBinaryPart + '$|^' + unaryPart);

  /**
   * Helper function for removing all whitespace from a string.
   * @private
   */
  function removeWhitespace(str) {
    return str.match(/\S+/g).join('');
  }

  /**
   * Converts MPL wff string to JSON object.
   * @private
   */
  function _wffToJSON(wff) {
    var json    = {},
        subwffs = [];

    if(propRegEx.test(wff))
      json.prop = wff;
    else if(wff.charAt(0) === '~')
      json.neg = _wffToJSON(wff.slice(1));
    else if(wff.substr(0, 2) === '[]')
      json.nec = _wffToJSON(wff.slice(2));
    else if(wff.substr(0, 2) === '<>')
      json.poss = _wffToJSON(wff.slice(2));
    else if(subwffs = wff.match(conjRegEx))
      json.conj = [_wffToJSON(subwffs[1]), _wffToJSON(subwffs[2])];
    else if(subwffs = wff.match(disjRegEx))
      json.disj = [_wffToJSON(subwffs[1]), _wffToJSON(subwffs[2])];
    else if(subwffs = wff.match(implRegEx))
      json.impl = [_wffToJSON(subwffs[1]), _wffToJSON(subwffs[2])];
    else if(subwffs = wff.match(equiRegEx))
      json.equi = [_wffToJSON(subwffs[1]), _wffToJSON(subwffs[2])];
    else
      throw new Error('invalid wff!');

    return json;
  }

  /**
   * Preprocesses MPL wff string, then converts to JSON object using previous function.
   */
  function wffToJSON(wff) {
    wff = removeWhitespace(wff);
    if(!parenCheckRegEx.test(wff)) wff = '(' + wff + ')';

    return _wffToJSON(wff);
  }

  /**
   * Converts the JSON representation of an MPL wff to its string representation.
   */
  function jsonToWff(json) {
    if(json.prop)
      return json.prop;
    else if(json.neg)
      return '~' + jsonToWff(json.neg);
    else if(json.nec)
      return '[]' + jsonToWff(json.nec);
    else if(json.poss)
      return '<>' + jsonToWff(json.poss);
    else if(json.conj && json.conj.length === 2)
      return '(' + jsonToWff(json.conj[0]) + ' & ' + jsonToWff(json.conj[1]) + ')';
    else if(json.disj && json.disj.length === 2)
      return '(' + jsonToWff(json.disj[0]) + ' | ' + jsonToWff(json.disj[1]) + ')';
    else if(json.impl && json.impl.length === 2)
      return '(' + jsonToWff(json.impl[0]) + ' -> ' + jsonToWff(json.impl[1]) + ')';
    else if(json.equi && json.equi.length === 2)
      return '(' + jsonToWff(json.equi[0]) + ' <-> ' + jsonToWff(json.equi[1]) + ')';
    else
      throw new Error('invalid JSON for formula!');
  }

  /**
   * Converts an MPL wff string to a LaTeX expression.
   */
  function wffToLaTeX(wff) {
    return wff.replace(/~/g,    '\\lnot{}')
              .replace(/\[\]/g, '\\Box{}')
              .replace(/<>/g,   '\\Diamond{}')
              .replace(/&/g,    '\\land{}')
              .replace(/\|/g,   '\\lor{}')
              .replace(/<->/g,  '\\leftrightarrow{}')
              .replace(/->/g,   '\\rightarrow{}');
  }

  /**
   * Converts the JSON representation of an MPL wff to a LaTeX expression.
   */
  function jsonToLaTeX(json) {
    return wffToLaTeX(jsonToWff(json));
  }

  /**
   * Converts an (ASCII) MPL wff string to a Unicode string.
   */
  function wffToUnicode(wff) {
    wff = removeWhitespace(wff);
    return wff.replace(/~/g,    '\u00ac')
              .replace(/\[\]/g, '\u25a1')
              .replace(/<>/g,   '\u22c4')
              .replace(/&/g,    ' \u2227 ')
              .replace(/\|/g,   ' \u2228 ')
              .replace(/<->/g,  ' \u2194 ')
              .replace(/->/g,   ' \u2192 ');
  }

  /**
   * Converts the JSON representation of an MPL wff to a Unicode string for displaying.
   */
  function jsonToUnicode(json) {
    return wffToUnicode(jsonToWff(json));
  }

  /**
   * Constructor for Kripke model.
   * @constructor
   */
  function Model(propvars, states, relation) {
    // array of names of propositional variables in use
    this.propvars = propvars;

    // array of states in model, where each state is represented by a truth assignment;
    // i.e., an array of booleans corresponding to propvars
    this.states = states;

    // accessibility relation represented as array of arrays;
    // one subarray for each state in model, which is a list of successor state indices
    this.relation = relation;

    // returns truth value for a given proposition at a given state in the model
    this.valuation = function(prop, state) {
      return this.states[state][this.propvars.indexOf(prop)];
    };
  }

  /**
   * Evaluate truth of a wff at a given state within a given model.
   */
  function truth(model, state, wff) {
    if(wff.prop)
      return model.valuation(wff.prop, state);
    else if(wff.neg)
      return !truth(model, state, wff.neg);
    else if(wff.conj)
      return wff.conj.every(function(subwff) { return truth(model, state, subwff); });
    else if(wff.disj)
      return wff.disj.some(function(subwff) { return truth(model, state, subwff); });
    else if(wff.impl)
      return (!truth(model, state, wff.impl[0]) || truth(model, state, wff.impl[1]));
    else if(wff.equi)
      return (truth(model, state, wff.equi[0]) === truth(model, state, wff.equi[1]));
    else if(wff.nec)
      return model.relation[state].every(function(succState) { return truth(model, succState, wff.nec) });
    else if(wff.poss)
      return model.relation[state].some(function(succState) { return truth(model, succState, wff.poss) });
    else
      throw new Error('invalid formula!');
  }

  // export public methods
  return {
    wffToJSON: wffToJSON,
    jsonToWff: jsonToWff,
    wffToLaTeX: wffToLaTeX,
    jsonToLaTeX: jsonToLaTeX,
    wffToUnicode: wffToUnicode,
    jsonToUnicode: jsonToUnicode,
    Model: Model,
    truth: truth
  };

})();
<commit_msg>MPL: Textual cleanup<commit_after>/**
 * MPL: A library for parsing and evaluating modal propositional logic.
 *
 * @author  Ross Kirsling
 * @version 1.0.0
 */

var MPL = (function() {
  'use strict';

  // sub-regexes
  var beginPart         = '^\\(',
      unaryPart         = '(?:~|\\[\\]|<>)',
      propOrBinaryPart  = '(?:\\w+|\\(.*\\))',
      subwffPart        = unaryPart + '*' + propOrBinaryPart,
      endPart           = '\\)$';

  // binary connective regexes
  var conjRegEx = new RegExp(beginPart + '(' + subwffPart + ')&('   + subwffPart + ')' + endPart), // (p&q)
      disjRegEx = new RegExp(beginPart + '(' + subwffPart + ')\\|(' + subwffPart + ')' + endPart), // (p|q)
      implRegEx = new RegExp(beginPart + '(' + subwffPart + ')->('  + subwffPart + ')' + endPart), // (p->q)
      equiRegEx = new RegExp(beginPart + '(' + subwffPart + ')<->(' + subwffPart + ')' + endPart); // (p<->q)

  // proposition regex
  var propRegEx = /^\w+$/;

  // regex to check if a well-formed formula DOESN'T need outer parentheses,
  // i.e., wff is a proposition, is parenthesized, or starts with a unary connective
  var parenCheckRegEx = new RegExp('^' + propOrBinaryPart + '$|^' + unaryPart);

  /**
   * Helper function for removing all whitespace from a string.
   * @private
   */
  function _removeWhitespace(str) {
    return str.match(/\S+/g).join('');
  }

  /**
   * Converts an MPL wff string to its JSON representation.
   * @private
   */
  function _wffToJSON(wff) {
    var json    = {},
        subwffs = [];

    if(propRegEx.test(wff))
      json.prop = wff;
    else if(wff.charAt(0) === '~')
      json.neg = _wffToJSON(wff.slice(1));
    else if(wff.substr(0, 2) === '[]')
      json.nec = _wffToJSON(wff.slice(2));
    else if(wff.substr(0, 2) === '<>')
      json.poss = _wffToJSON(wff.slice(2));
    else if(subwffs = wff.match(conjRegEx))
      json.conj = [_wffToJSON(subwffs[1]), _wffToJSON(subwffs[2])];
    else if(subwffs = wff.match(disjRegEx))
      json.disj = [_wffToJSON(subwffs[1]), _wffToJSON(subwffs[2])];
    else if(subwffs = wff.match(implRegEx))
      json.impl = [_wffToJSON(subwffs[1]), _wffToJSON(subwffs[2])];
    else if(subwffs = wff.match(equiRegEx))
      json.equi = [_wffToJSON(subwffs[1]), _wffToJSON(subwffs[2])];
    else
      throw new Error('Invalid formula!');

    return json;
  }

  /**
   * Preprocesses an MPL wff string, then converts it to its JSON representation.
   */
  function wffToJSON(wff) {
    wff = _removeWhitespace(wff);
    if(!parenCheckRegEx.test(wff)) wff = '(' + wff + ')';

    return _wffToJSON(wff);
  }

  /**
   * Converts the JSON representation of an MPL wff to its string representation.
   */
  function jsonToWff(json) {
    if(json.prop)
      return json.prop;
    else if(json.neg)
      return '~' + jsonToWff(json.neg);
    else if(json.nec)
      return '[]' + jsonToWff(json.nec);
    else if(json.poss)
      return '<>' + jsonToWff(json.poss);
    else if(json.conj && json.conj.length === 2)
      return '(' + jsonToWff(json.conj[0]) + ' & ' + jsonToWff(json.conj[1]) + ')';
    else if(json.disj && json.disj.length === 2)
      return '(' + jsonToWff(json.disj[0]) + ' | ' + jsonToWff(json.disj[1]) + ')';
    else if(json.impl && json.impl.length === 2)
      return '(' + jsonToWff(json.impl[0]) + ' -> ' + jsonToWff(json.impl[1]) + ')';
    else if(json.equi && json.equi.length === 2)
      return '(' + jsonToWff(json.equi[0]) + ' <-> ' + jsonToWff(json.equi[1]) + ')';
    else
      throw new Error('Invalid JSON for formula!');
  }

  /**
   * Converts an MPL wff string to a LaTeX expression.
   */
  function wffToLaTeX(wff) {
    return wff.replace(/~/g,    '\\lnot{}')
              .replace(/\[\]/g, '\\Box{}')
              .replace(/<>/g,   '\\Diamond{}')
              .replace(/&/g,    '\\land{}')
              .replace(/\|/g,   '\\lor{}')
              .replace(/<->/g,  '\\leftrightarrow{}')
              .replace(/->/g,   '\\rightarrow{}');
  }

  /**
   * Converts the JSON representation of an MPL wff to a LaTeX expression.
   */
  function jsonToLaTeX(json) {
    return wffToLaTeX(jsonToWff(json));
  }

  /**
   * Converts an (ASCII) MPL wff string to a Unicode string for displaying.
   */
  function wffToUnicode(wff) {
    wff = _removeWhitespace(wff);
    return wff.replace(/~/g,    '\u00ac')
              .replace(/\[\]/g, '\u25a1')
              .replace(/<>/g,   '\u22c4')
              .replace(/&/g,    ' \u2227 ')
              .replace(/\|/g,   ' \u2228 ')
              .replace(/<->/g,  ' \u2194 ')
              .replace(/->/g,   ' \u2192 ');
  }

  /**
   * Converts the JSON representation of an MPL wff to a Unicode string for displaying.
   */
  function jsonToUnicode(json) {
    return wffToUnicode(jsonToWff(json));
  }

  /**
   * Constructor for Kripke model.
   * @constructor
   */
  function Model(propvars, states, relation) {
    // array of names of propositional variables in use
    this.propvars = propvars;

    // array of states in model, where each state is represented by a truth assignment,
    // i.e., an array of booleans corresponding to propvars
    this.states = states;

    // accessibility relation represented as array of arrays,
    // one subarray for each state in model, which is a list of successor state indices
    this.relation = relation;

    // returns truth value for a given proposition at a given state in the model
    this.valuation = function(prop, state) {
      return this.states[state][this.propvars.indexOf(prop)];
    };
  }

  /**
   * Evaluate the truth of an MPL wff (in JSON representation) at a given state within a given model.
   */
  function truth(model, state, wff) {
    if(wff.prop)
      return model.valuation(wff.prop, state);
    else if(wff.neg)
      return !truth(model, state, wff.neg);
    else if(wff.conj)
      return wff.conj.every(function(subwff) { return truth(model, state, subwff); });
    else if(wff.disj)
      return wff.disj.some(function(subwff) { return truth(model, state, subwff); });
    else if(wff.impl)
      return (!truth(model, state, wff.impl[0]) || truth(model, state, wff.impl[1]));
    else if(wff.equi)
      return (truth(model, state, wff.equi[0]) === truth(model, state, wff.equi[1]));
    else if(wff.nec)
      return model.relation[state].every(function(succState) { return truth(model, succState, wff.nec) });
    else if(wff.poss)
      return model.relation[state].some(function(succState) { return truth(model, succState, wff.poss) });
    else
      throw new Error('Invalid formula!');
  }

  // export public methods
  return {
    wffToJSON: wffToJSON,
    jsonToWff: jsonToWff,
    wffToLaTeX: wffToLaTeX,
    jsonToLaTeX: jsonToLaTeX,
    wffToUnicode: wffToUnicode,
    jsonToUnicode: jsonToUnicode,
    Model: Model,
    truth: truth
  };

})();
<|endoftext|>


<commit_before>function id(value){return value+1;}
<commit_msg>練習問題２−３<commit_after>function id(value){return value+2;}
<|endoftext|>


<commit_before>/* ****** MODEL ******** */

var neighborhoodSpots = [
		{
			title: "Saggio",
			phone: "212-795-3080",
			location: {lat: 40.851473, lng: -73.939588},
			type: "Restaurant",
//			label: "Restaurant"
		},
    	{
    		title: "Mambi Steakhouse",
    		phone: "212-928-9796",
    		location: {lat: 40.84772, lng: -73.938251},
    		type: "Restaurant"
    	},
    	{
    		title: "Planet Fitness",
    		phone: "646-216-3150",
    		location: {lat: 40.847326, lng: -73.937638},
    		type: "Gym",
    //		label:"Gym"
    	},
    	{
    		title: "Le Cheile",
    		phone: "212-740-3111",
    		location: {lat: 40.851495, lng: -73.939988},
    		type: "Restaurant"
    	},
    	{
    		title: "Elite Cleaners",
    		phone: "212-927-5872",
    		location: {lat: 40.843097, lng: -73.939438},
    		type: "Dry Cleaners",
    //		label: "Dry Cleaners"
    	},
    	{
    		title: "Columbia Wine Co",
    		phone: "212-543-2633",
    		location: {lat: 40.842125, lng: -73.939272},
    		type: "Liquor Store",
    //		label: "Liquor Store"
    	}
	]

	//****** VIEW ******** //

var listView = function(data) {
	this.title = ko.observable(data.title);
	this.location = ko.observable(data.location);
	this.type = ko.observable(data.type);
}

// ****** VIEWMODEL ******** //

var ViewModel = function() {
	var self = this;

	this.places = ko.observableArray([]);

	neighborhoodSpots.forEach(function(locationItem) {
		self.places.push(new listView(locationItem));
	});

	this.selectedType = ko.observable();
	this.clearFilter = function() {
		this.selectedType(null)
	}
}

ko.applyBindings(new ViewModel());

// ******** MAP ******** //

var map;

// Create empty arry to push markers into.
var markers = [];

// Get that map going in the map div!
// Thanks to Google Maps API for the super helpful documentation, course, and instructions!
var initMap = function() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: {lat: 40.843436, lng: -73.934794},
		zoom: 14
	});

	// Close infowindow when any other portion of the map is clicked.
	google.maps.event.addListener(map, "click", function(event) {
		mapInfoWindow.close();
		marker.setIcon(defaultIcon);
	});

	var mapInfoWindow = new google.maps.InfoWindow();

	var defaultIcon = makeMarkerIcon('ff2d00');

	var highlightedIcon = makeMarkerIcon('631504');

	var clickedIcon = makeMarkerIcon('46e91f');

	// loop through neighborhoodSpots array to make markers.
	for (var i = 0; i < neighborhoodSpots.length; i++) {
		var title = neighborhoodSpots[i].title;
		var phone = neighborhoodSpots[i].phone;
		var position = neighborhoodSpots[i].location;

		var marker = new google.maps.Marker({
			map: map,
			position: position,
			title: title,
			phone: phone,
			// markers drop in when page loads.
			animation: google.maps.Animation.DROP,
			icon: defaultIcon,
			id: i
		});

/*	// Make marker bounce on click.
	marker.addListener("click", makeBounce); */

	// Push markers to markers[] array.
	markers.push(marker);

	//Open info window on click.
	marker.addListener("click", function() {
		fillInfoWindow(this, mapInfoWindow);
		// change clicked icon's color.
		this.setIcon(clickedIcon);
	});

	// Change marker color when mouse hovers over marker.
	marker.addListener("mouseover", function() {
		this.setIcon(highlightedIcon);
	});

	// Use default color when not hovering over marker.
	marker.addListener("mouseout", function() {
		// Make sure icon hasn't been clicked.
		if (this.setIcon(clickedIcon) != true {
		this.setIcon(defaultIcon);
		}
	});
//}

/*	function makeBounce() {
		var bounce = setInterval(function() {
			marker.setAnimation(google.maps.Animation.BOUNCE);
		}, 100);

		setTimeout(function() {
			clearInterval(bounce);
		}, 1000);
	} */

	function fillInfoWindow(marker, infowindow) {
		// Check if marker's window is already open.
		if (infowindow.marker != marker) {
			// Clear infowindow
			infowindow.setContent('');
			infowindow.marker = marker;
			// Open  infowinow
			infowindow.open(map, marker)

			// Close infowindow on click.
			infowindow.addListener('closeclick', function() {
				infowindow.marker(null);
				// Change icon color back to default.
				marker.setIcon(defaultIcon);
			});

			infowindow.setContent("
" + marker.title + "

" + marker.phone + "
")

			}
		}

		// This function takes in a color, and then creates a new marker
        // icon of that color. The icon will be 21px wide by 34px high, have an
        // origin of 0, 0 and be anchored at 10, 34. Again, thank you Google API for the help.
      function makeMarkerIcon(markerColor) {
        var markerImage = new google.maps.MarkerImage(
          "https://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|" + markerColor +
          "|40|_|%E2%80%A2",
          new google.maps.Size(21, 34),
          new google.maps.Point(0, 0),
          new google.maps.Point(10, 34),
          new google.maps.Size(21,34));
        return markerImage;
      }

};<commit_msg>add (<commit_after>/* ****** MODEL ******** */

var neighborhoodSpots = [
		{
			title: "Saggio",
			phone: "212-795-3080",
			location: {lat: 40.851473, lng: -73.939588},
			type: "Restaurant",
//			label: "Restaurant"
		},
    	{
    		title: "Mambi Steakhouse",
    		phone: "212-928-9796",
    		location: {lat: 40.84772, lng: -73.938251},
    		type: "Restaurant"
    	},
    	{
    		title: "Planet Fitness",
    		phone: "646-216-3150",
    		location: {lat: 40.847326, lng: -73.937638},
    		type: "Gym",
    //		label:"Gym"
    	},
    	{
    		title: "Le Cheile",
    		phone: "212-740-3111",
    		location: {lat: 40.851495, lng: -73.939988},
    		type: "Restaurant"
    	},
    	{
    		title: "Elite Cleaners",
    		phone: "212-927-5872",
    		location: {lat: 40.843097, lng: -73.939438},
    		type: "Dry Cleaners",
    //		label: "Dry Cleaners"
    	},
    	{
    		title: "Columbia Wine Co",
    		phone: "212-543-2633",
    		location: {lat: 40.842125, lng: -73.939272},
    		type: "Liquor Store",
    //		label: "Liquor Store"
    	}
	]

	//****** VIEW ******** //

var listView = function(data) {
	this.title = ko.observable(data.title);
	this.location = ko.observable(data.location);
	this.type = ko.observable(data.type);
}

// ****** VIEWMODEL ******** //

var ViewModel = function() {
	var self = this;

	this.places = ko.observableArray([]);

	neighborhoodSpots.forEach(function(locationItem) {
		self.places.push(new listView(locationItem));
	});

	this.selectedType = ko.observable();
	this.clearFilter = function() {
		this.selectedType(null)
	}
}

ko.applyBindings(new ViewModel());

// ******** MAP ******** //

var map;

// Create empty arry to push markers into.
var markers = [];

// Get that map going in the map div!
// Thanks to Google Maps API for the super helpful documentation, course, and instructions!
var initMap = function() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: {lat: 40.843436, lng: -73.934794},
		zoom: 14
	});

	// Close infowindow when any other portion of the map is clicked.
	google.maps.event.addListener(map, "click", function(event) {
		mapInfoWindow.close();
		marker.setIcon(defaultIcon);
	});

	var mapInfoWindow = new google.maps.InfoWindow();

	var defaultIcon = makeMarkerIcon('ff2d00');

	var highlightedIcon = makeMarkerIcon('631504');

	var clickedIcon = makeMarkerIcon('46e91f');

	// loop through neighborhoodSpots array to make markers.
	for (var i = 0; i < neighborhoodSpots.length; i++) {
		var title = neighborhoodSpots[i].title;
		var phone = neighborhoodSpots[i].phone;
		var position = neighborhoodSpots[i].location;

		var marker = new google.maps.Marker({
			map: map,
			position: position,
			title: title,
			phone: phone,
			// markers drop in when page loads.
			animation: google.maps.Animation.DROP,
			icon: defaultIcon,
			id: i
		});

/*	// Make marker bounce on click.
	marker.addListener("click", makeBounce); */

	// Push markers to markers[] array.
	markers.push(marker);

	//Open info window on click.
	marker.addListener("click", function() {
		fillInfoWindow(this, mapInfoWindow);
		// change clicked icon's color.
		this.setIcon(clickedIcon);
	});

	// Change marker color when mouse hovers over marker.
	marker.addListener("mouseover", function() {
		this.setIcon(highlightedIcon);
	});

	// Use default color when not hovering over marker.
	marker.addListener("mouseout", function() {
		// Make sure icon hasn't been clicked.
		if (this.setIcon(clickedIcon) != true) {
		this.setIcon(defaultIcon);
		}
	});
}

/*	function makeBounce() {
		var bounce = setInterval(function() {
			marker.setAnimation(google.maps.Animation.BOUNCE);
		}, 100);

		setTimeout(function() {
			clearInterval(bounce);
		}, 1000);
	} */

	function fillInfoWindow(marker, infowindow) {
		// Check if marker's window is already open.
		if (infowindow.marker != marker) {
			// Clear infowindow
			infowindow.setContent('');
			infowindow.marker = marker;
			// Open  infowinow
			infowindow.open(map, marker)

			// Close infowindow on click.
			infowindow.addListener('closeclick', function() {
				infowindow.marker(null);
				// Change icon color back to default.
				marker.setIcon(defaultIcon);
			});

			infowindow.setContent("
" + marker.title + "

" + marker.phone + "
")

			}
		}

		// This function takes in a color, and then creates a new marker
        // icon of that color. The icon will be 21px wide by 34px high, have an
        // origin of 0, 0 and be anchored at 10, 34. Again, thank you Google API for the help.
      function makeMarkerIcon(markerColor) {
        var markerImage = new google.maps.MarkerImage(
          "https://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|" + markerColor +
          "|40|_|%E2%80%A2",
          new google.maps.Size(21, 34),
          new google.maps.Point(0, 0),
          new google.maps.Point(10, 34),
          new google.maps.Size(21,34));
        return markerImage;
      }

};<|endoftext|>


<commit_before>'use strict'

var app = angular.module('app', [
    'app.trello'
]);

app.controller('mainController', function($scope, TrelloService){
    TrelloService.getBoards(false).then(function(boards){
        console.log(JSON.stringify(boards));
    });

    $scope.trelloInfo = {
        currentBoard: 'hue'
    };
});
<commit_msg>Showing first board name in the template<commit_after>'use strict'

var app = angular.module('app', [
    'app.trello'
]);

app.controller('mainController', function($scope, TrelloService){
    TrelloService.getBoards(false).then(function(boards){
        console.log(boards);
        console.log($scope);
        if(boards.length > 0){
            $scope.trelloInfo.currentBoard = boards[0].name;
            $scope.trelloInfo.currentBoardId = boards[0].id;
            $scope.$apply();
        }
    });

    $scope.trelloInfo = {};
});
<|endoftext|>


<commit_before>var stadiumInfo = [
  ["AT&T Park", "San Francisco, CA", "Giants", "37.778473", "-122.389595"],
  ["Angel Stadium Anaheim", "Anaheim, CA", "Los Angeles Angels", "33.799925", "-117.883194"],
  ["Busch Stadium", "St. Louis, MO", "St. Louis Cardinals", "38.622317", "-90.193891"],
  ["Chase Field", "Phoenix, AZ", "Arizona Diamondbacks", "33.445526", "-112.066721"],
  ["Citi Field", "New York, NY", "New York Mets", "40.756337", "-73.846043"],
  ["Citizens Bank Park", "Philadelphia, PA", "Philadelphia Phillies", "39.905547", "-75.166589"],
  ["Comerica Park", "Detroit, MI", "Detroit Tigers", "42.339227", "-83.049506"],
  ["Coors Field", "Denver, CO", "Colorado Rockies", "39.755891", "-104.994198"],
  ["Dodger Stadium", "Los Angeles", "Los Angeles Dodgers", "34.072724", "-118.240646"],
  ["Fenway Park", "Boston, MA", "Boston Red Sox", "42.346619", "-71.096961"],
  ["Globe Life Park", "Arlington, TX", "Texas Rangers", "32.751147", "-97.082454"],
  ["Great American Ball Park", "Cincinnati, OH", "Cincinnati Reds", "39.097935", "-84.508158"],
  ["Kauffman Stadium", "Kansas City, MO", "Kansas City Royals", "39.051098", "-94.481115"],
  ["Marlins Park", "Miami, FL", "Miami Marlins", "25.778655", "-80.220305"],
  ["Miller Park", "Milwaukee, WI", "Milwaukee Brewers", "43.027982", "-87.971165"],
  ["Minute Maid Park", "Houston, TX", "Houston Astros", "29.756965", "-95.354824"],
  ["Nationals Park", "Washington, DC", "Washington Nationals", "38.873010", "-77.007457"],
  ["O.co Coliseum", "Oakland, CA", "Oakland Athletics", "37.751605", "-122.200523"],
  ["Oriole Park at Camden Yards", "Baltimore, MD", "Baltimore Orioles", "39.283964", "-76.621618"],
  ["PNC Park", "Pittsburgh, PA", "Pittsburgh Pirates", "40.447307", "-80.006841"],
  ["Petco Park", "San Diego, CA", "San Diego Padres", "32.707710", "-117.157097"],
  ["Progressive Field", "Cleveland, OH", "Cleveland Indians", "41.496192", "-81.685238"],
  ["Rogers Centre", "Toronto, ON", "Toronto Blue Jays", "43.641111", "-79.389675"],
  ["Safeco Field", "Seattle, WA", "Seattle Mariners", "47.591358", "-122.332283"],
  ["Target Field", "Minneapolis, MN", "Minnesota Twins", "44.981713", "-93.277347"],
  ["Tropicana Field", "St. Petersburg, FL", "Tampa Bay Rays", "27.768160", "-82.653465"],
  ["Turner Field", "Atlanta, GA", "Atlanta Braves", "33.734805", "-84.389996"],
  ["U.S. Cellular Field", "Chicago, IL", "Chicago White Sox", "41.829908", "-87.633540"],
  ["Wrigley Field", "Chicago, IL", "Chicago Cubs", "41.947856", "-87.655887"],
  ["Yankee Stadium", "Bronx, NY", "New York Yankees", "40.829327", "-73.927735"]
];

var allStadiums = [];

function Stadium (name, city, team, long, lat){
  this.name = name;
  this.city = city;
  this.team = team;
  this.long = long;
  this.lat = lat;
}

(function makeStadiums (){
  for (var i = 0; i < stadiumInfo.length; i++){
    allStadiums.push(new Stadium(stadiumInfo[i][0], stadiumInfo[i][1], stadiumInfo[i][2], stadiumInfo[i][3], stadiumInfo[i][4]));
  }
})();

var inputHandler = {
  listContainer: document.getElementById('list'),

  createStadiumList: function(){
    var stadiumList = document.createElement("ul");
    for (var i = 0; i < allStadiums.length; i++){
      var stadiumEl = document.createElement("li");
      var checkbox = document.createElement('input');
      checkbox.type = "checkbox";
      checkbox.id = allStadiums[i].name;
      var label = document.createElement('label')
      label.htmlFor = "id";
      label.appendChild(document.createTextNode(allStadiums[i].team));
      stadiumList.appendChild(checkbox);
      stadiumList.appendChild(stadiumEl);
      stadiumEl.appendChild(checkbox);
      stadiumEl.appendChild(label);
      stadiumList.appendChild(stadiumEl);
    }
    inputHandler.listContainer.appendChild(stadiumList);
  }
}

inputHandler.createStadiumList();
<commit_msg>Fix the lost merge map<commit_after>var stadiumInfo = [
  ["AT&T Park", "San Francisco, CA", "Giants", "37.778473", "-122.389595"],
  ["Angel Stadium Anaheim", "Anaheim, CA", "Los Angeles Angels", "33.799925", "-117.883194"],
  ["Busch Stadium", "St. Louis, MO", "St. Louis Cardinals", "38.622317", "-90.193891"],
  ["Chase Field", "Phoenix, AZ", "Arizona Diamondbacks", "33.445526", "-112.066721"],
  ["Citi Field", "New York, NY", "New York Mets", "40.756337", "-73.846043"],
  ["Citizens Bank Park", "Philadelphia, PA", "Philadelphia Phillies", "39.905547", "-75.166589"],
  ["Comerica Park", "Detroit, MI", "Detroit Tigers", "42.339227", "-83.049506"],
  ["Coors Field", "Denver, CO", "Colorado Rockies", "39.755891", "-104.994198"],
  ["Dodger Stadium", "Los Angeles", "Los Angeles Dodgers", "34.072724", "-118.240646"],
  ["Fenway Park", "Boston, MA", "Boston Red Sox", "42.346619", "-71.096961"],
  ["Globe Life Park", "Arlington, TX", "Texas Rangers", "32.751147", "-97.082454"],
  ["Great American Ball Park", "Cincinnati, OH", "Cincinnati Reds", "39.097935", "-84.508158"],
  ["Kauffman Stadium", "Kansas City, MO", "Kansas City Royals", "39.051098", "-94.481115"],
  ["Marlins Park", "Miami, FL", "Miami Marlins", "25.778655", "-80.220305"],
  ["Miller Park", "Milwaukee, WI", "Milwaukee Brewers", "43.027982", "-87.971165"],
  ["Minute Maid Park", "Houston, TX", "Houston Astros", "29.756965", "-95.354824"],
  ["Nationals Park", "Washington, DC", "Washington Nationals", "38.873010", "-77.007457"],
  ["O.co Coliseum", "Oakland, CA", "Oakland Athletics", "37.751605", "-122.200523"],
  ["Oriole Park at Camden Yards", "Baltimore, MD", "Baltimore Orioles", "39.283964", "-76.621618"],
  ["PNC Park", "Pittsburgh, PA", "Pittsburgh Pirates", "40.447307", "-80.006841"],
  ["Petco Park", "San Diego, CA", "San Diego Padres", "32.707710", "-117.157097"],
  ["Progressive Field", "Cleveland, OH", "Cleveland Indians", "41.496192", "-81.685238"],
  ["Rogers Centre", "Toronto, ON", "Toronto Blue Jays", "43.641111", "-79.389675"],
  ["Safeco Field", "Seattle, WA", "Seattle Mariners", "47.591358", "-122.332283"],
  ["Target Field", "Minneapolis, MN", "Minnesota Twins", "44.981713", "-93.277347"],
  ["Tropicana Field", "St. Petersburg, FL", "Tampa Bay Rays", "27.768160", "-82.653465"],
  ["Turner Field", "Atlanta, GA", "Atlanta Braves", "33.734805", "-84.389996"],
  ["U.S. Cellular Field", "Chicago, IL", "Chicago White Sox", "41.829908", "-87.633540"],
  ["Wrigley Field", "Chicago, IL", "Chicago Cubs", "41.947856", "-87.655887"],
  ["Yankee Stadium", "Bronx, NY", "New York Yankees", "40.829327", "-73.927735"]
];

var allStadiums = [];

function Stadium (name, city, team, long, lat){
  this.name = name;
  this.city = city;
  this.team = team;
  this.long = long;
  this.lat = lat;
}

(function makeStadiums (){
  for (var i = 0; i < stadiumInfo.length; i++){
    allStadiums.push(new Stadium(stadiumInfo[i][0], stadiumInfo[i][1], stadiumInfo[i][2], stadiumInfo[i][3], stadiumInfo[i][4]));
  }
})();

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 38.0, lng: -95.35},
    zoom: 4
  });
}

var inputHandler = {
  listContainer: document.getElementById('list'),

  createStadiumList: function(){
    var stadiumList = document.createElement("ul");
    for (var i = 0; i < allStadiums.length; i++){
      var stadiumEl = document.createElement("li");
      var checkbox = document.createElement('input');
      checkbox.type = "checkbox";
      checkbox.id = allStadiums[i].name;
      var label = document.createElement('label')
      label.htmlFor = "id";
      label.appendChild(document.createTextNode(allStadiums[i].team));
      stadiumList.appendChild(checkbox);
      stadiumList.appendChild(stadiumEl);
      stadiumEl.appendChild(checkbox);
      stadiumEl.appendChild(label);
      stadiumList.appendChild(stadiumEl);
    }
    inputHandler.listContainer.appendChild(stadiumList);
  }
}

inputHandler.createStadiumList();
<|endoftext|>


<commit_before>/* global process */
import { defineSupportCode } from 'cucumber';
import Webdriver from 'selenium-webdriver';
import WebdriverProxy from 'selenium-webdriver/proxy';
import 'chromedriver';

import cp from 'child_process';
import net from 'net';
import http from 'http';
import https from 'https';
import httpProxy from 'http-proxy';
import express from 'express';
import chai from 'chai';
import chaiString from 'chai-string';

import devices from './devices.json';
import * as proxyConfig from './proxy';

chai.use(chaiString);
chai.should();

const appHostname = process.env.APP_HOST || 'localhost';
const appPort = process.env.APP_PORT || 9001;
const proxyPort = process.env.PROXY_HTTP_PORT || 9888;
const proxyTlsPort = process.env.PROXY_HTTPS_PORT || 9898;

const host = `${appHostname}:${appPort}`;
const baseUri = `http://${host}`;

cp.spawn('npm', [
    'start',
    '--',
    `--port=${appPort}`,
    `--proxyHost=${appHostname}`,
    `--proxyPort=${proxyPort}`,
    '--allowInsecureTls=true',
], {
    shell: true,
});

const interceptorServer = httpProxy.createProxyServer();

const createProxy = () => {

    const proxyApp = express();

    proxyApp.use((req, res, next) => {

        if (req.hostname === appHostname) {
            return interceptorServer.web(req, res, { target: baseUri });
        }

        return next();

    });

    const proxyHttpServer = http.createServer(proxyApp);
    const proxyHttpsServer = https.createServer(proxyConfig, proxyApp);

    proxyHttpServer.listen(proxyPort);
    proxyHttpsServer.listen(proxyTlsPort);

    proxyHttpServer.on('connect', (req, socket) => {

        const relaySocket = net.connect(proxyTlsPort, appHostname, () => {

            socket.write(
                'HTTP/1.1 200 Connection Established\r\n' +
                '\r\n',
            );

            relaySocket.pipe(socket);
            socket.pipe(relaySocket);

        });

    });

    proxyApp.quit = () => {
        proxyHttpServer.close();
        proxyHttpsServer.close();
    };

    return proxyApp;

};

const normalizeCapabilities = ({ deviceEmulation, ...etc }) => {

    const chromeOptions = {
        mobileEmulation: deviceEmulation,
        args: ['lang=en'],
    };

    return { browserName: 'chrome', chromeOptions, ...etc };

};

const createDriver = capabilities => new Webdriver.Builder()
    .withCapabilities({ [Webdriver.Capability.ACCEPT_SSL_CERTS]: true, ...normalizeCapabilities(capabilities) })
    .setProxy(WebdriverProxy.manual({ http: `${appHostname}:${proxyPort}`, https: `${appHostname}:${proxyPort}` }))
    .build();

//

class World {
    baseUri = baseUri;
    createProxy = createProxy;
    createDriver = createDriver;
    devices = devices;
}

defineSupportCode(({ setWorldConstructor }) => setWorldConstructor(World));
<commit_msg>add a small delay to initialization of cucumber tests<commit_after>/* global process */
import { defineSupportCode } from 'cucumber';
import Webdriver from 'selenium-webdriver';
import WebdriverProxy from 'selenium-webdriver/proxy';
import 'chromedriver';

import cp from 'child_process';
import net from 'net';
import http from 'http';
import https from 'https';
import httpProxy from 'http-proxy';
import express from 'express';
import chai from 'chai';
import chaiString from 'chai-string';

import devices from './devices.json';
import * as proxyConfig from './proxy';

chai.use(chaiString);
chai.should();

function sleep(time) {
    const stop = new Date().getTime();
    while (new Date().getTime() < stop + time);
}

const appHostname = process.env.APP_HOST || 'localhost';
const appPort = process.env.APP_PORT || 9001;
const proxyPort = process.env.PROXY_HTTP_PORT || 9888;
const proxyTlsPort = process.env.PROXY_HTTPS_PORT || 9898;

const host = `${appHostname}:${appPort}`;
const baseUri = `http://${host}`;

cp.spawn('npm', [
    'start',
    '--',
    `--port=${appPort}`,
    `--proxyHost=${appHostname}`,
    `--proxyPort=${proxyPort}`,
    '--allowInsecureTls=true',
], {
    shell: true,
});

// devnote: this is horrible, but we can't stall cucumber from
// running scenarios and we need a little time for our server
// to start
sleep(1000);

const interceptorServer = httpProxy.createProxyServer();

const createProxy = () => {

    const proxyApp = express();

    proxyApp.use((req, res, next) => {

        if (req.hostname === appHostname) {
            return interceptorServer.web(req, res, { target: baseUri });
        }

        return next();

    });

    const proxyHttpServer = http.createServer(proxyApp);
    const proxyHttpsServer = https.createServer(proxyConfig, proxyApp);

    proxyHttpServer.listen(proxyPort);
    proxyHttpsServer.listen(proxyTlsPort);

    proxyHttpServer.on('connect', (req, socket) => {

        const relaySocket = net.connect(proxyTlsPort, appHostname, () => {

            socket.write(
                'HTTP/1.1 200 Connection Established\r\n' +
                '\r\n',
            );

            relaySocket.pipe(socket);
            socket.pipe(relaySocket);

        });

    });

    proxyApp.quit = () => {
        proxyHttpServer.close();
        proxyHttpsServer.close();
    };

    return proxyApp;

};

const normalizeCapabilities = ({ deviceEmulation, ...etc }) => {

    const chromeOptions = {
        mobileEmulation: deviceEmulation,
        args: ['lang=en'],
    };

    return { browserName: 'chrome', chromeOptions, ...etc };

};

const createDriver = capabilities => new Webdriver.Builder()
    .withCapabilities({ [Webdriver.Capability.ACCEPT_SSL_CERTS]: true, ...normalizeCapabilities(capabilities) })
    .setProxy(WebdriverProxy.manual({ http: `${appHostname}:${proxyPort}`, https: `${appHostname}:${proxyPort}` }))
    .build();

//

class World {
    baseUri = baseUri;
    createProxy = createProxy;
    createDriver = createDriver;
    devices = devices;
}

defineSupportCode(({ setWorldConstructor }) => setWorldConstructor(World));
<|endoftext|>


<commit_before>'use strict';
var getcount = true;
var count;
var app = angular.module('myApp', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "HomeController"})
    // Pages
	.when("/surfer", {templateUrl: "partials/surfer.html", controller: "MovieController"})
    .when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
    .when("/faq", {templateUrl: "partials/faq.html", controller: "PageCtrl"})
    .when("/pricing", {templateUrl: "partials/pricing.html", controller: "PageCtrl"})
    .when("/services", {templateUrl: "partials/services.html", controller: "PageCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    // Blog
    .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
    .when("/blog/post", {templateUrl: "partials/blog_item.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);

app.controller('HomeController',function($scope, $http){

		$http.get("http://exp-expservices.rhcloud.com/live", {cache: false})
		  .then(function(response){ console.log("Services are up and running");},
		  function(response){$scope.hits = "Service Down"; console.log(response);});
		console.log(getcount);
		console.log(count);
		if(getcount == true){
			$http.get("http://services.eliteofindia.club/hits", {cache: false})
			  .then(function(response){ count = $scope.hits = response.data.hits; getcount=false;console.log(response);}, function(response){console.log(response);});
		}
		else{
			$scope.hits = count;
		}

});

  app.controller('MovieController',function($scope, $http, $interval){
    $scope.$watch('search', function() {
      fetch();
    });

	$scope.theTime = new Date().toLocaleTimeString();
	  $interval(function () {
		  $scope.theTime = new Date().toLocaleTimeString();
	  }, 1000);

    $scope.search = "Sherlock Holmes";
    function fetch(){

		$http.get("http://exp-expservices.rhcloud.com/live", {cache: false})
		.then(function(response){ console.log("Services are up and running");},
		function(response){console.log(response);});

      $http.get("http://services.eliteofindia.club/maininfo/" + $scope.search, {cache: false})
      .then(function(response){ $scope.details = response.data; });

      $http.get("http://services.eliteofindia.club/relatedinfo/" + $scope.search, {cache: false})
      .then(function(response){ $scope.related = response.data; });

	  /*$http.get("http://exp-expservices.rhcloud.com/hits", {cache: false})
	  .then(function(response){ $scope.hits = response.data.hits; console.log(response.data.hits);}, function(response){console.log(response);});*/

    }

    $scope.update = function(movie){
      $scope.search = movie.Title;
    };

    $scope.select = function(){
      this.setSelectionRange(0, this.value.length);
    }
  });
  app.directive("btnAutoCollapse",function() {
	  var dir = {
		restrict: 'A',
		scope: {},
		link: link
	  };
	  return dir;

	  function link(scope, element, attrs) {
		element.on('click', function(event) {
		  $(".navbar-collapse").collapse('hide');
		});
	  }
}

  );

<commit_msg>IE broke<commit_after>'use strict';
var getcount = true;
var count;
var app = angular.module('myApp', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "HomeController"})
    // Pages
	.when("/surfer", {templateUrl: "partials/surfer.html", controller: "MovieController"})
    .when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
    .when("/faq", {templateUrl: "partials/faq.html", controller: "PageCtrl"})
    .when("/pricing", {templateUrl: "partials/pricing.html", controller: "PageCtrl"})
    .when("/services", {templateUrl: "partials/services.html", controller: "PageCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    // Blog
    .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
    .when("/blog/post", {templateUrl: "partials/blog_item.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/", {templateUrl: "partials/home.html", controller: "HomeController"});
}]);

app.controller('HomeController',function($scope, $http){

		$http.get("http://exp-expservices.rhcloud.com/live", {cache: false})
		  .then(function(response){ console.log("Services are up and running");},
		  function(response){$scope.hits = "Service Down"; console.log(response);});
		console.log(getcount);
		console.log(count);
		if(getcount == true){
			$http.get("http://services.eliteofindia.club/hits", {cache: false})
			  .then(function(response){ count = $scope.hits = response.data.hits; getcount=false;console.log(response);}, function(response){console.log(response);});
		}
		else{
			$scope.hits = count;
		}

});

  app.controller('MovieController',function($scope, $http, $interval){
    $scope.$watch('search', function() {
      fetch();
    });

	$scope.theTime = new Date().toLocaleTimeString();
	  $interval(function () {
		  $scope.theTime = new Date().toLocaleTimeString();
	  }, 1000);

    $scope.search = "Sherlock Holmes";
    function fetch(){

		$http.get("http://exp-expservices.rhcloud.com/live", {cache: false})
		.then(function(response){ console.log("Services are up and running");},
		function(response){console.log(response);});

      $http.get("http://services.eliteofindia.club/maininfo/" + $scope.search, {cache: false})
      .then(function(response){ $scope.details = response.data; });

      $http.get("http://services.eliteofindia.club/relatedinfo/" + $scope.search, {cache: false})
      .then(function(response){ $scope.related = response.data; });

	  /*$http.get("http://exp-expservices.rhcloud.com/hits", {cache: false})
	  .then(function(response){ $scope.hits = response.data.hits; console.log(response.data.hits);}, function(response){console.log(response);});*/

    }

    $scope.update = function(movie){
      $scope.search = movie.Title;
    };

    $scope.select = function(){
      this.setSelectionRange(0, this.value.length);
    }
  });
  app.directive("btnAutoCollapse",directive);

  function directive() {
  var dir = {
    restrict: 'A',
    scope: {},
    link: link
  };
  return dir;

  function link(scope, element, attrs) {
    element.on('click', function(event) {
      $(".navbar-collapse").collapse('hide');
    });
  }
}

<|endoftext|>


<commit_before>/*User Story: I am presented with a random series of button presses.
User Story: Each time I input a series of button presses correctly, I see the same series of button presses but with an additional step.
User Story: I hear a sound that corresponds to each button both when the series of button presses plays, and when I personally press a button.
User Story: If I press the wrong button, I am notified that I have done so, and that series of button presses starts again to remind me of the pattern so I can try again.
User Story: I can see how many steps are in the current series of button presses.
User Story: If I want to restart, I can hit a button to do so, and the game will return to a single step.
User Story: I can play in strict mode where if I get a button press wrong, it notifies me that I have done so, and the game restarts at a new random series of button presses.
User Story: I can win the game by getting a series of 20 steps correct. I am notified of my victory, then the game starts over.*/
$(document).ready(function() {

  "use strict";

  var game = {
    //variables
    score: $("#score"),
    strict: false,
    powerOn: false,
    gameMoves: [],
    gameSequence: [],
    screenStart: "--",
    level: 1,
    moveCount: 0,
    sounds: {
      /*sound1: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
      sound2: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3"),
      sound3: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
      sound4: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"),
      winSound: new Audio("https://raw.githubusercontent.com/Missarachnid/fcc-simon/gh-pages/audio/you_win.mp3"),
      loseSound: new Audio("https://raw.githubusercontent.com/Missarachnid/fcc-simon/gh-pages/audio/game_over.mp3"),
      wrongMove: new Audio("https://raw.githubusercontent.com/Missarachnid/fcc-simon/gh-pages/audio/error.wav")*/
      sound1: $("#sound1")[0],
      sound2: $("#sound2")[0],
      sound3: $("#sound3")[0],
      sound4: $("#sound4")[0],
      winSound: $("#winSound")[0],
      loseSound: $("#loseSound")[0],
      wrongMove: $("#wrongMove")[0]
    },
    func: {
      arrayCreate: function() {
        var count = 20;
        while (count > 0) {
          var num = Math.floor((Math.random() * 4) + 1);
          game.gameMoves.push(num);
          count--;
        }
      },
      yellow: function() {
        game.sounds.sound1.play();
        $("#yellow").animate({
          opacity: "0.1"
        }, 100).animate({
          opacity: "1"
        }, 1000);
      },
      green: function() {
        game.sounds.sound2.play();
        $("#green").animate({
          opacity: "0.1"
        }, 100).animate({
          opacity: "1"
        }, 1000);
      },
      red: function() {
        game.sounds.sound3.play();
        $("#red").animate({
          opacity: "0.1"
        }, 100).animate({
          opacity: "1"
        }, 1000);
      },
      blue: function() {
        game.sounds.sound4.play();
        $("#blue").animate({
          opacity: "0.1"
        }, 100).animate({
          opacity: "1"
        }, 1000);
      },
      gameOver: function() {
        game.sounds.loseSound.play();
        game.score.html(game.screenStart);
        setTimeout(function(){
          game.func.reset();
          game.score.html(game.level);
          game.func.animator();
        }, 4000);
      },
      winGame: function() {
        game.sounds.winSound.play();
        game.score.html(game.screenStart);
         setTimeout(function(){
          game.func.reset();
          game.score.html(game.level);
          game.func.animator();
        }, 4000);
      },
      reset: function() {
        game.level = 1;
        game.score.html(game.screenStart);
        game.gameMoves = [];
        game.gameSequence = [];
        game.playerTurn = false;
        game.func.disableColors();
        game.func.arrayCreate();
      },
      checkMatch: function(item) {
        if (parseInt(item) === parseInt(game.gameSequence[game.moveCount])) {
          game.moveCount++;
          if (game.level === game.gameMoves.length && game.moveCount === game.gameMoves.length) {
            game.func.winGame();
          } else if (game.moveCount === game.gameSequence.length && game.level < game.gameMoves.length) {
            game.func.nextTurn();
          }
       } else if (parseInt(item) !== parseInt(game.gameSequence[game.moveCount])) {

          if (game.strict === true) {
            game.func.gameOver();
          } else {
            game.sounds.wrongMove.play();
           game.func.wrongTurn();
          }
        }
      },
      nextTurn: function() {
        game.level++;
        game.moveCount = 0;
        game.score.html(game.level);
        game.func.disableColors();
        setTimeout(game.func.animator, 1500);
      },
      wrongTurn: function() {
        game.moveCount = 0;
        game.func.disableColors();
        setTimeout(game.func.animator, 1500);
      },

      myDelay: function(n) {
        var temp = game.gameSequence[n];
        var speed;

        if (game.level < 5) {
          speed = 1300;
        } else if (game.level >= 5 && game.level < 9) {
          speed = 1100;
        } else if (game.level >= 9 && game.level < 13) {
          speed = 900;
        } else {
          speed = 750;
        }
        switch (temp) {
          case 1:
            window.setTimeout(game.func.yellow, speed * n);
            break;
          case 2:
            window.setTimeout(game.func.green, speed * n);
            break;
          case 3:
            window.setTimeout(game.func.red, speed * n);
            break;
          case 4:
            window.setTimeout(game.func.blue, speed * n);
            break;
        }
      },
      animator: function() {
        setTimeout(function() {
          game.gameSequence = game.gameMoves.slice(0, game.level);
          for (var i = 0; i <= game.gameSequence.length - 1; i++) {
            if(game.powerOn === true){
              game.func.myDelay(i);
            }else{
              return false;
            }
            if (i === game.gameSequence.length - 1) {
              game.playerTurn = true;
              game.func.enableColors();
            }else{
              game.func.disableColors();
            }
          }
        }, 1500);
      },
      disableToggle: function() {
        if ($(".choice").prop("disabled")) {
          $(".choice").prop("disabled", false);
        } else {
          $(".choice").prop("disabled", true);
        }
      },
      disableColors: function() {
        $("#green, #yellow, #red, #blue").prop("disabled", true);
      },
      enableColors: function() {
        $("#green, #yellow, #red, #blue").prop("disabled", false);
      }
    },
    buttons: {
      yellowClick: $("#yellow").click(function() {
        game.func.yellow();
        game.func.checkMatch(1);
      }),
      greenClick: $("#green").click(function() {
        game.func.green();
        game.func.checkMatch(2);
      }),
      redClick: $("#red").click(function() {
        game.func.red();
        game.func.checkMatch(3);
      }),
      blueClick: $("#blue").click(function() {
        game.func.blue();
        game.func.checkMatch(4);
      }),
      startClick: $("#start").click(function() {
        game.func.reset();
        game.score.html(game.level);
        game.func.animator();
      }),
      strictClick: $("#strict").click(function() {
        if (game.strict === false) {
          game.strict = true;
          $(".light").css("background-color", "yellow");
        } else {
          game.strict = false;
          $(".light").css("background-color", "black");
        }
      }),
      onOffClick: $("#onOff").click(function() {
        if (game.powerOn === false) {
          game.score.html(game.screenStart);
          game.func.disableToggle();
          game.powerOn = true;

        } else {
          game.powerOn = false;
          game.func.disableToggle();
          game.func.disableColors();
          $(".light").css("background-color", "black");
          game.func.reset();
          game.score.empty();
        }
      })
    }
  };

});
<commit_msg>fixed bug<commit_after>/*User Story: I am presented with a random series of button presses.
User Story: Each time I input a series of button presses correctly, I see the same series of button presses but with an additional step.
User Story: I hear a sound that corresponds to each button both when the series of button presses plays, and when I personally press a button.
User Story: If I press the wrong button, I am notified that I have done so, and that series of button presses starts again to remind me of the pattern so I can try again.
User Story: I can see how many steps are in the current series of button presses.
User Story: If I want to restart, I can hit a button to do so, and the game will return to a single step.
User Story: I can play in strict mode where if I get a button press wrong, it notifies me that I have done so, and the game restarts at a new random series of button presses.
User Story: I can win the game by getting a series of 20 steps correct. I am notified of my victory, then the game starts over.*/
$(document).ready(function() {

  "use strict";

  var game = {
    //variables
    score: $("#score"),
    strict: false,
    powerOn: false,
    gameMoves: [],
    gameSequence: [],
    screenStart: "--",
    level: 1,
    moveCount: 0,
    sounds: {
      /*sound1: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
      sound2: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3"),
      sound3: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
      sound4: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"),
      winSound: new Audio("https://raw.githubusercontent.com/Missarachnid/fcc-simon/gh-pages/audio/you_win.mp3"),
      loseSound: new Audio("https://raw.githubusercontent.com/Missarachnid/fcc-simon/gh-pages/audio/game_over.mp3"),
      wrongMove: new Audio("https://raw.githubusercontent.com/Missarachnid/fcc-simon/gh-pages/audio/error.wav")*/
      sound1: $("#sound1")[0],
      sound2: $("#sound2")[0],
      sound3: $("#sound3")[0],
      sound4: $("#sound4")[0],
      winSound: $("#winSound")[0],
      loseSound: $("#loseSound")[0],
      wrongMove: $("#wrongMove")[0]
    },
    func: {
      arrayCreate: function() {
        var count = 20;
        while (count > 0) {
          var num = Math.floor((Math.random() * 4) + 1);
          game.gameMoves.push(num);
          count--;
        }
      },
      yellow: function() {
        if(game.powerOn === true){
          game.sounds.sound1.play();
          $("#yellow").animate({
            opacity: "0.1"
          }, 100).animate({
            opacity: "1"
          }, 1000);
        }else{
          return false;
        }
      },
      green: function() {
        if(game.powerOn === true){
          game.sounds.sound2.play();
          $("#green").animate({
            opacity: "0.1"
          }, 100).animate({
            opacity: "1"
          }, 1000);
        }else{
          return false;
        }
      },
      red: function() {
        if(game.powerOn === true){
          game.sounds.sound3.play();
          $("#red").animate({
            opacity: "0.1"
          }, 100).animate({
            opacity: "1"
          }, 1000);
        }else{
         return false;
        }
      },
      blue: function() {
        if(game.powerOn === true){
          game.sounds.sound4.play();
          $("#blue").animate({
            opacity: "0.1"
          }, 100).animate({
            opacity: "1"
          }, 1000);
        }else{
          return false;
        }
      },
      gameOver: function() {
        game.sounds.loseSound.play();
        game.score.html(game.screenStart);
        setTimeout(function(){
          game.func.reset();
          game.score.html(game.level);
          game.func.animator();
        }, 4000);
      },
      winGame: function() {
        game.sounds.winSound.play();
        game.score.html(game.screenStart);
         setTimeout(function(){
          game.func.reset();
          game.score.html(game.level);
          game.func.animator();
        }, 4000);
      },
      reset: function() {
        game.level = 1;
        game.score.html(game.screenStart);
        game.gameMoves = [];
        game.gameSequence = [];
        game.playerTurn = false;
        game.func.disableColors();
        game.func.arrayCreate();
      },
      checkMatch: function(item) {
        if (parseInt(item) === parseInt(game.gameSequence[game.moveCount])) {
          game.moveCount++;
          if (game.level === game.gameMoves.length && game.moveCount === game.gameMoves.length) {
            game.func.winGame();
          } else if (game.moveCount === game.gameSequence.length && game.level < game.gameMoves.length) {
            game.func.nextTurn();
          }
       } else if (parseInt(item) !== parseInt(game.gameSequence[game.moveCount])) {

          if (game.strict === true) {
            game.func.gameOver();
          } else {
            game.sounds.wrongMove.play();
           game.func.wrongTurn();
          }
        }
      },
      nextTurn: function() {
        game.level++;
        game.moveCount = 0;
        game.score.html(game.level);
        game.func.disableColors();
        setTimeout(game.func.animator, 1500);
      },
      wrongTurn: function() {
        game.moveCount = 0;
        game.func.disableColors();
        setTimeout(game.func.animator, 1500);
      },
      myDelay: function(n) {
        var temp = game.gameSequence[n];
        var speed;
          if(game.powerOn !== false){
          if (game.level < 5) {
            speed = 1300;
          } else if (game.level >= 5 && game.level < 9) {
            speed = 1100;
          } else if (game.level >= 9 && game.level < 13) {
            speed = 900;
          } else {
            speed = 750;
          }

            switch (temp) {
              case 1:
                window.setTimeout(game.func.yellow, speed * n);
                break;
              case 2:
                window.setTimeout(game.func.green, speed * n);
                break;
              case 3:
                window.setTimeout(game.func.red, speed * n);
                break;
              case 4:
                window.setTimeout(game.func.blue, speed * n);
                break;
            }

        }else{
          return false;
        }
      },
      animator: function() {
        setTimeout(function() {
          game.gameSequence = game.gameMoves.slice(0, game.level);
            for (var i = 0; i <= game.gameSequence.length - 1; i++) {
              if(game.powerOn === true){
                game.func.myDelay(i);
              }else{
                return false;
              }
              if (i === game.gameSequence.length - 1) {
                game.playerTurn = true;
                game.func.enableColors();
              }else{
                game.func.disableColors();
              }
          }
        }, 1500);
      },
      disableToggle: function() {
        if ($(".choice").prop("disabled")) {
          $(".choice").prop("disabled", false);
        } else {
          $(".choice").prop("disabled", true);
        }
      },
      disableColors: function() {
        $("#green, #yellow, #red, #blue").prop("disabled", true);
      },
      enableColors: function() {
        $("#green, #yellow, #red, #blue").prop("disabled", false);
      }
    },
    buttons: {
      yellowClick: $("#yellow").click(function() {
        game.func.yellow();
        game.func.checkMatch(1);
      }),
      greenClick: $("#green").click(function() {
        game.func.green();
        game.func.checkMatch(2);
      }),
      redClick: $("#red").click(function() {
        game.func.red();
        game.func.checkMatch(3);
      }),
      blueClick: $("#blue").click(function() {
        game.func.blue();
        game.func.checkMatch(4);
      }),
      startClick: $("#start").click(function() {
        game.func.reset();
        game.score.html(game.level);
        game.func.animator();
      }),
      strictClick: $("#strict").click(function() {
        if (game.strict === false) {
          game.strict = true;
          $(".light").css("background-color", "yellow");
        } else {
          game.strict = false;
          $(".light").css("background-color", "black");
        }
      }),
      onOffClick: $("#onOff").click(function() {
        if (game.powerOn === false) {
          game.score.html(game.screenStart);
          game.func.disableToggle();
          game.powerOn = true;

        } else {
          game.powerOn = false;
          game.func.disableToggle();
          game.func.disableColors();
          $(".light").css("background-color", "black");
          game.func.reset();
          game.score.empty();
        }
      })
    }
  };
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    $("#query").val(""); //Empty the search field when the page loads
    $(".Reset").on("click", function() {
        $("#query").val("");
        $(".results").html("");
        $(".Reset").addClass("hide");
    })
    $("#search").on("click", function(e) {
        search();
        $("#random").css("display", "none");

    })
    $(".searchbox").on("keypress", function(e) {
        if (e.keyCode == 13) {
            $("#random").css("display", "none");
            search();
        }
    })
})

function search() {
    $.ajax({
        url: "https://en.wikipedia.org/w/api.php",
        jsonp: "callback",
        dataType: 'jsonp',
        data: {
            action: "query",
            list: "search",
            srsearch: $("#query").val(),
            srinfo: "suggestion",
            srlimit: "10",
            format: "json"
        },
        xhrFields: {
            withCredentials: true
        },
        success: display

    });
}
// the display function, displays cards
function display(data) {
    $(".results").html("");
    $(".Reset").removeClass("hide");
    $.each(data.query.search, function(index, result) {
        var html_content = ""; // Initialize
        html_content += '
';
        html_content += '
';
        html_content += '
';
        html_content += '
'
        html_content += '';
        html_content += result.title + "";
        html_content += "
" + result.snippet + "
";
        html_content += '
';
        html_content += '
';
        html_content += "';
        html_content += ' Link';
        html_content += '

';

        $(".results").append(html_content);

    });
}
<commit_msg> Remove  keypress search<commit_after>$(document).ready(function() {
    $("#query").val(""); //Empty the search field when the page loads
    $(".Reset").on("click", function() {
        $("#query").val("");
        $(".results").html("");
        $(".Reset").addClass("hide");
    })
    $("#search").on("click", function(e) {
        search();
        $("#random").css("display", "none");

    })
})

function search() {
    $.ajax({
        url: "https://en.wikipedia.org/w/api.php",
        jsonp: "callback",
        dataType: 'jsonp',
        data: {
            action: "query",
            list: "search",
            srsearch: $("#query").val(),
            srinfo: "suggestion",
            srlimit: "10",
            format: "json"
        },
        xhrFields: {
            withCredentials: true
        },
        success: display

    });
}
// the display function, displays cards
function display(data) {
    $(".results").html("");
    $(".Reset").removeClass("hide");
    $.each(data.query.search, function(index, result) {
        var html_content = ""; // Initialize
        html_content += '
';
        html_content += '
';
        html_content += '
';
        html_content += '
'
        html_content += '';
        html_content += result.title + "";
        html_content += "
" + result.snippet + "
";
        html_content += '
';
        html_content += '
';
        html_content += "';
        html_content += ' Link';
        html_content += '

';

        $(".results").append(html_content);

    });
}
<|endoftext|>


<commit_before>var app = angular.module('portfolio', ['ngRoute', 'ngAnimate']);

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
	$routeProvider
		.when('/', {
			templateUrl : 'pages/home.html',
		})
		.when('/ombuds', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.when('/women-in-engineering', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.when('/impact', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.when('/spectrum', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.when('/leafco', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.otherwise({
			templateUrl: 'pages/home.html',
		});

	$locationProvider.html5Mode(true);
}]);

// This is the key to view transition happiness! Mike Robinson
app.run(function ($rootScope, $timeout, $window) {
  $rootScope.$on('$routeChangeSuccess', function () {
    $timeout(function () {
      $window.scrollTo(0,0);
    }, 700);
  });
});<commit_msg>angular debug mode off<commit_after>var app = angular.module('portfolio', ['ngRoute', 'ngAnimate']);

app.config(['$routeProvider', '$locationProvider', '$compileProvider', function($routeProvider, $locationProvider, $compileProvider) {
	$compileProvider.debugInfoEnabled(false);

	$routeProvider
		.when('/', {
			templateUrl : 'pages/home.html',
		})
		.when('/ombuds', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.when('/women-in-engineering', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.when('/impact', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.when('/spectrum', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.when('/leafco', {
			templateUrl : 'pages/project.html',
			controller: 'ProjectCtrl',
			controllerAs: 'p'
		})
		.otherwise({
			templateUrl: 'pages/home.html',
		});

	$locationProvider.html5Mode(true);
}]);

// This is the key to view transition happiness! Mike Robinson
app.run(function ($rootScope, $timeout, $window) {
  $rootScope.$on('$routeChangeSuccess', function () {
    $timeout(function () {
      $window.scrollTo(0,0);
    }, 700);
  });
});<|endoftext|>