<commit_before>const Wire = require('./wire');
const config = require('./../config');
const net = require('net');

const clean = (data) => {
	if (Buffer.isBuffer(data)) {
		return data.toString();
	} else if (Array.isArray(data)) {
		return data.map(clean);
	} else if (typeof data === 'object') {
		return Object.keys(data).reduce((result, key) => Object.assign(result, { [key]: clean(data[key]) }), {});
	}

	return data;
};

const filterTorrent = (names) => names.filter((name) => config.filters.findIndex(element => name.toLowerCase().includes(element)) > -1);
const getType = (names) => {
	const weights = names.reduce(
		(result, name) =>
			Object.keys(config.formats)
				.filter((key) => {
					const ext = name ? name.split('.').pop() : '';

					return config.formats[key].find((format) => format === ext);
				})
				.reduce(
					(weight, type) => Object.assign(weight, { [type]: weight[type] ? weight[type] + 1 : 1 }),
					result,
				),
		{},
	);

	return Object.keys(weights).reduce(
		(result, type) => (result && weights[result] > weights[type] ? result : type),
		'',
	);
};
const getTags = (names, type) =>
	names.reduce((result, name) => {
		const tags = config.tags
			.filter((tag) => {
				if (tag.type !== type) {
					return false;
				} else if (tag.includes && name.indexOf(tag.includes) > -1) {
					return true;
				} else if (tag.match && name.match(tag.match)) {
					return true;
				}
				return false;
			})
			.map(({ tag }) => tag);

		return result.concat(tags);
	}, []);

const upsertTorrent = async (torrent, knex) => {
	try {
		const records = await knex('torrents').where({ infohash: torrent.infohash });

		if (config.debug) {
			console.log(`${torrent.infohash} - ${records.length > 0 ? 'Updated' : 'Inserted'}`);
		}
		if (records.length > 0) {
			await knex('torrents')
				.update(Object.assign(torrent, { updated: new Date() }))
				.where({ infohash: torrent.infohash });
		} else {
			await knex('torrents')
				.insert(Object.assign(torrent, { created: new Date(), updated: new Date() }))
				.where({ infohash: torrent.infohash });
		}
	} catch (error) {
		if (config.debug) {
			console.log(error);
		}
	}
};

const buildRecord = (names, knex, { files, infohash, length, name }) => {
	try {
		const type = getType(names);
		const tags = [...new Set(getTags(names, type))];

		const record = {
			files: JSON.stringify(files),
			infohash: infohash.toString('hex'),
			length: length || files.reduce((result, { length: fileLength }) => result + fileLength, 0),
			name,
			tags: tags.join(','),
			type,
		};

		upsertTorrent(record, knex);
	} catch (error) {
		console.log(error);
	}
};

const onMetadata = (metadata, infohash, knex) => {
	try {
		const { info = {} } = clean(metadata);
		const { files = [], length, name } = info;
		const names = files.map(({ path }) => (Array.isArray(path) ? path.join('/') : path)).concat(name);
		const invalid = filterTorrent(names);
if (!invalid.length>0){
	console.log(invalid)
buildRecord(invalid, knex, { files, infohash, length, name });
}
	} catch (error) {
		console.log(error);
	}
};

const getMetadata = (infohash, rinfo, knex) => {
	const socket = new net.Socket();

	socket.setTimeout(config.timeout || 5000);
	socket.connect(
		rinfo.port,
		rinfo.address,
		() => {
			const wire = new Wire(infohash);

			socket.pipe(wire).pipe(socket);

			wire.on('metadata', (metadata, hash) => {
				onMetadata(metadata, hash, knex);
				socket.destroy();
			});

			wire.on('fail', () => {
				socket.destroy();
			});

			wire.sendHandshake();
		},
	);

	socket.on('error', () => {
		socket.destroy();
	});

	socket.on('timeout', () => {
		socket.destroy();
	});
};

module.exports = getMetadata;
<commit_msg>Update parser.js<commit_after>const Wire = require('./wire');
const config = require('./../config');
const net = require('net');

const clean = (data) => {
	if (Buffer.isBuffer(data)) {
		return data.toString();
	} else if (Array.isArray(data)) {
		return data.map(clean);
	} else if (typeof data === 'object') {
		return Object.keys(data).reduce((result, key) => Object.assign(result, { [key]: clean(data[key]) }), {});
	}

	return data;
};

const filterTorrent = (names) => names.filter((name) => config.filters.findIndex(element => name.toLowerCase().includes(element)) > -1);
const getType = (names) => {
	const weights = names.reduce(
		(result, name) =>
			Object.keys(config.formats)
				.filter((key) => {
					const ext = name ? name.split('.').pop() : '';

					return config.formats[key].find((format) => format === ext);
				})
				.reduce(
					(weight, type) => Object.assign(weight, { [type]: weight[type] ? weight[type] + 1 : 1 }),
					result,
				),
		{},
	);

	return Object.keys(weights).reduce(
		(result, type) => (result && weights[result] > weights[type] ? result : type),
		'',
	);
};
const getTags = (names, type) =>
	names.reduce((result, name) => {
		const tags = config.tags
			.filter((tag) => {
				if (tag.type !== type) {
					return false;
				} else if (tag.includes && name.indexOf(tag.includes) > -1) {
					return true;
				} else if (tag.match && name.match(tag.match)) {
					return true;
				}
				return false;
			})
			.map(({ tag }) => tag);

		return result.concat(tags);
	}, []);

const upsertTorrent = async (torrent, knex) => {
	try {
		const records = await knex('torrents').where({ infohash: torrent.infohash });

		if (config.debug) {
			console.log(`${torrent.infohash} - ${records.length > 0 ? 'Updated' : 'Inserted'}`);
		}
		if (records.length > 0) {
			await knex('torrents')
				.update(Object.assign(torrent, { updated: new Date() }))
				.where({ infohash: torrent.infohash });
		} else {
			await knex('torrents')
				.insert(Object.assign(torrent, { created: new Date(), updated: new Date() }))
				.where({ infohash: torrent.infohash });
		}
	} catch (error) {
		if (config.debug) {
			console.log(error);
		}
	}
};

const buildRecord = (names, knex, { files, infohash, length, name }) => {
	try {
		const type = getType(names);
		const tags = [...new Set(getTags(names, type))];

		const record = {
			files: JSON.stringify(files),
			infohash: infohash.toString('hex'),
			length: length || files.reduce((result, { length: fileLength }) => result + fileLength, 0),
			name,
			tags: tags.join(','),
			type,
		};

		upsertTorrent(record, knex);
	} catch (error) {
		console.log(error);
	}
};

const onMetadata = (metadata, infohash, knex) => {
	try {
		const { info = {} } = clean(metadata);
		const { files = [], length, name } = info;
		const names = files.map(({ path }) => (Array.isArray(path) ? path.join('/') : path)).concat(name);
		const invalid = filterTorrent(names);
if (!invalid.length>0){
buildRecord(invalid, knex, { files, infohash, length, name });
}
	} catch (error) {
		console.log(error);
	}
};

const getMetadata = (infohash, rinfo, knex) => {
	const socket = new net.Socket();

	socket.setTimeout(config.timeout || 5000);
	socket.connect(
		rinfo.port,
		rinfo.address,
		() => {
			const wire = new Wire(infohash);

			socket.pipe(wire).pipe(socket);

			wire.on('metadata', (metadata, hash) => {
				onMetadata(metadata, hash, knex);
				socket.destroy();
			});

			wire.on('fail', () => {
				socket.destroy();
			});

			wire.sendHandshake();
		},
	);

	socket.on('error', () => {
		socket.destroy();
	});

	socket.on('timeout', () => {
		socket.destroy();
	});
};

module.exports = getMetadata;
<|endoftext|>


<commit_before>var History = {};

chrome.browserAction.setTitle({ 'title': '?'});
chrome.browserAction.setBadgeText({ 'text': '?'});
chrome.browserAction.setBadgeBackgroundColor({ 'color': "#666" });

function FormatDuration(d) {
  var minutes = Math.floor(d / (60 * 1000));
  var description;
  if (minutes < 60) {
    description = minutes + "m";
  } else {
    var hours = Math.floor(minutes / 60);
    var display_minutes = minutes % 60;
    if (display_minutes < 10) {
      display_minutes = "0" + display_minutes;
    }
    description = hours + ":" + display_minutes;
  }
  return description;
}

function HandleChange(tabId, changeInfo, tab) {
  if ("url" in changeInfo) {
    chrome.extension.getBackgroundPage().console.log("Tab changed: ", tabId, changeInfo);
    var now = new Date();
    if (!(tabId in History)) {
      History[tabId] = [];
    }
    History[tabId].unshift([now, changeInfo.url]);
    var title = "";
    for (var i=0; i < History[tabId].length; i++) {
      var t = History[tabId][i][0]
      if (i < History[tabId].length - 1) {
        if (History[tabId][i][0].toLocaleDateString() != History[tabId][i+1][0].toLocaleDateString()) {
          title += t.toLocaleDateString() + " ";
        }
        title += t.toLocaleTimeString() + " ";
        title += FormatDuration(History[tabId][i][0] - History[tabId][i+1][0]) + " ";
      } else {
        title += t.toLocaleDateString() + " " + t.toLocaleTimeString() + " ";
      }
      title += History[tabId][i][1] + "\n";
    }
    chrome.browserAction.setBadgeText({ 'tabId': tabId, 'text': '0m'});
    chrome.browserAction.setTitle({ 'tabId': tabId, 'title': title});
  }
}

function UpdateBadges() {
  var now = new Date();
  for (tabId in History) {
    var description = FormatDuration(now - History[tabId][0][0]);
    chrome.browserAction.setBadgeText({ 'tabId': parseInt(tabId), 'text': description});
  }
}

setInterval(UpdateBadges, 3000);

chrome.tabs.onUpdated.addListener(HandleChange);
<commit_msg>Put the duration on the correct line in the title.<commit_after>var History = {};

chrome.browserAction.setTitle({ 'title': '?'});
chrome.browserAction.setBadgeText({ 'text': '?'});
chrome.browserAction.setBadgeBackgroundColor({ 'color': "#666" });

function FormatDuration(d) {
  var minutes = Math.floor(d / (60 * 1000));
  var description;
  if (minutes < 60) {
    description = minutes + "m";
  } else {
    var hours = Math.floor(minutes / 60);
    var display_minutes = minutes % 60;
    if (display_minutes < 10) {
      display_minutes = "0" + display_minutes;
    }
    description = hours + ":" + display_minutes;
  }
  return description;
}

function HandleChange(tabId, changeInfo, tab) {
  if ("url" in changeInfo) {
    chrome.extension.getBackgroundPage().console.log("Tab changed: ", tabId, changeInfo);
    var now = new Date();
    if (!(tabId in History)) {
      History[tabId] = [];
    }
    History[tabId].unshift([now, changeInfo.url]);
    var title = "";
    for (var i=0; i < History[tabId].length; i++) {
      var t = History[tabId][i][0]
      var show_date = false;
      if (i == History[tabId].length - 1 ||
          (History[tabId][i][0].toLocaleDateString() != History[tabId][i+1][0].toLocaleDateString())) {
        title += t.toLocaleDateString() + " ";
      }
      title += t.toLocaleTimeString() + " ";
      if (i > 0) {
        title += FormatDuration(History[tabId][i-1][0] - History[tabId][i][0]) + " ";
      }
      title += History[tabId][i][1] + "\n";
    }
    chrome.browserAction.setBadgeText({ 'tabId': tabId, 'text': '0m'});
    chrome.browserAction.setTitle({ 'tabId': tabId, 'title': title});
  }
}

function UpdateBadges() {
  var now = new Date();
  for (tabId in History) {
    var description = FormatDuration(now - History[tabId][0][0]);
    chrome.browserAction.setBadgeText({ 'tabId': parseInt(tabId), 'text': description});
  }
}

setInterval(UpdateBadges, 3000);

chrome.tabs.onUpdated.addListener(HandleChange);
<|endoftext|>


<commit_before>#!/usr/bin/env node
/* jshint node:true, unused:true */
'use strict';

var fs = require('fs');

var log4js = require('log4js');
var rest   = require('restler-q');

var Api = require('../lib/schoolnet');

var log = log4js.getLogger('schoolnet');

function embedShell(config) {
    var doc = ['Schoolnet interactive shell\n',
    'Current config:\n' + JSON.stringify(config, null, 2) + '\n',
    'The following variables are in your context:',
    '  api - SchoolnetApi service instance',
    '  config',
    '  log - log4js logger (schoolnet)',
    '  Api - Schoolnet service constructor\n',
    '  modules:',
    '    log4js, rest (restler-q)\n',
    ];
    var context = {
        api: config && new Api(config),
        Api: Api,
        config: config,
        log: log,
        log4js: log4js,
        rest: rest,
        school: {
            institutionId: '006b8369-2fd8-48f0-aea3-e3b222e25b25',
            institutionName: 'Rosebud Elementary School',
            externalId: '519'
        }
    };
    require('embed-shell')({context: context, doc: doc, prompt: 'schoolnet> '});
}

function loadConfig(filename) {
    if (!filename) {
        return null;
    }
    if (filename[0] != '/') {
        filename = process.cwd() + '/' + filename;
    }
    if (!fs.existsSync(filename)) {
        return null;
    }
    return require(filename);
}

function main() {
    var prog = require('commander');
    prog.option('-c, --config [config]', 'json conf file');
    prog.parse(process.argv);
    embedShell(loadConfig(prog.config));
}

if (!module.parent) {
    main();
}
<commit_msg>Remove school reference from shell.<commit_after>#!/usr/bin/env node
/* jshint node:true, unused:true */
'use strict';

var fs = require('fs');

var log4js = require('log4js');
var rest   = require('restler-q');

var Api = require('../lib/schoolnet');

var log = log4js.getLogger('schoolnet');

function embedShell(config) {
    var doc = ['Schoolnet interactive shell\n',
    'Current config:\n' + JSON.stringify(config, null, 2) + '\n',
    'The following variables are in your context:',
    '  api - SchoolnetApi service instance',
    '  config',
    '  log - log4js logger (schoolnet)',
    '  Api - Schoolnet service constructor\n',
    '  modules:',
    '    log4js, rest (restler-q)\n',
    ];
    var context = {
        api: config && new Api(config),
        Api: Api,
        config: config,
        log: log,
        log4js: log4js,
        rest: rest,
    };
    require('embed-shell')({context: context, doc: doc, prompt: 'schoolnet> '});
}

function loadConfig(filename) {
    if (!filename) {
        return null;
    }
    if (filename[0] != '/') {
        filename = process.cwd() + '/' + filename;
    }
    if (!fs.existsSync(filename)) {
        return null;
    }
    return require(filename);
}

function main() {
    var prog = require('commander');
    prog.option('-c, --config [config]', 'json conf file');
    prog.parse(process.argv);
    embedShell(loadConfig(prog.config));
}

if (!module.parent) {
    main();
}
<|endoftext|>


<commit_before>angular./**
* app Module
*
* Description
*/
module('app', ['ui.bootstrap', 'chart.js'])
	.config(function($provide) {
		$provide.constant('getUserItems', 'getAllItems.php');
		$provide.constant('getItemByUPC', 'ItembyUPC.php');
		$provide.constant('getCurrentEvents', 'getHistoryInfo.php');
		$provide.constant('MessagesSet', [
			{
				message_id: 1,
				message_title: 'Amazon 15% off until end of today',
				message_text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tristique hendrerit ex, vitae aliquet lacus lacinia non. Nam quis tincidunt elit, eu efficitur tellus. Ut lacinia laoreet magna at vulputate. Cras aliquam eros at ligula hendrerit placerat. Sed at magna tempus dui dictum cursus ac et mauris.'
			},
			{
				message_id: 2,
				message_title: 'Sears 18% off until tomorrow',
				message_text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tristique hendrerit ex, vitae aliquet lacus lacinia non. Nam quis tincidunt elit, eu efficitur tellus. Ut lacinia laoreet magna at vulputate. Cras aliquam eros at ligula hendrerit placerat. Sed at magna tempus dui dictum cursus ac et mauris.'
			}
		]);
		$provide.constant('GraphData', {
			'data': [
						[25.74, 34.23, 35.67, 37.45, 39.34, 45.54, 45.55, 89.45]
					],
			'series': ['Cumulative expense'],
			'labels': ['September 12', 'September 13', 'September 14', 'September 15', 'September 16', 'September 17', 'September 18', 'September 19']
			}
		);
		$provide.value('Items', [
   // {
   //     item_name: 'Advil',
   //     pull_class: 'widget-icon red pull-left',
   //     widget_class: 'fa fa-plus-square',
   //     percent_left: '2.3',
   //     label_class: 'label label-danger',
   //     color_code: {
   //     	color: '#D95349'
   //     },
   //     status: 'Almost None',
   //     message: 'Buy by end of today'
   // },
   {
		item_name: 'Advil',
	   	pull_class: 'widget-icon red pull-left',
	   	widget_class: 'fa fa-plus-square',
	   	label_class: 'label label-danger',
	   	color_code: {
	   		color: '#D9534F'
	   	},
	   	status: 'Almost None',
	   	message: 'Buy by end of today'
   },
   {
       item_name: 'Milk',
       pull_class: 'widget-icon blue pull-left',
       widget_class: 'fa fa-shopping-cart',
       percent_left: '8.5',
       label_class: 'label label-warning',
       color_code: {
       	color: '#F0AD4E'
       },
       weight: null,
       status: 'Low',
       message: 'Buy within the next 3 days'
   },
   {
       item_name: 'Oranges',
       pull_class: 'widget-icon blue pull-left',
       widget_class: 'fa fa-shopping-cart',
       percent_left: '16.8',
       label_class: 'label label-warning',
       color_code: {
       	color: '#F0AD4E'
       },
       weight: null,
       status: 'Low',
       message: 'Buy within the next 2 days'
   },
   {
       item_name: 'Soft Drinks',
       pull_class: 'widget-icon green pull-left',
       widget_class: 'fa fa-glass',
       percent_left: '56.8',
       label_class: 'label label-info',
       color_code: {
       	color: '#428BCA'
       },
       weight: null,
       status: 'About Half',
       message: 'Buy in a week'
   },
   {
       item_name: 'Detergent',
       pull_class: 'widget-icon orange pull-left',
       widget_class: 'fa fa-tint',
       percent_left: '91.2',
       label_class: 'label label-success',
       color_code: {
       	color: '#5CB85C'
       },
       weight: null,
       status: 'Plenty',
       message: 'Buy in a couple of months'
   },
]);
	}).service('httpHandler', ['$http', function($http){
		this.request = function(UrlToQuery, Data) {
			return $http({
				method: "post",
				url: UrlToQuery,
				data: Data,
				headers: { 'Content-Type': 'application/json;charset=utf-8' }
			});
		}
	}]).factory('indexFactory', ['httpHandler', 'getUserItems', 'getItemByUPC', 'getCurrentEvents', function(httpHandler, getUserItems, getItemByUPC, getCurrentEvents){
		return {
			UserItems: function() {
				return httpHandler.request(getUserItems, {});
			},
			UPCDetails: function(upc) {
				return httpHandler.request(getItemByUPC, {
					upc: upc
				});
			},
			CurrentEvents: function() {
				return httpHandler.request(getCurrentEvents, {});
			}
		}
	}]).directive("rdWidget", function() {
        var d={
            transclude:!0,
            template:'

',
            restrict:"EA"
        };
        return d
    }).directive('enterSubmit', function () {
	    return {
	      restrict: 'A',
	      link: function (scope, elem, attrs) {

	        elem.bind('keydown', function(event) {
	          var code = event.keyCode || event.which;

	          if (code === 13) {
	            if (!event.shiftKey) {
	              event.preventDefault();
	              scope.$apply(attrs.enterSubmit);
	            }
	          }
	        });
	      }
	    }
	}).directive("rdLoading", function() {
        var d=
        {
            restrict:"AE",
            template:'

'
        };
        return d
    }).directive("rdWidgetBody", function() {
        var d=
        {
            requires:"^rdWidget",
            scope:{
                loading:"@?",
                classes:"@?"
            },
            transclude:!0,
            template:'
<rd-loading ng-show="loading"></rd-loading>

',
            restrict:"E"
        };
        return d
    }).directive("rdWidgetFooter",function (){
        var e=
        {
            requires:"^rdWidget",
            transclude:!0,
            template:'

',
            restrict:"E"
        };
        return e
    }).directive("rdWidgetHeader", function() {
        var e=
        {
            requires:"^rdWidget",
            scope:{
                title:"@",
                icon:"@"},
                transclude:!0,
                template:'
 {{title}}

',
                restrict:"E"
        };
        return e
    }).controller('controller', ['$scope', 'indexFactory', 'MessagesSet', '$interval', 'GraphData', 'Items', '$q', function($scope, indexFactory, MessagesSet, $interval, GraphData, Items, $q){
    	$scope.data = {};
    	$scope.data.messages = MessagesSet;
    	$scope.data.items = Items;

		$scope.toggle = true;

		$scope.data.dataset = GraphData.data;
		$scope.data.labels = GraphData.labels;
		$scope.data.series = GraphData.series;

		$scope.toggleSidebar = function() {
			/*
			Had to simplify a lot of routing
			 */
			$scope.toggle = !$scope.toggle;
		}

		//First get the initial commmit

		// indexFactory.UserItems().then(function(successResponse) {
		// 	console.log(successResponse);
		// 	for (var i = 0; i < successResponse.data.length; i++) {
		// 		var upc_id = successResponse.data[i].upc;
		// 		indexFactory.UPCDetails(upc_id).then(function(successResponse) {
		// 			console.log(successResponse);
		// 			for (var i = 0; i < successResponse.data.length; i++) {
		// 				$scope.data.items.push({
		// 					item_name: successResponse.data.item_name,
		// 					widget_class: 'fa fa-cutlery',
		// 					label_class: 'label label-success',
		// 					percent_left: 100,
		// 					status: 'Plenty',
		// 					message: 'Buy next month',
		// 					pull_class: 'widget-icon purple pull-left'
		// 				});
		// 			}
		// 		}, function(errorResponse) {
		// 			console.log(errorResponse);
		// 		});
		// 	}
		// }, function(errorResponse) {
		// 	console.log(errorResponse);
		// });

		function getRandomArbitrary(min, max) {
			return Math.random() * (max - min) + min;
		}

		function getRandom(min, max) {
		    return min + Math.floor(Math.random() * (max - min + 1));
		}

		function getEvents(waitEvent) {
			var deferred = $q.defer();
			console.log('waiting for ' + waitEvent);
			$interval(function() {
				indexFactory.CurrentEvents().then(function(successResponse) {
					if (successResponse.data.length == waitEvent) {
						deferred.resolve();
					}
				});
			}, 1000);
			return deferred.promise;
		}

		function getUserItems() {
			console.log('querried');
			indexFactory.UserItems().then(function(successResponse) {
				console.log(successResponse);
				//First we need to get all the unique items
				var objectArray = {};
				for (var i = 0; i < successResponse.data.length; i++) {
					objectArray[successResponse.data[i].upc] = '';
				}
				console.log(objectArray);
				var objectsToAdd = [];

				function inItems(upc_id) {
					for (var i = 0; i < $scope.data.items.length; i++) {
						if ($scope.data.items[i].upc == upc_id) {
							return true;
						}
					}
					return false;
				}

				angular.forEach(objectArray, function(value, key) {
					if (!inItems(key)) {
						this.push(key);
					}
				}, objectsToAdd);

				console.log(objectsToAdd);

				$scope.eventOnePromise = getEvents(1).then(function(successResponse){
					var $q.defer();
					console.log('got 1');
					for (var i = 0; i < objectsToAdd.length; i++) {
						console.log(objectsToAdd[i]);
						indexFactory.UPCDetails(objectsToAdd[i]).then(function(successResponse) {
							console.log(successResponse);
							$scope.data.items.push({
								upc: successResponse.data.upc,
								item_name: successResponse.data.item_name,
								percent_left: 100,
								color_code:{
									color: '#5CB85C'
								},
								widget_class: 'fa fa-leaf',
								pull_class: 'widget-icon purple pull-left',
								status: 'Plenty',
								label_class: 'label label-success'
							});
							$scope.data.dataset[0][$scope.data.dataset[0].length - 1] += 5;
							$scope.stopIntervalOne();
							deferred.resolve();
						}, function(errorResponse) {
							console.log(errorResponse);
						})
					}
					return deferred.promise;
				});
			}, function(errorResponse) {
				console.log(errorResponse);
			});
		}

		var promise = $interval(getUserItems, 3000);

		$scope.stopIntervalOne = function() {
			$interval.cancel(promise);
		}

		function waitForThree() {
			getEvents(3).then(function(successResponse) {
				//Weight changed
				console.log('got');
				$scope.eventOnePromise.then(function(successResponse) {
					for (var i = 0; i < $scope.data.items.length; i++) {
						if ($scope.data.items[i].upc == '060383049645') {
							$scope.data.items[i].color_code = {
								color: '#D9534F'
							};
							$scope.data.items[i].label_class = 'label label-danger';
							$scope.data.items[i].status = 'Almost None';
							$scope.data.items[i].percent_left = 4;
							break;
						}
					}
				});

			});
		}
		var promise = $interval(waitForThree, 3000);

		$scope.close = function(messageID) {
			for (var i = 0; i < $scope.data.messages.length; i++) {
				if ($scope.data.messages[i].message_id == messageID) {
					$scope.data.messages.splice(i, 1);
				}
			}
		}
	}]);<commit_msg>dsadasd<commit_after>angular./**
* app Module
*
* Description
*/
module('app', ['ui.bootstrap', 'chart.js'])
	.config(function($provide) {
		$provide.constant('getUserItems', 'getAllItems.php');
		$provide.constant('getItemByUPC', 'ItembyUPC.php');
		$provide.constant('getCurrentEvents', 'getHistoryInfo.php');
		$provide.constant('MessagesSet', [
			{
				message_id: 1,
				message_title: 'Amazon 15% off until end of today',
				message_text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tristique hendrerit ex, vitae aliquet lacus lacinia non. Nam quis tincidunt elit, eu efficitur tellus. Ut lacinia laoreet magna at vulputate. Cras aliquam eros at ligula hendrerit placerat. Sed at magna tempus dui dictum cursus ac et mauris.'
			},
			{
				message_id: 2,
				message_title: 'Sears 18% off until tomorrow',
				message_text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tristique hendrerit ex, vitae aliquet lacus lacinia non. Nam quis tincidunt elit, eu efficitur tellus. Ut lacinia laoreet magna at vulputate. Cras aliquam eros at ligula hendrerit placerat. Sed at magna tempus dui dictum cursus ac et mauris.'
			}
		]);
		$provide.constant('GraphData', {
			'data': [
						[25.74, 34.23, 35.67, 37.45, 39.34, 45.54, 45.55, 89.45]
					],
			'series': ['Cumulative expense'],
			'labels': ['September 12', 'September 13', 'September 14', 'September 15', 'September 16', 'September 17', 'September 18', 'September 19']
			}
		);
		$provide.value('Items', [
   // {
   //     item_name: 'Advil',
   //     pull_class: 'widget-icon red pull-left',
   //     widget_class: 'fa fa-plus-square',
   //     percent_left: '2.3',
   //     label_class: 'label label-danger',
   //     color_code: {
   //     	color: '#D95349'
   //     },
   //     status: 'Almost None',
   //     message: 'Buy by end of today'
   // },
   {
		item_name: 'Advil',
	   	pull_class: 'widget-icon red pull-left',
	   	widget_class: 'fa fa-plus-square',
	   	label_class: 'label label-danger',
	   	color_code: {
	   		color: '#D9534F'
	   	},
	   	status: 'Almost None',
	   	message: 'Buy by end of today'
   },
   {
       item_name: 'Milk',
       pull_class: 'widget-icon blue pull-left',
       widget_class: 'fa fa-shopping-cart',
       percent_left: '8.5',
       label_class: 'label label-warning',
       color_code: {
       	color: '#F0AD4E'
       },
       weight: null,
       status: 'Low',
       message: 'Buy within the next 3 days'
   },
   {
       item_name: 'Oranges',
       pull_class: 'widget-icon blue pull-left',
       widget_class: 'fa fa-shopping-cart',
       percent_left: '16.8',
       label_class: 'label label-warning',
       color_code: {
       	color: '#F0AD4E'
       },
       weight: null,
       status: 'Low',
       message: 'Buy within the next 2 days'
   },
   {
       item_name: 'Soft Drinks',
       pull_class: 'widget-icon green pull-left',
       widget_class: 'fa fa-glass',
       percent_left: '56.8',
       label_class: 'label label-info',
       color_code: {
       	color: '#428BCA'
       },
       weight: null,
       status: 'About Half',
       message: 'Buy in a week'
   },
   {
       item_name: 'Detergent',
       pull_class: 'widget-icon orange pull-left',
       widget_class: 'fa fa-tint',
       percent_left: '91.2',
       label_class: 'label label-success',
       color_code: {
       	color: '#5CB85C'
       },
       weight: null,
       status: 'Plenty',
       message: 'Buy in a couple of months'
   },
]);
	}).service('httpHandler', ['$http', function($http){
		this.request = function(UrlToQuery, Data) {
			return $http({
				method: "post",
				url: UrlToQuery,
				data: Data,
				headers: { 'Content-Type': 'application/json;charset=utf-8' }
			});
		}
	}]).factory('indexFactory', ['httpHandler', 'getUserItems', 'getItemByUPC', 'getCurrentEvents', function(httpHandler, getUserItems, getItemByUPC, getCurrentEvents){
		return {
			UserItems: function() {
				return httpHandler.request(getUserItems, {});
			},
			UPCDetails: function(upc) {
				return httpHandler.request(getItemByUPC, {
					upc: upc
				});
			},
			CurrentEvents: function() {
				return httpHandler.request(getCurrentEvents, {});
			}
		}
	}]).directive("rdWidget", function() {
        var d={
            transclude:!0,
            template:'

',
            restrict:"EA"
        };
        return d
    }).directive('enterSubmit', function () {
	    return {
	      restrict: 'A',
	      link: function (scope, elem, attrs) {

	        elem.bind('keydown', function(event) {
	          var code = event.keyCode || event.which;

	          if (code === 13) {
	            if (!event.shiftKey) {
	              event.preventDefault();
	              scope.$apply(attrs.enterSubmit);
	            }
	          }
	        });
	      }
	    }
	}).directive("rdLoading", function() {
        var d=
        {
            restrict:"AE",
            template:'

'
        };
        return d
    }).directive("rdWidgetBody", function() {
        var d=
        {
            requires:"^rdWidget",
            scope:{
                loading:"@?",
                classes:"@?"
            },
            transclude:!0,
            template:'
<rd-loading ng-show="loading"></rd-loading>

',
            restrict:"E"
        };
        return d
    }).directive("rdWidgetFooter",function (){
        var e=
        {
            requires:"^rdWidget",
            transclude:!0,
            template:'

',
            restrict:"E"
        };
        return e
    }).directive("rdWidgetHeader", function() {
        var e=
        {
            requires:"^rdWidget",
            scope:{
                title:"@",
                icon:"@"},
                transclude:!0,
                template:'
 {{title}}

',
                restrict:"E"
        };
        return e
    }).controller('controller', ['$scope', 'indexFactory', 'MessagesSet', '$interval', 'GraphData', 'Items', '$q', function($scope, indexFactory, MessagesSet, $interval, GraphData, Items, $q){
    	$scope.data = {};
    	$scope.data.messages = MessagesSet;
    	$scope.data.items = Items;

		$scope.toggle = true;

		$scope.data.dataset = GraphData.data;
		$scope.data.labels = GraphData.labels;
		$scope.data.series = GraphData.series;

		$scope.toggleSidebar = function() {
			/*
			Had to simplify a lot of routing
			 */
			$scope.toggle = !$scope.toggle;
		}

		//First get the initial commmit

		// indexFactory.UserItems().then(function(successResponse) {
		// 	console.log(successResponse);
		// 	for (var i = 0; i < successResponse.data.length; i++) {
		// 		var upc_id = successResponse.data[i].upc;
		// 		indexFactory.UPCDetails(upc_id).then(function(successResponse) {
		// 			console.log(successResponse);
		// 			for (var i = 0; i < successResponse.data.length; i++) {
		// 				$scope.data.items.push({
		// 					item_name: successResponse.data.item_name,
		// 					widget_class: 'fa fa-cutlery',
		// 					label_class: 'label label-success',
		// 					percent_left: 100,
		// 					status: 'Plenty',
		// 					message: 'Buy next month',
		// 					pull_class: 'widget-icon purple pull-left'
		// 				});
		// 			}
		// 		}, function(errorResponse) {
		// 			console.log(errorResponse);
		// 		});
		// 	}
		// }, function(errorResponse) {
		// 	console.log(errorResponse);
		// });

		function getRandomArbitrary(min, max) {
			return Math.random() * (max - min) + min;
		}

		function getRandom(min, max) {
		    return min + Math.floor(Math.random() * (max - min + 1));
		}

		function getEvents(waitEvent) {
			var deferred = $q.defer();
			console.log('waiting for ' + waitEvent);
			$interval(function() {
				indexFactory.CurrentEvents().then(function(successResponse) {
					if (successResponse.data.length == waitEvent) {
						deferred.resolve();
					}
				});
			}, 1000);
			return deferred.promise;
		}

		function getUserItems() {
			console.log('querried');
			indexFactory.UserItems().then(function(successResponse) {
				console.log(successResponse);
				//First we need to get all the unique items
				var objectArray = {};
				for (var i = 0; i < successResponse.data.length; i++) {
					objectArray[successResponse.data[i].upc] = '';
				}
				console.log(objectArray);
				var objectsToAdd = [];

				function inItems(upc_id) {
					for (var i = 0; i < $scope.data.items.length; i++) {
						if ($scope.data.items[i].upc == upc_id) {
							return true;
						}
					}
					return false;
				}

				angular.forEach(objectArray, function(value, key) {
					if (!inItems(key)) {
						this.push(key);
					}
				}, objectsToAdd);

				console.log(objectsToAdd);

				$scope.eventOnePromise = getEvents(1).then(function(successResponse){
					var deferred = $q.defer();
					console.log('got 1');
					for (var i = 0; i < objectsToAdd.length; i++) {
						console.log(objectsToAdd[i]);
						indexFactory.UPCDetails(objectsToAdd[i]).then(function(successResponse) {
							console.log(successResponse);
							$scope.data.items.push({
								upc: successResponse.data.upc,
								item_name: successResponse.data.item_name,
								percent_left: 100,
								color_code:{
									color: '#5CB85C'
								},
								widget_class: 'fa fa-leaf',
								pull_class: 'widget-icon purple pull-left',
								status: 'Plenty',
								label_class: 'label label-success'
							});
							$scope.data.dataset[0][$scope.data.dataset[0].length - 1] += 5;
							$scope.stopIntervalOne();
							deferred.resolve();
						}, function(errorResponse) {
							console.log(errorResponse);
						})
					}
					return deferred.promise;
				});
			}, function(errorResponse) {
				console.log(errorResponse);
			});
		}

		var promise = $interval(getUserItems, 3000);

		$scope.stopIntervalOne = function() {
			$interval.cancel(promise);
		}

		function waitForThree() {
			getEvents(3).then(function(successResponse) {
				//Weight changed
				console.log('got');
				$scope.eventOnePromise.then(function(successResponse) {
					for (var i = 0; i < $scope.data.items.length; i++) {
						if ($scope.data.items[i].upc == '060383049645') {
							$scope.data.items[i].color_code = {
								color: '#D9534F'
							};
							$scope.data.items[i].label_class = 'label label-danger';
							$scope.data.items[i].status = 'Almost None';
							$scope.data.items[i].percent_left = 4;
							break;
						}
					}
				});

			});
		}
		var promise = $interval(waitForThree, 3000);

		$scope.close = function(messageID) {
			for (var i = 0; i < $scope.data.messages.length; i++) {
				if ($scope.data.messages[i].message_id == messageID) {
					$scope.data.messages.splice(i, 1);
				}
			}
		}
	}]);<|endoftext|>


<commit_before>/*
 * MelonJS Game Engine
 * Copyright (C) 2011 - 2016, Olivier Biot, Jason Oster, Aaron McLeod
 * http://www.melonjs.org
 *
 */

/*
 * A level entity
 */

/**
 * @class
 * @extends me.Entity
 * @memberOf me
 * @constructor
 * @param {Number} x the x coordinates of the object
 * @param {Number} y the y coordinates of the object
 * @param {Object} settings See {@link me.Entity}
 * @param {String} [settings.duration] Fade duration (in ms)
 * @param {String|me.Color} [settings.color] Fade color
 * @param {String} [settings.to] TMX level to load
 * @param {String|me.Container} [settings.container] Target container. See {@link me.levelDirector.loadLevel}
 * @param {Function} [settings.onLoaded] Level loaded callback. See {@link me.levelDirector.loadLevel}
 * @param {Boolean} [settings.flatten] Flatten all objects into the target container. See {@link me.levelDirector.loadLevel}
 * @param {Boolean} [settings.setViewportBounds] Resize the viewport to match the level. See {@link me.levelDirector.loadLevel}
 * @example
 * me.game.world.addChild(new me.LevelEntity(
 *     x, y, {
 *         "duration" : 250,
 *         "color" : "#000",
 *         "to" : "mymap2"
 *     }
 * ));
 */
me.LevelEntity = me.Entity.extend(
/** @scope me.LevelEntity.prototype */
{
    /** @ignore */
    init : function (x, y, settings) {
        this._super(me.Entity, "init", [x, y, settings]);

        this.nextlevel = settings.to;

        this.fade = settings.fade;
        this.duration = settings.duration;
        this.fading = false;

        this.name = "levelEntity";

        // a temp variable
        this.gotolevel = settings.to;

        // Collect the defined level settings
        this.loadLevelSettings = {};
        [ "container", "onLoaded", "flatten", "setViewportBounds" ].forEach(function (v) {
            if (typeof(settings[v]) !== "undefined") {
                this.loadLevelSettings[v] = settings[v];
            }
        }.bind(this));

        // Lookup container name
        if (typeof(this.loadLevelSettings.container) === "string") {
            this.loadLevelSettings.container = me.game.world.getChildByName(this.loadLevelSettings.container)[0];
        }

        this.body.collisionType = me.collision.types.ACTION_OBJECT;
    },

    /**
     * @ignore
     */
    onFadeComplete : function () {
        me.levelDirector.loadLevel(this.gotolevel, this.loadLevelSettings);
        me.game.viewport.fadeOut(this.fade, this.duration);
    },

    /**
     * go to the specified level
     * @name goTo
     * @memberOf me.LevelEntity
     * @function
     * @param {String} [level=this.nextlevel] name of the level to load
     * @protected
     */
    goTo : function (level) {
        this.gotolevel = level || this.nextlevel;
        // load a level
        //console.log("going to : ", to);
        if (this.fade && this.duration) {
            if (!this.fading) {
                this.fading = true;
                me.game.viewport.fadeIn(this.fade, this.duration,
                        this.onFadeComplete.bind(this));
            }
        } else {
            me.levelDirector.loadLevel(this.gotolevel, this.loadLevelSettings);
        }
    },

    /** @ignore */
    onCollision : function () {
        if (this.name === "levelEntity") {
            this.goTo();
        }
        return false;
    }
});
<commit_msg>fix an issue where the level "host" container would not yet be added to the game world<commit_after>/*
 * MelonJS Game Engine
 * Copyright (C) 2011 - 2016, Olivier Biot, Jason Oster, Aaron McLeod
 * http://www.melonjs.org
 *
 */

/*
 * A level entity
 */

/**
 * @class
 * @extends me.Entity
 * @memberOf me
 * @constructor
 * @param {Number} x the x coordinates of the object
 * @param {Number} y the y coordinates of the object
 * @param {Object} settings See {@link me.Entity}
 * @param {String} [settings.duration] Fade duration (in ms)
 * @param {String|me.Color} [settings.color] Fade color
 * @param {String} [settings.to] TMX level to load
 * @param {String|me.Container} [settings.container] Target container. See {@link me.levelDirector.loadLevel}
 * @param {Function} [settings.onLoaded] Level loaded callback. See {@link me.levelDirector.loadLevel}
 * @param {Boolean} [settings.flatten] Flatten all objects into the target container. See {@link me.levelDirector.loadLevel}
 * @param {Boolean} [settings.setViewportBounds] Resize the viewport to match the level. See {@link me.levelDirector.loadLevel}
 * @example
 * me.game.world.addChild(new me.LevelEntity(
 *     x, y, {
 *         "duration" : 250,
 *         "color" : "#000",
 *         "to" : "mymap2"
 *     }
 * ));
 */
me.LevelEntity = me.Entity.extend(
/** @scope me.LevelEntity.prototype */
{
    /** @ignore */
    init : function (x, y, settings) {
        this._super(me.Entity, "init", [x, y, settings]);

        this.nextlevel = settings.to;

        this.fade = settings.fade;
        this.duration = settings.duration;
        this.fading = false;

        this.name = "levelEntity";

        // a temp variable
        this.gotolevel = settings.to;

        // Collect the defined level settings
        this.loadLevelSettings = {};
        [ "container", "onLoaded", "flatten", "setViewportBounds" ].forEach(function (v) {
            if (typeof(settings[v]) !== "undefined") {
                this.loadLevelSettings[v] = settings[v];
            }
        }.bind(this));

        this.body.collisionType = me.collision.types.ACTION_OBJECT;
    },

    /**
     * @ignore
     */
     getlevelSettings : function () {
         // Lookup for the container instance
         if (typeof(this.loadLevelSettings.container) === "string") {
             this.loadLevelSettings.container = me.game.world.getChildByName(this.loadLevelSettings.container)[0];
         }
         return this.loadLevelSettings;
     },

    /**
     * @ignore
     */
    onFadeComplete : function () {

        me.levelDirector.loadLevel(this.gotolevel, this.getlevelSettings());
        me.game.viewport.fadeOut(this.fade, this.duration);
    },

    /**
     * go to the specified level
     * @name goTo
     * @memberOf me.LevelEntity
     * @function
     * @param {String} [level=this.nextlevel] name of the level to load
     * @protected
     */
    goTo : function (level) {
        this.gotolevel = level || this.nextlevel;
        // load a level
        //console.log("going to : ", to);
        if (this.fade && this.duration) {
            if (!this.fading) {
                this.fading = true;
                me.game.viewport.fadeIn(this.fade, this.duration,
                        this.onFadeComplete.bind(this));
            }
        } else {
            me.levelDirector.loadLevel(this.gotolevel, this.getlevelSettings());
        }
    },

    /** @ignore */
    onCollision : function () {
        if (this.name === "levelEntity") {
            this.goTo.apply(this);
        }
        return false;
    }
});
<|endoftext|>


<commit_before>var Q = require("q");

var phantom=require('node-phantom');

function promisify(nodeAsyncFn, context, modifier) {
  return function() {
    var defer = Q.defer()
    , args = Array.prototype.slice.call(arguments);

    args.push(function(err, val) {
      if (err !== null) {
        return defer.reject(err);
      }

      if (modifier)
        modifier(val);

      return defer.resolve(val);
    });

    nodeAsyncFn.apply(context || {}, args);

    return defer.promise;
  };
};

phantom.createSync = promisify(phantom.create, phantom, function(ph) {
  ph.createPageSync = promisify(ph.createPage, ph, function(page) {
    page.openSync = promisify(page.open, page);
  });
});

phantom.createSync().then(function(ph) {
  return ph.createPageSync().then(function(page) {

    console.log("calling open");
    return page.openSync("http://google.com/")
      .then(function(status) {

          console.log("opened site? ", status);

          var title = page.evaluate(function() {
            return document.title;
          });

          console.log("title was " + title);
        })
      .then(function() {

          console.log("finished");
          ph.exit();
        },
        function(err) {

          console.log("failed: " + err);
        });
  });
});
<commit_msg>more promisification of phantom code<commit_after>var Q = require("q");

var phantom=require('node-phantom');

function promisify(nodeAsyncFn, context, modifier) {
  return function() {
    var defer = Q.defer()
    , args = Array.prototype.slice.call(arguments);

    args.push(function(err, val) {
      if (err !== null) {
        return defer.reject(err);
      }

      if (modifier)
        modifier(val);

      return defer.resolve(val);
    });

    nodeAsyncFn.apply(context || {}, args);

    return defer.promise;
  };
};

phantom.createSync = promisify(phantom.create, phantom, function(ph) {
  ph.createPageSync = promisify(ph.createPage, ph, function(page) {
    page.openSync = promisify(page.open, page);
    page.evaluateSync = promisify(page.evaluate, page);
  });
});

phantom.createSync().then(function(ph) {
  return ph.createPageSync().then(function(page) {

    console.log("calling open");
    return page.openSync("http://google.com/")
      .then(function(status) {

          console.log("opened site? ", status);

          return page.evaluateSync(function() {
            return document.title;
          });
        })
      .then(function(title) {
        console.log("title was " + title);
      })
      .then(function() {

          console.log("finished");
          ph.exit();
        },
        function(err) {

          console.log("failed: " + err);
        });
  });
});
<|endoftext|>


<commit_before>/**
* Wraps jQuery.prettyKalturaConfig with a single object based config and support for custom
* entry, uiconf and wid ( partner )
*
* @dependencies jQuery, jQuery.prettyKalturaConfig
*/
( function( kWidget ){ "use strict"

	kWidget.featureConfig = function( options ){
		// set update method in local function so we can call it any time we re-render the player
		var updateOptionsWithLocalSettings = function(){
			// Check for any kdoc-embed localStorage setting overrides
			var setKeys = ['wid', 'uiconf_id', 'entry_id'];
			$.each( setKeys, function(inx, key){
				if( options.embed && options.embed[ key] && localStorage[ 'kdoc-embed-' + key ] ){
					 options.embed[ key] = localStorage[ 'kdoc-embed-' + key ];
				}
			});

			// Do a special check for plugins with "ks" if we have a localStorage override.
			if( localStorage[ 'kdoc-embed-ks' ] && options.embed && options.embed.flashvars ){
				$.each(options.embed.flashvars, function( pKey, pObj){
					if( pKey == 'ks'){
						options.embed.flashvars[ pKey ] = localStorage[ 'kdoc-embed-ks' ];
					}
					if( $.isPlainObject( pObj ) ){
						$.each( pObj, function( pluginKey, pluginValue ){
							if( pluginKey == 'ks' ){
								options.embed.flashvars[ pKey ][pluginKey] = localStorage[ 'kdoc-embed-ks' ];
							}
						})
					}
				})
			}
		}
		updateOptionsWithLocalSettings();

		// By convention we document the first plugin ontop ( prettyKalturaConfig initial design
		// required passing a given pluginId.
		var firstPluginId = null;
		$.each( options.embed.flashvars, function( pName, na ) {
			firstPluginId = pName;
			return false;
		})
		// TODO read any url overrides from hash payload

		// display pretty config box:
		$('#' + options.featureConfigId ).prettyKalturaConfig(
				firstPluginId,
				options.embed.flashvars,
				function( fv ){
					// update flashvars:
					options.embed.flashvars = fv;
					// update embed settings
					updateOptionsWithLocalSettings();
					// update player embed:
					kWidget.embed( options.embed );
				},
				true // showSettingsTab
		)
		// do the actual kWidget embed
		kWidget.embed( options.embed );
	}

})( window.kWidget );<commit_msg>make sure kWidget is set in featureConfig<commit_after>/**
* Wraps jQuery.prettyKalturaConfig with a single object based config and support for custom
* entry, uiconf and wid ( partner )
*
* @dependencies jQuery, jQuery.prettyKalturaConfig
*/
( function( kWidget ){ "use strict"
	// make sure kWidget is set:
	if( !kWidget ){
		return ;
	}
	kWidget.featureConfig = function( options ){
		// set update method in local function so we can call it any time we re-render the player
		var updateOptionsWithLocalSettings = function(){
			// Check for any kdoc-embed localStorage setting overrides
			var setKeys = ['wid', 'uiconf_id', 'entry_id'];
			$.each( setKeys, function(inx, key){
				if( options.embed && options.embed[ key] && localStorage[ 'kdoc-embed-' + key ] ){
					 options.embed[ key] = localStorage[ 'kdoc-embed-' + key ];
				}
			});

			// Do a special check for plugins with "ks" if we have a localStorage override.
			if( localStorage[ 'kdoc-embed-ks' ] && options.embed && options.embed.flashvars ){
				$.each(options.embed.flashvars, function( pKey, pObj){
					if( pKey == 'ks'){
						options.embed.flashvars[ pKey ] = localStorage[ 'kdoc-embed-ks' ];
					}
					if( $.isPlainObject( pObj ) ){
						$.each( pObj, function( pluginKey, pluginValue ){
							if( pluginKey == 'ks' ){
								options.embed.flashvars[ pKey ][pluginKey] = localStorage[ 'kdoc-embed-ks' ];
							}
						})
					}
				})
			}
		}
		updateOptionsWithLocalSettings();

		// By convention we document the first plugin ontop ( prettyKalturaConfig initial design
		// required passing a given pluginId.
		var firstPluginId = null;
		$.each( options.embed.flashvars, function( pName, na ) {
			firstPluginId = pName;
			return false;
		})
		// TODO read any url overrides from hash payload

		// display pretty config box:
		$('#' + options.featureConfigId ).prettyKalturaConfig(
				firstPluginId,
				options.embed.flashvars,
				function( fv ){
					// update flashvars:
					options.embed.flashvars = fv;
					// update embed settings
					updateOptionsWithLocalSettings();
					// update player embed:
					kWidget.embed( options.embed );
				},
				true // showSettingsTab
		)
		// do the actual kWidget embed
		kWidget.embed( options.embed );
	}

})( window.kWidget );<|endoftext|>


<commit_before>import type from "@unction/type"
import isIterable from "@unction/isiterable"
import xstream from "xstream"

export default function mergeRight (left: IterableType): Function {
  if (!isIterable(left)) {
    throw new Error("left is not an iterable")
  }

  const leftType = type(left)

  return function mergeRightLeft (right: IterableType): IterableType {
    if (!isIterable(right)) {
      throw new Error("right was not an iterable")
    }

    if (left.constructor.name !== right.constructor.name) {
      throw new Error("left and right weren't the same type")
    }

    switch (leftType) {
      case "Array": {
        return [
          ...left,
          ...right,
        ]
      }
      case "Object": {
        return {
          ...left,
          ...right,
        }
      }
      case "Map": {
        return new Map()
      }
      case "WeakMap": {
        return new WeakMap()
      }
      case "Set": {
        return new Set()
      }
      case "WeakSet": {
        return new WeakSet()
      }
      case "Stream": {
        return new xstream.merge(left, right)
      }

      default: {
        throw new Error(`left wasn't an iterable type we know how to merge: ${leftType}`)
      }
    }
  }
}
<commit_msg>argh, totally wrong syntax<commit_after>import type from "@unction/type"
import isIterable from "@unction/isiterable"
import xstream from "xstream"

export default function mergeRight (left: IterableType): Function {
  if (!isIterable(left)) {
    throw new Error("left is not an iterable")
  }

  const leftType = type(left)

  return function mergeRightLeft (right: IterableType): IterableType {
    if (!isIterable(right)) {
      throw new Error("right was not an iterable")
    }

    if (left.constructor.name !== right.constructor.name) {
      throw new Error("left and right weren't the same type")
    }

    switch (leftType) {
      case "Array": {
        return [
          ...left,
          ...right,
        ]
      }
      case "Object": {
        return {
          ...left,
          ...right,
        }
      }
      case "Map": {
        return new Map()
      }
      case "WeakMap": {
        return new WeakMap()
      }
      case "Set": {
        return new Set()
      }
      case "WeakSet": {
        return new WeakSet()
      }
      case "Stream": {
        return xstream.merge(left, right)
      }

      default: {
        throw new Error(`left wasn't an iterable type we know how to merge: ${leftType}`)
      }
    }
  }
}
<|endoftext|>


<commit_before>module.exports = {
	parser: 'babel-eslint',   // https://github.com/babel/babel-eslint
	parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
    },
  },
	env: {                    // http://eslint.org/docs/user-guide/configuring.html#specifying-environments
		'browser': true,         // browser global variables
		'node': true             // Node.js global variables and Node.js-specific rules
	},
	rules: {
		/**
		 * Strict mode
		 */
		// babel inserts 'use strict'; for us
		'strict': ['error', 'never'],   // http://eslint.org/docs/rules/strict

		/**
		 * ES6
		 */
		'no-var': 'error',           // http://eslint.org/docs/rules/no-var
		'prefer-const': 'error',     // http://eslint.org/docs/rules/prefer-const
		'no-const-assign': 'error',  // http://eslint.org/docs/rules/no-const-assign

		/**
		 * Variables
		 */
		'no-shadow': 'error',                    // http://eslint.org/docs/rules/no-shadow
		'no-shadow-restricted-names': 'error',   // http://eslint.org/docs/rules/no-shadow-restricted-names
		'no-undef': 'error',                     // http://eslint.org/docs/rules/no-undef
		'no-unused-vars': ['warn', {            // http://eslint.org/docs/rules/no-unused-vars
			'vars': 'local',
			'args': 'none'
		}],
		//'no-use-before-define': 'error',         // http://eslint.org/docs/rules/no-use-before-define

		/**
		 * Possible errors
		 */
		'comma-dangle': 'off', // ['error', 'always-multiline'],   // http://eslint.org/docs/rules/comma-dangle
		'no-cond-assign': ['error', 'always'],                 // http://eslint.org/docs/rules/no-cond-assign
		'no-console': 'off',                                 // http://eslint.org/docs/rules/no-console
		'no-debugger': 'warn',                                // http://eslint.org/docs/rules/no-debugger
		'no-alert': 'off',                                   // http://eslint.org/docs/rules/no-alert
		'no-constant-condition': 'warn',                      // http://eslint.org/docs/rules/no-constant-condition
		'no-dupe-keys': 'error',                               // http://eslint.org/docs/rules/no-dupe-keys
		'no-duplicate-case': 'error',                          // http://eslint.org/docs/rules/no-duplicate-case
		'no-empty': 'off',                                   // http://eslint.org/docs/rules/no-empty
		'no-ex-assign': 'error',                               // http://eslint.org/docs/rules/no-ex-assign
		'no-extra-boolean-cast': 'off',                      // http://eslint.org/docs/rules/no-extra-boolean-cast
		'no-extra-semi': 'error',                              // http://eslint.org/docs/rules/no-extra-semi
		'no-func-assign': 'error',                             // http://eslint.org/docs/rules/no-func-assign
		'no-inner-declarations': 'error',                      // http://eslint.org/docs/rules/no-inner-declarations
		'no-invalid-regexp': 'error',                          // http://eslint.org/docs/rules/no-invalid-regexp
		'no-irregular-whitespace': 'error',                    // http://eslint.org/docs/rules/no-irregular-whitespace
		'no-obj-calls': 'error',                               // http://eslint.org/docs/rules/no-obj-calls
		'no-sparse-arrays': 'error',                           // http://eslint.org/docs/rules/no-sparse-arrays
		'no-unreachable': 'error',                             // http://eslint.org/docs/rules/no-unreachable
		'use-isnan': 'error',                                  // http://eslint.org/docs/rules/use-isnan
		'block-scoped-var': 'error',                           // http://eslint.org/docs/rules/block-scoped-var

		/**
		 * Best practices
		 */
		'consistent-return': 'error',        // http://eslint.org/docs/rules/consistent-return
		'curly': ['error', 'multi-line'],    // http://eslint.org/docs/rules/curly
		'default-case': 'error',             // http://eslint.org/docs/rules/default-case
		'dot-notation': ['error', {          // http://eslint.org/docs/rules/dot-notation
			'allowKeywords': true
		}],
		'eqeqeq': 'error',                   // http://eslint.org/docs/rules/eqeqeq
		'guard-for-in': 'error',             // http://eslint.org/docs/rules/guard-for-in
		'no-caller': 'error',                // http://eslint.org/docs/rules/no-caller
		'no-else-return': 'off',           // http://eslint.org/docs/rules/no-else-return
		'no-eq-null': 'error',               // http://eslint.org/docs/rules/no-eq-null
		'no-eval': 'error',                  // http://eslint.org/docs/rules/no-eval
		'no-extend-native': 'error',         // http://eslint.org/docs/rules/no-extend-native
		'no-extra-bind': 'error',            // http://eslint.org/docs/rules/no-extra-bind
		'no-fallthrough': 'error',           // http://eslint.org/docs/rules/no-fallthrough
		'no-floating-decimal': 'error',      // http://eslint.org/docs/rules/no-floating-decimal
		'no-implied-eval': 'error',          // http://eslint.org/docs/rules/no-implied-eval
		'no-lone-blocks': 'error',           // http://eslint.org/docs/rules/no-lone-blocks
		'no-loop-func': 'error',             // http://eslint.org/docs/rules/no-loop-func
		'no-multi-str': 'error',             // http://eslint.org/docs/rules/no-multi-str
		'no-native-reassign': 'error',       // http://eslint.org/docs/rules/no-native-reassign
		'no-new': 'error',                   // http://eslint.org/docs/rules/no-new
		'no-new-func': 'error',              // http://eslint.org/docs/rules/no-new-func
		'no-new-wrappers': 'error',          // http://eslint.org/docs/rules/no-new-wrappers
		'no-octal': 'error',                 // http://eslint.org/docs/rules/no-octal
		'no-octal-escape': 'error',          // http://eslint.org/docs/rules/no-octal-escape
		'no-param-reassign': 'off',        // http://eslint.org/docs/rules/no-param-reassign
		'no-proto': 'error',                 // http://eslint.org/docs/rules/no-proto
		'no-redeclare': 'error',             // http://eslint.org/docs/rules/no-redeclare
		'no-return-assign': 'error',         // http://eslint.org/docs/rules/no-return-assign
		'no-script-url': 'error',            // http://eslint.org/docs/rules/no-script-url
		'no-self-compare': 'error',          // http://eslint.org/docs/rules/no-self-compare
		'no-sequences': 'error',             // http://eslint.org/docs/rules/no-sequences
		'no-throw-literal': 'error',         // http://eslint.org/docs/rules/no-throw-literal
		'no-with': 'error',                  // http://eslint.org/docs/rules/no-with
		'radix': 'error',                    // http://eslint.org/docs/rules/radix
		'vars-on-top': 'error',              // http://eslint.org/docs/rules/vars-on-top
		'wrap-iife': ['error', 'any'],       // http://eslint.org/docs/rules/wrap-iife
		'yoda': 'error',                     // http://eslint.org/docs/rules/yoda

		/**
		 * Style
		 */
		'indent': ['error', 'tab', { 'SwitchCase': 1 }],   // http://eslint.org/docs/rules/indent
		'brace-style': [                           // http://eslint.org/docs/rules/brace-style
			'error',
			'1tbs', {
				'allowSingleLine': true
			}
		],
		/*'quotes': [
			'error', 'single', 'avoid-escape'         // http://eslint.org/docs/rules/quotes
		],*/
		'camelcase': ['error', {                     // http://eslint.org/docs/rules/camelcase
			'properties': 'never'
		}],
		'comma-spacing': ['error', {                 // http://eslint.org/docs/rules/comma-spacing
			'before': false,
			'after': true
		}],
		'comma-style': ['error', 'last'],            // http://eslint.org/docs/rules/comma-style
		'eol-last': 'error',                         // http://eslint.org/docs/rules/eol-last
		'func-names': 'warn',                       // http://eslint.org/docs/rules/func-names
		'key-spacing': ['error', {                   // http://eslint.org/docs/rules/key-spacing
			'beforeColon': false,
			'afterColon': true
		}],
		'new-cap': ['error', {                       // http://eslint.org/docs/rules/new-cap
			'newIsCap': true,
			'capIsNew': false
		}],
		'no-multiple-empty-lines': 'off',          // http://eslint.org/docs/rules/no-multiple-empty-lines
		//'no-nested-ternary': 'error',                // http://eslint.org/docs/rules/no-nested-ternary
		'no-new-object': 'error',                    // http://eslint.org/docs/rules/no-new-object
		'no-spaced-func': 'error',                   // http://eslint.org/docs/rules/no-spaced-func
		'no-trailing-spaces': 'off',               // http://eslint.org/docs/rules/no-trailing-spaces
		'no-extra-parens': ['error', 'functions'],   // http://eslint.org/docs/rules/no-extra-parens
		'no-underscore-dangle': 'off',             // http://eslint.org/docs/rules/no-underscore-dangle
		'one-var': ['error', 'never'],               // http://eslint.org/docs/rules/one-var
		'padded-blocks': 'off',                    // http://eslint.org/docs/rules/padded-blocks
		'semi': ['error', 'always'],                 // http://eslint.org/docs/rules/semi
		'semi-spacing': ['error', {                  // http://eslint.org/docs/rules/semi-spacing
			'before': false,
			'after': true
		}],
		'keyword-spacing': 'error', // http://eslint.org/docs/rules/keyword-spacing
		'space-before-blocks': 'error',                      // http://eslint.org/docs/rules/space-before-blocks
		'space-before-function-paren': ['error', 'never'],   // http://eslint.org/docs/rules/space-before-function-paren
		'space-infix-ops': 'error',                          // http://eslint.org/docs/rules/space-infix-ops
		'spaced-comment': 'off'
	}
};
<commit_msg>fix indent rule<commit_after>module.exports = {
	parser: 'babel-eslint',   // https://github.com/babel/babel-eslint
	parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
    },
  },
	env: {                    // http://eslint.org/docs/user-guide/configuring.html#specifying-environments
		'browser': true,         // browser global variables
		'node': true             // Node.js global variables and Node.js-specific rules
	},
	rules: {
		/**
		 * Strict mode
		 */
		// babel inserts 'use strict'; for us
		'strict': ['error', 'never'],   // http://eslint.org/docs/rules/strict

		/**
		 * ES6
		 */
		'no-var': 'error',           // http://eslint.org/docs/rules/no-var
		'prefer-const': 'error',     // http://eslint.org/docs/rules/prefer-const
		'no-const-assign': 'error',  // http://eslint.org/docs/rules/no-const-assign

		/**
		 * Variables
		 */
		'no-shadow': 'error',                    // http://eslint.org/docs/rules/no-shadow
		'no-shadow-restricted-names': 'error',   // http://eslint.org/docs/rules/no-shadow-restricted-names
		'no-undef': 'error',                     // http://eslint.org/docs/rules/no-undef
		'no-unused-vars': ['warn', {            // http://eslint.org/docs/rules/no-unused-vars
			'vars': 'local',
			'args': 'none'
		}],
		//'no-use-before-define': 'error',         // http://eslint.org/docs/rules/no-use-before-define

		/**
		 * Possible errors
		 */
		'comma-dangle': 'off', // ['error', 'always-multiline'],   // http://eslint.org/docs/rules/comma-dangle
		'no-cond-assign': ['error', 'always'],                 // http://eslint.org/docs/rules/no-cond-assign
		'no-console': 'off',                                 // http://eslint.org/docs/rules/no-console
		'no-debugger': 'warn',                                // http://eslint.org/docs/rules/no-debugger
		'no-alert': 'off',                                   // http://eslint.org/docs/rules/no-alert
		'no-constant-condition': 'warn',                      // http://eslint.org/docs/rules/no-constant-condition
		'no-dupe-keys': 'error',                               // http://eslint.org/docs/rules/no-dupe-keys
		'no-duplicate-case': 'error',                          // http://eslint.org/docs/rules/no-duplicate-case
		'no-empty': 'off',                                   // http://eslint.org/docs/rules/no-empty
		'no-ex-assign': 'error',                               // http://eslint.org/docs/rules/no-ex-assign
		'no-extra-boolean-cast': 'off',                      // http://eslint.org/docs/rules/no-extra-boolean-cast
		'no-extra-semi': 'error',                              // http://eslint.org/docs/rules/no-extra-semi
		'no-func-assign': 'error',                             // http://eslint.org/docs/rules/no-func-assign
		'no-inner-declarations': 'error',                      // http://eslint.org/docs/rules/no-inner-declarations
		'no-invalid-regexp': 'error',                          // http://eslint.org/docs/rules/no-invalid-regexp
		'no-irregular-whitespace': 'error',                    // http://eslint.org/docs/rules/no-irregular-whitespace
		'no-obj-calls': 'error',                               // http://eslint.org/docs/rules/no-obj-calls
		'no-sparse-arrays': 'error',                           // http://eslint.org/docs/rules/no-sparse-arrays
		'no-unreachable': 'error',                             // http://eslint.org/docs/rules/no-unreachable
		'use-isnan': 'error',                                  // http://eslint.org/docs/rules/use-isnan
		'block-scoped-var': 'error',                           // http://eslint.org/docs/rules/block-scoped-var

		/**
		 * Best practices
		 */
		'consistent-return': 'error',        // http://eslint.org/docs/rules/consistent-return
		'curly': ['error', 'multi-line'],    // http://eslint.org/docs/rules/curly
		'default-case': 'error',             // http://eslint.org/docs/rules/default-case
		'dot-notation': ['error', {          // http://eslint.org/docs/rules/dot-notation
			'allowKeywords': true
		}],
		'eqeqeq': 'error',                   // http://eslint.org/docs/rules/eqeqeq
		'guard-for-in': 'error',             // http://eslint.org/docs/rules/guard-for-in
		'no-caller': 'error',                // http://eslint.org/docs/rules/no-caller
		'no-else-return': 'off',           // http://eslint.org/docs/rules/no-else-return
		'no-eq-null': 'error',               // http://eslint.org/docs/rules/no-eq-null
		'no-eval': 'error',                  // http://eslint.org/docs/rules/no-eval
		'no-extend-native': 'error',         // http://eslint.org/docs/rules/no-extend-native
		'no-extra-bind': 'error',            // http://eslint.org/docs/rules/no-extra-bind
		'no-fallthrough': 'error',           // http://eslint.org/docs/rules/no-fallthrough
		'no-floating-decimal': 'error',      // http://eslint.org/docs/rules/no-floating-decimal
		'no-implied-eval': 'error',          // http://eslint.org/docs/rules/no-implied-eval
		'no-lone-blocks': 'error',           // http://eslint.org/docs/rules/no-lone-blocks
		'no-loop-func': 'error',             // http://eslint.org/docs/rules/no-loop-func
		'no-multi-str': 'error',             // http://eslint.org/docs/rules/no-multi-str
		'no-native-reassign': 'error',       // http://eslint.org/docs/rules/no-native-reassign
		'no-new': 'error',                   // http://eslint.org/docs/rules/no-new
		'no-new-func': 'error',              // http://eslint.org/docs/rules/no-new-func
		'no-new-wrappers': 'error',          // http://eslint.org/docs/rules/no-new-wrappers
		'no-octal': 'error',                 // http://eslint.org/docs/rules/no-octal
		'no-octal-escape': 'error',          // http://eslint.org/docs/rules/no-octal-escape
		'no-param-reassign': 'off',        // http://eslint.org/docs/rules/no-param-reassign
		'no-proto': 'error',                 // http://eslint.org/docs/rules/no-proto
		'no-redeclare': 'error',             // http://eslint.org/docs/rules/no-redeclare
		'no-return-assign': 'error',         // http://eslint.org/docs/rules/no-return-assign
		'no-script-url': 'error',            // http://eslint.org/docs/rules/no-script-url
		'no-self-compare': 'error',          // http://eslint.org/docs/rules/no-self-compare
		'no-sequences': 'error',             // http://eslint.org/docs/rules/no-sequences
		'no-throw-literal': 'error',         // http://eslint.org/docs/rules/no-throw-literal
		'no-with': 'error',                  // http://eslint.org/docs/rules/no-with
		'radix': 'error',                    // http://eslint.org/docs/rules/radix
		'vars-on-top': 'error',              // http://eslint.org/docs/rules/vars-on-top
		'wrap-iife': ['error', 'any'],       // http://eslint.org/docs/rules/wrap-iife
		'yoda': 'error',                     // http://eslint.org/docs/rules/yoda

		/**
		 * Style
		 */
		// http://eslint.org/docs/rules/indent
		indent: ['error', 'tab', {
			SwitchCase: 1,
			FunctionDeclaration: {
        parameters: 2,
        body: 1
      },
		}],
		'brace-style': [                           // http://eslint.org/docs/rules/brace-style
			'error',
			'1tbs', {
				'allowSingleLine': true
			}
		],
		/*'quotes': [
			'error', 'single', 'avoid-escape'         // http://eslint.org/docs/rules/quotes
		],*/
		'camelcase': ['error', {                     // http://eslint.org/docs/rules/camelcase
			'properties': 'never'
		}],
		'comma-spacing': ['error', {                 // http://eslint.org/docs/rules/comma-spacing
			'before': false,
			'after': true
		}],
		'comma-style': ['error', 'last'],            // http://eslint.org/docs/rules/comma-style
		'eol-last': 'error',                         // http://eslint.org/docs/rules/eol-last
		'func-names': 'warn',                       // http://eslint.org/docs/rules/func-names
		'key-spacing': ['error', {                   // http://eslint.org/docs/rules/key-spacing
			'beforeColon': false,
			'afterColon': true
		}],
		'new-cap': ['error', {                       // http://eslint.org/docs/rules/new-cap
			'newIsCap': true,
			'capIsNew': false
		}],
		'no-multiple-empty-lines': 'off',          // http://eslint.org/docs/rules/no-multiple-empty-lines
		//'no-nested-ternary': 'error',                // http://eslint.org/docs/rules/no-nested-ternary
		'no-new-object': 'error',                    // http://eslint.org/docs/rules/no-new-object
		'no-spaced-func': 'error',                   // http://eslint.org/docs/rules/no-spaced-func
		'no-trailing-spaces': 'off',               // http://eslint.org/docs/rules/no-trailing-spaces
		'no-extra-parens': ['error', 'functions'],   // http://eslint.org/docs/rules/no-extra-parens
		'no-underscore-dangle': 'off',             // http://eslint.org/docs/rules/no-underscore-dangle
		'one-var': ['error', 'never'],               // http://eslint.org/docs/rules/one-var
		'padded-blocks': 'off',                    // http://eslint.org/docs/rules/padded-blocks
		'semi': ['error', 'always'],                 // http://eslint.org/docs/rules/semi
		'semi-spacing': ['error', {                  // http://eslint.org/docs/rules/semi-spacing
			'before': false,
			'after': true
		}],
		'keyword-spacing': 'error', // http://eslint.org/docs/rules/keyword-spacing
		'space-before-blocks': 'error',                      // http://eslint.org/docs/rules/space-before-blocks
		'space-before-function-paren': ['error', 'never'],   // http://eslint.org/docs/rules/space-before-function-paren
		'space-infix-ops': 'error',                          // http://eslint.org/docs/rules/space-infix-ops
		'spaced-comment': 'off'
	}
};
<|endoftext|>


<commit_before><commit_msg>Updating Articles<commit_after><|endoftext|>


<commit_before>if (!Vector2) {
  /*
    Vector2 is a more advanced, more specialized PVector.
  */
  var Vector2 = function(x, y) {
    this.x = x || 0;
    this.y = y || 0;
  };
  /*
    Returns the sum of two vectors
  */
  Vector2.add = function(toAdd1, toAdd2) {
    return new Vector2(
      toAdd1.x + toAdd2.x,
      toAdd1.y + toAdd2.y
    );
  };
  /*
    Returns the difference of two vectors
  */
  Vector2.sub = function(subtractFrom, toSubtract) {
    return new Vector2(
      subtractFrom.x - toSubtract.x,
      subtractFrom.y - toSubtract.y
    );
  };
  /*
    Returns the product of a vector and a scalar
  */
  Vector2.mult = function(toMultiply, scaleFactor) {
    return new Vector2(
      toMultiply.x * scaleFactor,
      toMultiply.y * scaleFactor
    );
  };
  /*
    Returns the quotient of a vector and a scalar
  */
  Vector2.div = function(toDivide, inverseFactor) {
    return new Vector2(
      toDivide.x / inverseFactor,
      toDivide.y / inverseFactor
    );
  };
  /*
    Returns the magnitude or length of a vector
  */
  Vector2.mag = function(toMeasure) {
    return Math.sqrt(toMeasure.x * toMeasure.x + toMeasure.y * toMeasure.y);
  };
  /*
    Returns the square of the magnitude of a vector
    This is much faster than .mag and works in some situations
  */
  Vector2.magSq = function(toMeasure) {
    return toMeasure.x * toMeasure.x + toMeasure.y * toMeasure.y;
  };
  /*
    Returns the unit equivalent of a vector
  */
  Vector2.normalize = function(toNormalize) {
    return Vector2.div(toNormalize, toNormalize.mag());
  };
  /*
    Returns the rotation of a vector
  */
  Vector2.rotate = function(toRotate, rotateBy) {
    var cosAngle = Math.cos(rotateBy);
    var sinAngle = Math.sin(rotateBy);
    return new Vector2(
      toRotate.x * cosAngle - y * sinAngle,
      toRotate.x * sinAngle + y * cosAngle
    );
  };
  /*
    Returns the midpoint of two vectors
  */
  Vector2.mid = function(lineEnd1, lineEnd2) {
    return new Vector2(
      lineEnd1.x / 2 + lineEnd2.x / 2,
      lineEnd1.y / 2 + lineEnd2.y / 2
    );
  };
  /*
    Returns the distance between two vectors
  */
  Vector2.dist = function(lineEnd1, lineEnd2) {
    return Vector2.sub(lineEnd1, lineEnd2).mag();
  };
  /*
    Returns the linear interpolation of two vectors
  */
  Vector2.lerp = function(lerpFrom, lerpTo, lerpStage) {
    return new Vector2(
      lerpFrom.x + (lerpTo.x - lerpFrom.x) * lerpStage,
      lerpFrom.y + (lerpTo.y - lerpFrom.y) * lerpStage
    );
  };
  /*
    Returns the dot product of two vectors
  */
  Vector2.dot = function(toDot1, toDot2) {
    return toDot1.x * toDot2.x + toDot1.y * toDot2.y;
  };
  /*
    Returns a vector converted to an array
  */
  Vector2.array = function(toConvert) {
    return [toConvert.x, toConvert.y];
  };
  /*
    Returns the reflection of one vector over the line represented by two other vectors
  */
  Vector2.reflect = function(toReflect, linePoint1, linePoint2) {
    return Vector2.sub(toReflect,
      Vector2.mult(
        Vector2.sub(toReflect, new Vector2(
          (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), toReflect)) /
          (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)), Equation.M(linePoint1, linePoint2) *
          (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), toReflect)) /
          (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)) + Equation.B(linePoint1, linePoint2)
        )),
        2)
    );
  };

  /*
    Adds a vector to this vector
  */
  Vector2.prototype.add = function(toAdd) {
    this.x += toAdd.x;
    this.y += toAdd.y;
  };
  /*
    Subtracts a vector from this vector
  */
  Vector2.prototype.sub = function(toSubtract) {
    this.x -= toSubtract.x;
    this.y -= toSubtract.y;
  };
  /*
    Scales this vector
  */
  Vector2.prototype.mult = function(scaleFactor) {
    this.x *= scaleFactor;
    this.y *= scaleFactor;
  };
  /*
    Inversely scales this vector
  */
  Vector2.prototype.div = function(inverseFactor) {
    this.x /= inverseFactor;
    this.y /= inverseFactor;
  };
  /*
    Returns the magnitude of this vector
  */
  Vector2.prototype.mag = function() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  };
  /*
    Returns the squared magnitude of this vector
  */
  Vector2.prototype.magSq = function() {
    return this.x * this.x + this.y * this.y;
  };
  /*
    Normalizes the vector
  */
  Vector2.prototype.normalize = function() {
    this.div(this.mag());
  };
  /*
    Rotates the vector
  */
  Vector2.prototype.rotate = function(rotateBy) {
    var cosAngle = Math.cos(rotateBy);
    var sinAngle = Math.sin(rotateBy);
    var oldX = this.x;
    this.x = oldX * cosAngle - y * sinAngle;
    this.y = oldX * sinAngle + y * cosAngle;
  };
  /*
    Returns the midpoint of this and another vector
  */
  Vector2.prototype.mid = function(lineEnd) {
    return new Vector2(
      this.x / 2 + lineEnd.x / 2,
      this.y / 2 + lineEnd.y / 2
    );
  };
  /*
    Returns the distance between this and another vector
  */
  Vector2.prototype.dist = function(lineEnd) {
    return Vector2.sub(this, lineEnd).mag();
  };
  /*
    Returns the linear interpolation of this and another vector
  */
  Vector2.prototype.lerp = function(lerpWith, lerpStage) {
    return new Vector2(
      this.x + (lerpWith.x - this.x) * lerpStage,
      this.y + (lerpWith.y - this.y) * lerpStage
    );
  };
  /*
    Returns the dot product of this and another vector
  */
  Vector2.prototype.dot = function(dotWith) {
    return this.x * dotWith.x + this.y * dotWith.y;
  };
  /*
    Returns this vector converted to an array
  */
  Vector2.prototype.array = function() {
    return [this.x, this.y];
  };
  /*
    Returns the reflection of this vector over a line defined by two points
  */
  Vector2.prototype.reflect = function(linePoint1, linePoint2) {
    return Vector2.sub(this,
      Vector2.mult(
        Vector2.sub(this, new Vector2(
          (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), this)) /
          (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)), Equation.M(linePoint1, linePoint2) *
          (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), this)) /
          (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)) + Equation.B(linePoint1, linePoint2)
        )),
        2)
    );
  };
  /*
    Returns a copy of this vector
  */
  Vector2.prototype.get = function() {
    return new Vector2(this.x, this.y);
  };
  /*
    Sets the coordinates of this vector
  */
  Vector2.prototype.set = function(x, y) {
    this.x = x;
    this.y = y;
  };
}
<commit_msg>Update vector2.js<commit_after>if (!Vector2) {
  /*
    Vector2 is a more advanced, more specialized PVector.
  */
  var Vector2 = function(x, y) {
    this.x = x || 0;
    this.y = y || 0;
  };
  /*
    Returns the sum of two vectors
  */
  Vector2.add = function(toAdd1, toAdd2) {
    return new Vector2(
      toAdd1.x + toAdd2.x,
      toAdd1.y + toAdd2.y
    );
  };
  /*
    Returns the difference of two vectors
  */
  Vector2.sub = function(subtractFrom, toSubtract) {
    return new Vector2(
      subtractFrom.x - toSubtract.x,
      subtractFrom.y - toSubtract.y
    );
  };
  /*
    Returns the product of a vector and a scalar
  */
  Vector2.mult = function(toMultiply, scaleFactor) {
    return new Vector2(
      toMultiply.x * scaleFactor,
      toMultiply.y * scaleFactor
    );
  };
  /*
    Returns the quotient of a vector and a scalar
  */
  Vector2.div = function(toDivide, inverseFactor) {
    return new Vector2(
      toDivide.x / inverseFactor,
      toDivide.y / inverseFactor
    );
  };
  /*
    Returns the magnitude or length of a vector
  */
  Vector2.mag = function(toMeasure) {
    return Math.sqrt(toMeasure.x * toMeasure.x + toMeasure.y * toMeasure.y);
  };
  /*
    Returns the square of the magnitude of a vector
    This is much faster than .mag and works in some situations
  */
  Vector2.magSq = function(toMeasure) {
    return toMeasure.x * toMeasure.x + toMeasure.y * toMeasure.y;
  };
  /*
    Returns the unit equivalent of a vector
  */
  Vector2.normalize = function(toNormalize) {
    return Vector2.div(toNormalize, toNormalize.mag());
  };
  /*
    Returns the rotation of a vector
  */
  Vector2.rotate = function(toRotate, rotateBy) {
    var cosAngle = Math.cos(rotateBy);
    var sinAngle = Math.sin(rotateBy);
    return new Vector2(
      toRotate.x * cosAngle - toRotate.y * sinAngle,
      toRotate.x * sinAngle + toRotate.y * cosAngle
    );
  };
  /*
    Returns the midpoint of two vectors
  */
  Vector2.mid = function(lineEnd1, lineEnd2) {
    return new Vector2(
      lineEnd1.x / 2 + lineEnd2.x / 2,
      lineEnd1.y / 2 + lineEnd2.y / 2
    );
  };
  /*
    Returns the distance between two vectors
  */
  Vector2.dist = function(lineEnd1, lineEnd2) {
    return Vector2.sub(lineEnd1, lineEnd2).mag();
  };
  /*
    Returns the linear interpolation of two vectors
  */
  Vector2.lerp = function(lerpFrom, lerpTo, lerpStage) {
    return new Vector2(
      lerpFrom.x + (lerpTo.x - lerpFrom.x) * lerpStage,
      lerpFrom.y + (lerpTo.y - lerpFrom.y) * lerpStage
    );
  };
  /*
    Returns the dot product of two vectors
  */
  Vector2.dot = function(toDot1, toDot2) {
    return toDot1.x * toDot2.x + toDot1.y * toDot2.y;
  };
  /*
    Returns a vector converted to an array
  */
  Vector2.array = function(toConvert) {
    return [toConvert.x, toConvert.y];
  };
  /*
    Returns the reflection of one vector over the line represented by two other vectors
  */
  Vector2.reflect = function(toReflect, linePoint1, linePoint2) {
    return Vector2.sub(toReflect,
      Vector2.mult(
        Vector2.sub(toReflect, new Vector2(
          (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), toReflect)) /
          (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)), Equation.M(linePoint1, linePoint2) *
          (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), toReflect)) /
          (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)) + Equation.B(linePoint1, linePoint2)
        )),
        2)
    );
  };

  /*
    Adds a vector to this vector
  */
  Vector2.prototype.add = function(toAdd) {
    this.x += toAdd.x;
    this.y += toAdd.y;
  };
  /*
    Subtracts a vector from this vector
  */
  Vector2.prototype.sub = function(toSubtract) {
    this.x -= toSubtract.x;
    this.y -= toSubtract.y;
  };
  /*
    Scales this vector
  */
  Vector2.prototype.mult = function(scaleFactor) {
    this.x *= scaleFactor;
    this.y *= scaleFactor;
  };
  /*
    Inversely scales this vector
  */
  Vector2.prototype.div = function(inverseFactor) {
    this.x /= inverseFactor;
    this.y /= inverseFactor;
  };
  /*
    Returns the magnitude of this vector
  */
  Vector2.prototype.mag = function() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  };
  /*
    Returns the squared magnitude of this vector
  */
  Vector2.prototype.magSq = function() {
    return this.x * this.x + this.y * this.y;
  };
  /*
    Normalizes the vector
  */
  Vector2.prototype.normalize = function() {
    this.div(this.mag());
  };
  /*
    Rotates the vector
  */
  Vector2.prototype.rotate = function(rotateBy) {
    var cosAngle = Math.cos(rotateBy);
    var sinAngle = Math.sin(rotateBy);
    var oldX = this.x;
    this.x = oldX * cosAngle - this.y * sinAngle;
    this.y = oldX * sinAngle + this.y * cosAngle;
  };
  /*
    Returns the midpoint of this and another vector
  */
  Vector2.prototype.mid = function(lineEnd) {
    return new Vector2(
      this.x / 2 + lineEnd.x / 2,
      this.y / 2 + lineEnd.y / 2
    );
  };
  /*
    Returns the distance between this and another vector
  */
  Vector2.prototype.dist = function(lineEnd) {
    return Vector2.sub(this, lineEnd).mag();
  };
  /*
    Returns the linear interpolation of this and another vector
  */
  Vector2.prototype.lerp = function(lerpWith, lerpStage) {
    return new Vector2(
      this.x + (lerpWith.x - this.x) * lerpStage,
      this.y + (lerpWith.y - this.y) * lerpStage
    );
  };
  /*
    Returns the dot product of this and another vector
  */
  Vector2.prototype.dot = function(dotWith) {
    return this.x * dotWith.x + this.y * dotWith.y;
  };
  /*
    Returns this vector converted to an array
  */
  Vector2.prototype.array = function() {
    return [this.x, this.y];
  };
  /*
    Returns the reflection of this vector over a line defined by two points
  */
  Vector2.prototype.reflect = function(linePoint1, linePoint2) {
    return Vector2.sub(this,
      Vector2.mult(
        Vector2.sub(this, new Vector2(
          (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), this)) /
          (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)), Equation.M(linePoint1, linePoint2) *
          (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), this)) /
          (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)) + Equation.B(linePoint1, linePoint2)
        )),
        2)
    );
  };
  /*
    Returns a copy of this vector
  */
  Vector2.prototype.get = function() {
    return new Vector2(this.x, this.y);
  };
  /*
    Sets the coordinates of this vector
  */
  Vector2.prototype.set = function(x, y) {
    this.x = x;
    this.y = y;
  };
}
<|endoftext|>