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

if (!window.Echo) window.Echo = {};

if (Echo.Loader) return;

var protocol = /^https?/.test(window.location.protocol) ? window.location.protocol : "http:";

/**
 * @class Echo.Loader
 * Static class which implements common mechanics for resources loading,
 * Echo environment establishing and Canvases initialization mechanics.
 *
 * @package loader.js
 */
Echo.Loader = {
	/** @private @readonly */
	"version": "",
	/** @ignore */
	"debug": false,
	/** @private */
	"config": {
		"cdnBaseURL": protocol + "//cdn.echoenabled.com/",
		"storageURL": {
			"dev": protocol + "//s3.amazonaws.com/echo-canvases/",
			// TODO: replace it with alias when it will be prepared
			"prod": protocol + "//dqspik3j3bxvu.cloudfront.net/"
		},
		"errorTimeout": 5000 // 5 sec
	},
	/** @ignore */
	"canvases": [],  // Canvases list initialized on the page
	/** @ignore */
	"overrides": {},  // Canvas Apps overrides object
	/** @ignore */
	"vars": {
		"state": {"resources": {}, "queue": []},
		"processing": false,
		"syncQueue": []
	}
};

/**
 * @static
 * Function to get normalized URL.
 *
 * @param {String} url
 * JavaScript or CSS stylesheet file URL.
 *
 * @param {Boolean} [devVersion=true]
 * Specifies whether function should return dev version of the file or not,
 * false value is useful when we want to get URL to image because
 * images don't have dev versions
 */
Echo.Loader.getURL = function(url, devVersion) {
	if (typeof devVersion === "undefined") devVersion = true;
	return /^https?:\/\/|^\/\//.test(url)
		? url
		: Echo.Loader.config.cdnBaseURL + "sdk/v" + Echo.Loader.version +
			(devVersion && Echo.Loader.isDebug() ? "/dev" : "") +
			(!url || url.charAt(0) === "/" ? "" : "/") + url;
};

/**
 * @static
 * Function to load the JavaScript or CSS stylesheet files in async mode.
 *
 * @param {Array} resources
 * Array of objects with the properties described below:
 *
 * @param {String} resources.url
 * JavaScript or CSS stylesheet file URL.
 *
 * @param {Function} resources.loaded
 * Function used to check whether the script was loaded. This function must return
 * the boolean value which indicates whether the resource was already loaded on the
 * page or not. If the resource has already been loaded - no download is performed
 * and the callback is called immediately.
 *
 * @param {Function} [callback]
 * Callback function which should be called as soon as all requested files
 * were downloaded.
 *
 * @param {Object} [config]
 * Object with configuration parameters
 *
 * @param {Number} config.errorTimeout
 * Timeout loading of resources in milliseconds, use as yepnope.errorTimeout
 *
 */
Echo.Loader.download = function(resources, callback, config) {
	config = config || {};
	callback = callback || function() {};

	if (!resources || !resources.length) {
		callback();
		return;
	}

	var state = Echo.Loader.vars.state;
	var syncQueue = Echo.Loader.vars.syncQueue;
	var invokeCallbacks = function() {
		var callbacks = [];
		// Important note: we should *not* execute callbacks
		// while iterating through the queue. We need to update
		// the queue first and only after that execute the callbacks,
		// because there might be calls to "Echo.Loader.download" function
		// which can interfere with the current queue state.
		state.queue = Echo.Loader._map(state.queue, function(item) {
			if (Echo.Loader._areResourcesReady(item.resources)) {
				callbacks.push(item.callback);
				return; // do *not* put this resource back into the queue
			}
			return item;
		});
		Echo.Loader._map(callbacks, function(_callback) { _callback(); });
	};

	// Important note: we should *not* execute another
	// Echo.yepnope until last one is completed.
	// See more information about the issue on Github:
	// https://github.com/SlexAxton/yepnope.js/issues/113
	var checkSyncQueue = function() {
		if (!Echo.Loader.vars.processing && syncQueue.length) {
			Echo.Loader.vars.processing = true;
			Echo.yepnope(syncQueue.shift());
		}
	};

	state.queue.push({"resources": resources, "callback": callback});

	var urls = Echo.Loader._map(resources, function(resource) {
		var url = Echo.Loader.getURL(resource.url);
		if (!Echo.Loader._areResourcesReady([resource]) &&
			state.resources[url] !== "loading") {
				state.resources[url] = "loading";
				return url;
		}
	});

	// invoke queued handler in case all requested resources
	// are ready by the time the "download" function is called
	if (!urls.length) {
		invokeCallbacks();
		return;
	}

	var prefix = "timeout=" + (config.errorTimeout || Echo.Loader.config.errorTimeout) + "!";
	syncQueue.push({
		"load": Echo.Loader._map(urls, function(url) { return prefix + url; }),
		"complete": function() {
			// mark all loaded scripts as "ready"
			Echo.Loader._map(urls, function(url) {
				state.resources[url] = "ready";
			});
			invokeCallbacks();
			Echo.Loader.vars.processing = false;
			checkSyncQueue();
		}
	});
	checkSyncQueue();
};

/**
 * @static
 * Allows to identify if the debug mode is enabled for Echo environment
 * on the page (i.e whether the logs should be printed in console,
 * non-minified versions of scripts should be used)
 *
 * @return {Boolean}
 */
Echo.Loader.isDebug = function() {
	return Echo.Loader.debug;
};

(function() {
	if (Echo.Loader.debug) return;

	var debug;
	var _debugCookieName = "echo-debug";
	var options = {"path": "/"};
	var hashParts = window.location.hash.match(/echo.debug:(true|false)/);
	if (hashParts && hashParts.length) {
		debug = hashParts[1];
	}
	if (typeof debug !== "undefined") {
		if (debug === "true") {
			Echo.Loader.debug = true;
			Echo.Cookie.set(_debugCookieName, true, options);
		} else {
			Echo.Loader.debug = false;
			Echo.Cookie.remove(_debugCookieName, options);
		}
		return;
	}
	Echo.Loader.debug = !!Echo.Cookie.get(_debugCookieName);
})();

/**
 * @static
 * Function to initialize Echo environment on the page by downloading Backplane lib,
 * jQuery library with the necessary dependencies and the base Echo classes.
 *
 * @param {Function} [callback]
 * Callback function which should be called as soon as Echo environment is ready.
 */
Echo.Loader.initEnvironment = function(callback) {
	var resources = [{
		"url": "backplane.js",
		"loaded": function() { return !!window.Backplane; }
	}, {
		"url": "third-party/jquery.pack.js",
		"loaded": function() { return !!Echo.jQuery; }
	}, {
		"url": "environment.pack.js",
		"loaded": function() { return !!Echo.Utils; }
	}];
	if (Echo.Loader._areResourcesReady(resources)) {
		callback && callback();
		return;
	}
	Echo.Loader.download(resources, callback);
};

/**
 * @static
 * Function which provides an ability to override config parameters of the
 * specific application within the canvas.
 *
 * @param {String} canvasID
 * Canvas ID.
 *
 * @param {String} appID
 * Application ID inside the canvas.
 *
 * @param {Object} config
 * Object with the application config overrides.
 */
Echo.Loader.override = function(canvasID, appID, config) {
	var overrides = Echo.Loader.overrides;
	overrides[canvasID] = overrides[canvasID] || {};
	overrides[canvasID][appID] = config;
};

/**
 * @static
 * Function to initialize canvases on the page.
 *
 * @param {Object} [config]
 * Object which defines the initialization of config parameters
 *
 * @param {Mixed} [config.canvases]
 * Array of jQuery elements or a single jQuery element, which represents a
 * canvas target. If this param is omitted, Echo Loader will look for the
 * canvases in the DOM structure.
 *
 * @param {Object} [config.target]
 * Target element where Echo Loader should look for the canvases if no
 * canvases were passed in the "config.canvases" field.
 */
Echo.Loader.init = function(config) {
	config = config || {};
	Echo.Loader.initEnvironment(function() {
		var $ = Echo.jQuery;
		var canvases = config.canvases;

		// convert a single canvas to the 1-element array
		// to keep the same contract below in the code
		if (canvases && !$.isArray(canvases) && !(canvases instanceof $)) {
			canvases = [canvases];
		}

		// if no canvases defined during initialization,
		// we look for all canvases in the target ('document' by default)
		canvases = canvases || $(".echo-canvas", config.target);

		$.map(canvases || [], function(canvas) {
			var target = $(canvas);
			var instance = new Echo.Canvas({
				"target": target,
				"overrides": Echo.Loader.overrides[target.data("canvas-id")] || {}
			});
			Echo.Loader.canvases.push(instance);
		});
	});
};

/**
 * @static
 * Function to initialize application on the page. The function performs the following actions:
 *
 * + initializes Echo JavaScript environment (if it was not initialized yet)
 * + establishes the Backplane connection (if app.backplane is defined)
 * + establishes Echo User session on the page (if app.config.appkey is defined)
 * + downloads the application script
 * + calls the app JavaScript class constructor which handles further application initialization
 *
 * @param {Object} app
 * Object which defines the base app configuration.
 *
 * @param {String} app.component
 * The name of the JavaScript app class which should be initialized.
 *
 * @param {String} app.script
 * Appliction JavaScript class script URL.
 *
 * @param {Object} [app.scripts]
 * Object which specifies the location (URL) of the production (minified) and development
 * (non-minified) versions of the app JavaScript class code. The "prod" and "dev" keys
 * should be used in order to specify the production and development URLs respectively.
 *
 * @param {Object} [app.backplane]
 * Object which contains the data to be passed into the Backplane.init call.
 *
 * @param {Object} [app.config]
 * Parameters to be passed into the application constructor during its initialization.
 */
Echo.Loader.initApplication = function(app) {
	Echo.Loader.initEnvironment(function() {
		var instance = new Echo.Canvas({
			"target": app.config.target,
			"useSecureAPI": !!app.config.useSecureAPI,
			"data": { // as we receive if from the Canvas Storage
				"apps": [app],
				"backplane": app.backplane
			}
		});
		Echo.Loader.canvases.push(instance);
	});
};

// implementation of the "map" function for the cases when jQuery is not loaded yet
Echo.Loader._map = function(list, iterator) {
	var result = [];
	if (list && list.length && iterator) {
		for (var i = 0; i < list.length; i++) {
			var value = iterator(list[i], i);
			if (value === false) break; // jQuery-like convention
			if (typeof value !== "undefined") result.push(value);
		}
	}
	return result;
};

Echo.Loader._areResourcesReady = function(resources) {
	var state = Echo.Loader.vars.state;
	var resourceReadyFlags = Echo.Loader._map(resources, function(resource) {
		var url = Echo.Loader.getURL(resource.url);
		// the 'true' flag will be added into the
		// result array only when resource is ready
		return (resource.loaded && resource.loaded()) ||
			(state.resources[url] && state.resources[url] === "ready");
	});
	return resources.length === resourceReadyFlags.length;
};

})();
<commit_msg>[Echo.Loader] update prod canvas storage URL<commit_after>(function() {
"use strict";

if (!window.Echo) window.Echo = {};

if (Echo.Loader) return;

var protocol = /^https?/.test(window.location.protocol) ? window.location.protocol : "http:";

/**
 * @class Echo.Loader
 * Static class which implements common mechanics for resources loading,
 * Echo environment establishing and Canvases initialization mechanics.
 *
 * @package loader.js
 */
Echo.Loader = {
	/** @private @readonly */
	"version": "",
	/** @ignore */
	"debug": false,
	/** @private */
	"config": {
		"cdnBaseURL": protocol + "//cdn.echoenabled.com/",
		"storageURL": {
			"prod": protocol + "//canvases.echoenabled.com/",
			"dev": protocol + "//s3.amazonaws.com/echo-canvases/"
		},
		"errorTimeout": 5000 // 5 sec
	},
	/** @ignore */
	"canvases": [],  // Canvases list initialized on the page
	/** @ignore */
	"overrides": {},  // Canvas Apps overrides object
	/** @ignore */
	"vars": {
		"state": {"resources": {}, "queue": []},
		"processing": false,
		"syncQueue": []
	}
};

/**
 * @static
 * Function to get normalized URL.
 *
 * @param {String} url
 * JavaScript or CSS stylesheet file URL.
 *
 * @param {Boolean} [devVersion=true]
 * Specifies whether function should return dev version of the file or not,
 * false value is useful when we want to get URL to image because
 * images don't have dev versions
 */
Echo.Loader.getURL = function(url, devVersion) {
	if (typeof devVersion === "undefined") devVersion = true;
	return /^https?:\/\/|^\/\//.test(url)
		? url
		: Echo.Loader.config.cdnBaseURL + "sdk/v" + Echo.Loader.version +
			(devVersion && Echo.Loader.isDebug() ? "/dev" : "") +
			(!url || url.charAt(0) === "/" ? "" : "/") + url;
};

/**
 * @static
 * Function to load the JavaScript or CSS stylesheet files in async mode.
 *
 * @param {Array} resources
 * Array of objects with the properties described below:
 *
 * @param {String} resources.url
 * JavaScript or CSS stylesheet file URL.
 *
 * @param {Function} resources.loaded
 * Function used to check whether the script was loaded. This function must return
 * the boolean value which indicates whether the resource was already loaded on the
 * page or not. If the resource has already been loaded - no download is performed
 * and the callback is called immediately.
 *
 * @param {Function} [callback]
 * Callback function which should be called as soon as all requested files
 * were downloaded.
 *
 * @param {Object} [config]
 * Object with configuration parameters
 *
 * @param {Number} config.errorTimeout
 * Timeout loading of resources in milliseconds, use as yepnope.errorTimeout
 *
 */
Echo.Loader.download = function(resources, callback, config) {
	config = config || {};
	callback = callback || function() {};

	if (!resources || !resources.length) {
		callback();
		return;
	}

	var state = Echo.Loader.vars.state;
	var syncQueue = Echo.Loader.vars.syncQueue;
	var invokeCallbacks = function() {
		var callbacks = [];
		// Important note: we should *not* execute callbacks
		// while iterating through the queue. We need to update
		// the queue first and only after that execute the callbacks,
		// because there might be calls to "Echo.Loader.download" function
		// which can interfere with the current queue state.
		state.queue = Echo.Loader._map(state.queue, function(item) {
			if (Echo.Loader._areResourcesReady(item.resources)) {
				callbacks.push(item.callback);
				return; // do *not* put this resource back into the queue
			}
			return item;
		});
		Echo.Loader._map(callbacks, function(_callback) { _callback(); });
	};

	// Important note: we should *not* execute another
	// Echo.yepnope until last one is completed.
	// See more information about the issue on Github:
	// https://github.com/SlexAxton/yepnope.js/issues/113
	var checkSyncQueue = function() {
		if (!Echo.Loader.vars.processing && syncQueue.length) {
			Echo.Loader.vars.processing = true;
			Echo.yepnope(syncQueue.shift());
		}
	};

	state.queue.push({"resources": resources, "callback": callback});

	var urls = Echo.Loader._map(resources, function(resource) {
		var url = Echo.Loader.getURL(resource.url);
		if (!Echo.Loader._areResourcesReady([resource]) &&
			state.resources[url] !== "loading") {
				state.resources[url] = "loading";
				return url;
		}
	});

	// invoke queued handler in case all requested resources
	// are ready by the time the "download" function is called
	if (!urls.length) {
		invokeCallbacks();
		return;
	}

	var prefix = "timeout=" + (config.errorTimeout || Echo.Loader.config.errorTimeout) + "!";
	syncQueue.push({
		"load": Echo.Loader._map(urls, function(url) { return prefix + url; }),
		"complete": function() {
			// mark all loaded scripts as "ready"
			Echo.Loader._map(urls, function(url) {
				state.resources[url] = "ready";
			});
			invokeCallbacks();
			Echo.Loader.vars.processing = false;
			checkSyncQueue();
		}
	});
	checkSyncQueue();
};

/**
 * @static
 * Allows to identify if the debug mode is enabled for Echo environment
 * on the page (i.e whether the logs should be printed in console,
 * non-minified versions of scripts should be used)
 *
 * @return {Boolean}
 */
Echo.Loader.isDebug = function() {
	return Echo.Loader.debug;
};

(function() {
	if (Echo.Loader.debug) return;

	var debug;
	var _debugCookieName = "echo-debug";
	var options = {"path": "/"};
	var hashParts = window.location.hash.match(/echo.debug:(true|false)/);
	if (hashParts && hashParts.length) {
		debug = hashParts[1];
	}
	if (typeof debug !== "undefined") {
		if (debug === "true") {
			Echo.Loader.debug = true;
			Echo.Cookie.set(_debugCookieName, true, options);
		} else {
			Echo.Loader.debug = false;
			Echo.Cookie.remove(_debugCookieName, options);
		}
		return;
	}
	Echo.Loader.debug = !!Echo.Cookie.get(_debugCookieName);
})();

/**
 * @static
 * Function to initialize Echo environment on the page by downloading Backplane lib,
 * jQuery library with the necessary dependencies and the base Echo classes.
 *
 * @param {Function} [callback]
 * Callback function which should be called as soon as Echo environment is ready.
 */
Echo.Loader.initEnvironment = function(callback) {
	var resources = [{
		"url": "backplane.js",
		"loaded": function() { return !!window.Backplane; }
	}, {
		"url": "third-party/jquery.pack.js",
		"loaded": function() { return !!Echo.jQuery; }
	}, {
		"url": "environment.pack.js",
		"loaded": function() { return !!Echo.Utils; }
	}];
	if (Echo.Loader._areResourcesReady(resources)) {
		callback && callback();
		return;
	}
	Echo.Loader.download(resources, callback);
};

/**
 * @static
 * Function which provides an ability to override config parameters of the
 * specific application within the canvas.
 *
 * @param {String} canvasID
 * Canvas ID.
 *
 * @param {String} appID
 * Application ID inside the canvas.
 *
 * @param {Object} config
 * Object with the application config overrides.
 */
Echo.Loader.override = function(canvasID, appID, config) {
	var overrides = Echo.Loader.overrides;
	overrides[canvasID] = overrides[canvasID] || {};
	overrides[canvasID][appID] = config;
};

/**
 * @static
 * Function to initialize canvases on the page.
 *
 * @param {Object} [config]
 * Object which defines the initialization of config parameters
 *
 * @param {Mixed} [config.canvases]
 * Array of jQuery elements or a single jQuery element, which represents a
 * canvas target. If this param is omitted, Echo Loader will look for the
 * canvases in the DOM structure.
 *
 * @param {Object} [config.target]
 * Target element where Echo Loader should look for the canvases if no
 * canvases were passed in the "config.canvases" field.
 */
Echo.Loader.init = function(config) {
	config = config || {};
	Echo.Loader.initEnvironment(function() {
		var $ = Echo.jQuery;
		var canvases = config.canvases;

		// convert a single canvas to the 1-element array
		// to keep the same contract below in the code
		if (canvases && !$.isArray(canvases) && !(canvases instanceof $)) {
			canvases = [canvases];
		}

		// if no canvases defined during initialization,
		// we look for all canvases in the target ('document' by default)
		canvases = canvases || $(".echo-canvas", config.target);

		$.map(canvases || [], function(canvas) {
			var target = $(canvas);
			var instance = new Echo.Canvas({
				"target": target,
				"overrides": Echo.Loader.overrides[target.data("canvas-id")] || {}
			});
			Echo.Loader.canvases.push(instance);
		});
	});
};

/**
 * @static
 * Function to initialize application on the page. The function performs the following actions:
 *
 * + initializes Echo JavaScript environment (if it was not initialized yet)
 * + establishes the Backplane connection (if app.backplane is defined)
 * + establishes Echo User session on the page (if app.config.appkey is defined)
 * + downloads the application script
 * + calls the app JavaScript class constructor which handles further application initialization
 *
 * @param {Object} app
 * Object which defines the base app configuration.
 *
 * @param {String} app.component
 * The name of the JavaScript app class which should be initialized.
 *
 * @param {String} app.script
 * Appliction JavaScript class script URL.
 *
 * @param {Object} [app.scripts]
 * Object which specifies the location (URL) of the production (minified) and development
 * (non-minified) versions of the app JavaScript class code. The "prod" and "dev" keys
 * should be used in order to specify the production and development URLs respectively.
 *
 * @param {Object} [app.backplane]
 * Object which contains the data to be passed into the Backplane.init call.
 *
 * @param {Object} [app.config]
 * Parameters to be passed into the application constructor during its initialization.
 */
Echo.Loader.initApplication = function(app) {
	Echo.Loader.initEnvironment(function() {
		var instance = new Echo.Canvas({
			"target": app.config.target,
			"useSecureAPI": !!app.config.useSecureAPI,
			"data": { // as we receive if from the Canvas Storage
				"apps": [app],
				"backplane": app.backplane
			}
		});
		Echo.Loader.canvases.push(instance);
	});
};

// implementation of the "map" function for the cases when jQuery is not loaded yet
Echo.Loader._map = function(list, iterator) {
	var result = [];
	if (list && list.length && iterator) {
		for (var i = 0; i < list.length; i++) {
			var value = iterator(list[i], i);
			if (value === false) break; // jQuery-like convention
			if (typeof value !== "undefined") result.push(value);
		}
	}
	return result;
};

Echo.Loader._areResourcesReady = function(resources) {
	var state = Echo.Loader.vars.state;
	var resourceReadyFlags = Echo.Loader._map(resources, function(resource) {
		var url = Echo.Loader.getURL(resource.url);
		// the 'true' flag will be added into the
		// result array only when resource is ready
		return (resource.loaded && resource.loaded()) ||
			(state.resources[url] && state.resources[url] === "ready");
	});
	return resources.length === resourceReadyFlags.length;
};

})();
<|endoftext|>


<commit_before>var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var dust = require('dustjs-linkedin');

// default prefix that should be prepended to all console.logs/errors
var prefix = 'RES: ';

var debug = typeof DEBUG_RESPONDER === 'boolean' ? DEBUG_RESPONDER : false;

module.exports = function(config) {

	// render/serialize and send response
	return function responder(req, res, next) {
		_.merge(res.locals, res.data,
			_.pick(res, 'navigation', 'page'),
			_.pick(res.page, 'template'));

		var template = res.locals.template || res.template;

		var formats = {
			html: function () {
				if (debug) console.log(prefix + ' ACCEPTS html, returning html');

				res.render(res.template || res.master || 'master');
			},

			json: function () {
				if (debug) console.log(prefix + ' ACCEPTS json, returning json');

				if(template) {
					if(res.statusCode > 399)
						template = dust.cache[res.statusCode] || 'error';

					var obj = dust.template(template);

					var templates = [ template ];

					if(obj.dependencies) templates = templates.concat(dust.dependencies(template));

					res.json(_.extend({
						template: template,
						compiled: _.map(templates, dust.compiled, dust),
						data: res.locals
					}, _.pick(res.locals.page, 'view')));
				} else {
					// if there is only a single value in the data object
					// (this can be a model/object or collection/array)
					// then only return that value.
					var keys = Object.keys(res.data);
					res.json(keys.length == 1 ? res.data[keys[0]] : res.data);
				}
			},

			default: function () {
				if (debug) console.log(prefix + ' Cannot find suitable ACCEPTS, returning status');
				res.sendStatus(res.statusCode || 406);
			}
		};

		//if (!template && !res.page) delete formats.html;

		res.format(formats);

		// TODO place in a better place
		delete req.session.lastPath;
	};
	// generates Not Found error if there is no page to render and no truthy values in data
};
<commit_msg>Remove all references to res.template (use res.locals.template or res.master instead).<commit_after>var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var dust = require('dustjs-linkedin');

// default prefix that should be prepended to all console.logs/errors
var prefix = 'RES: ';

var debug = typeof DEBUG_RESPONDER === 'boolean' ? DEBUG_RESPONDER : false;

module.exports = function(config) {

	// render/serialize and send response
	return function responder(req, res, next) {
		_.merge(res.locals, res.data,
			_.pick(res, 'navigation', 'page'),
			_.pick(res.page, 'template'));

		var formats = {
			html: function () {
				if (debug) console.log(prefix + ' ACCEPTS html, returning html');

				res.render(res.master || 'master');
			},

			json: function () {
				if (debug) console.log(prefix + ' ACCEPTS json, returning json');

				var template = res.locals.template;

				if(template) {
					if(res.statusCode > 399)
						template = dust.cache[res.statusCode] || 'error';

					var obj = dust.template(template);

					var templates = [ template ];

					if(obj.dependencies) templates = templates.concat(dust.dependencies(template));

					res.json(_.extend({
						template: template,
						compiled: _.map(templates, dust.compiled, dust),
						data: res.locals
					}, _.pick(res.locals.page, 'view')));
				} else {
					// if there is only a single value in the data object
					// (this can be a model/object or collection/array)
					// then only return that value.
					var keys = Object.keys(res.data);
					res.json(keys.length == 1 ? res.data[keys[0]] : res.data);
				}
			},

			default: function () {
				if (debug) console.log(prefix + ' Cannot find suitable ACCEPTS, returning status');
				res.sendStatus(res.statusCode || 406);
			}
		};

		//if (!template && !res.page) delete formats.html;

		res.format(formats);

		// TODO place in a better place
		delete req.session.lastPath;
	};
	// generates Not Found error if there is no page to render and no truthy values in data
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

'use strict';

import {
  type EventSubscription,
  type IEventEmitter,
} from '../vendor/emitter/EventEmitter';
import Platform from '../Utilities/Platform';
import RCTDeviceEventEmitter from './RCTDeviceEventEmitter';
import invariant from 'invariant';

interface NativeModule {
  addListener(eventType: string): void;
  removeListeners(count: number): void;
}

export type {EventSubscription};

/**
 * `NativeEventEmitter` is intended for use by Native Modules to emit events to
 * JavaScript listeners. If a `NativeModule` is supplied to the constructor, it
 * will be notified (via `addListener` and `removeListeners`) when the listener
 * count changes to manage "native memory".
 *
 * Currently, all native events are fired via a global `RCTDeviceEventEmitter`.
 * This means event names must be globally unique, and it means that call sites
 * can theoretically listen to `RCTDeviceEventEmitter` (although discouraged).
 */
export default class NativeEventEmitter<TEventToArgsMap: {...}>
  implements IEventEmitter<TEventToArgsMap> {
  _nativeModule: ?NativeModule;

  constructor(nativeModule: ?NativeModule) {
    if (Platform.OS === 'ios') {
      invariant(
        nativeModule != null,
        '`new NativeEventEmitter()` requires a non-null argument.',
      );
    }

    const hasAddListener =
      !!nativeModule && typeof nativeModule.addListener === 'function';
    const hasRemoveListeners =
      !!nativeModule && typeof nativeModule.removeListeners === 'function';

    if (nativeModule && hasAddListener && hasRemoveListeners) {
      this._nativeModule = nativeModule;
    } else {
      if (!hasAddListener) {
        console.warn(
          '`new NativeEventEmitter()` was called with a non-null argument without the required `addListener` method.',
        );
      }
      if (!hasRemoveListeners) {
        console.warn(
          '`new NativeEventEmitter()` was called with a non-null argument without the required `removeListeners` method.',
        );
      }
    }
  }

  addListener<TEvent: $Keys<TEventToArgsMap>>(
    eventType: TEvent,
    listener: (...args: $ElementType<TEventToArgsMap, TEvent>) => mixed,
    context?: mixed,
  ): EventSubscription {
    this._nativeModule?.addListener(eventType);
    let subscription: ?EventSubscription = RCTDeviceEventEmitter.addListener(
      eventType,
      listener,
      context,
    );

    return {
      remove: () => {
        if (subscription != null) {
          this._nativeModule?.removeListeners(1);
          // $FlowFixMe[incompatible-use]
          subscription.remove();
          subscription = null;
        }
      },
    };
  }

  /**
   * @deprecated Use `remove` on the EventSubscription from `addListener`.
   */
  removeListener<TEvent: $Keys<TEventToArgsMap>>(
    eventType: TEvent,
    listener: (...args: $ElementType<TEventToArgsMap, TEvent>) => mixed,
  ): void {
    this._nativeModule?.removeListeners(1);
    // NOTE: This will report a deprecation notice via `console.error`.
    // $FlowFixMe[prop-missing] - `removeListener` exists but is deprecated.
    RCTDeviceEventEmitter.removeListener(eventType, listener);
  }

  emit<TEvent: $Keys<TEventToArgsMap>>(
    eventType: TEvent,
    ...args: $ElementType<TEventToArgsMap, TEvent>
  ): void {
    // Generally, `RCTDeviceEventEmitter` is directly invoked. But this is
    // included for completeness.
    RCTDeviceEventEmitter.emit(eventType, ...args);
  }

  removeAllListeners<TEvent: $Keys<TEventToArgsMap>>(
    eventType?: ?TEvent,
  ): void {
    invariant(
      eventType != null,
      '`NativeEventEmitter.removeAllListener()` requires a non-null argument.',
    );
    this._nativeModule?.removeListeners(this.listenerCount(eventType));
    RCTDeviceEventEmitter.removeAllListeners(eventType);
  }

  listenerCount<TEvent: $Keys<TEventToArgsMap>>(eventType: TEvent): number {
    return RCTDeviceEventEmitter.listenerCount(eventType);
  }
}
<commit_msg>Fix incorrect warning on NativeEventEmitter when nativeModule is null<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

'use strict';

import {
  type EventSubscription,
  type IEventEmitter,
} from '../vendor/emitter/EventEmitter';
import Platform from '../Utilities/Platform';
import RCTDeviceEventEmitter from './RCTDeviceEventEmitter';
import invariant from 'invariant';

interface NativeModule {
  addListener(eventType: string): void;
  removeListeners(count: number): void;
}

export type {EventSubscription};

/**
 * `NativeEventEmitter` is intended for use by Native Modules to emit events to
 * JavaScript listeners. If a `NativeModule` is supplied to the constructor, it
 * will be notified (via `addListener` and `removeListeners`) when the listener
 * count changes to manage "native memory".
 *
 * Currently, all native events are fired via a global `RCTDeviceEventEmitter`.
 * This means event names must be globally unique, and it means that call sites
 * can theoretically listen to `RCTDeviceEventEmitter` (although discouraged).
 */
export default class NativeEventEmitter<TEventToArgsMap: {...}>
  implements IEventEmitter<TEventToArgsMap> {
  _nativeModule: ?NativeModule;

  constructor(nativeModule: ?NativeModule) {
    if (Platform.OS === 'ios') {
      invariant(
        nativeModule != null,
        '`new NativeEventEmitter()` requires a non-null argument.',
      );
    }

    const hasAddListener =
      !!nativeModule && typeof nativeModule.addListener === 'function';
    const hasRemoveListeners =
      !!nativeModule && typeof nativeModule.removeListeners === 'function';

    if (nativeModule && hasAddListener && hasRemoveListeners) {
      this._nativeModule = nativeModule;
    } else if (nativeModule != null) {
      if (!hasAddListener) {
        console.warn(
          '`new NativeEventEmitter()` was called with a non-null argument without the required `addListener` method.',
        );
      }
      if (!hasRemoveListeners) {
        console.warn(
          '`new NativeEventEmitter()` was called with a non-null argument without the required `removeListeners` method.',
        );
      }
    }
  }

  addListener<TEvent: $Keys<TEventToArgsMap>>(
    eventType: TEvent,
    listener: (...args: $ElementType<TEventToArgsMap, TEvent>) => mixed,
    context?: mixed,
  ): EventSubscription {
    this._nativeModule?.addListener(eventType);
    let subscription: ?EventSubscription = RCTDeviceEventEmitter.addListener(
      eventType,
      listener,
      context,
    );

    return {
      remove: () => {
        if (subscription != null) {
          this._nativeModule?.removeListeners(1);
          // $FlowFixMe[incompatible-use]
          subscription.remove();
          subscription = null;
        }
      },
    };
  }

  /**
   * @deprecated Use `remove` on the EventSubscription from `addListener`.
   */
  removeListener<TEvent: $Keys<TEventToArgsMap>>(
    eventType: TEvent,
    listener: (...args: $ElementType<TEventToArgsMap, TEvent>) => mixed,
  ): void {
    this._nativeModule?.removeListeners(1);
    // NOTE: This will report a deprecation notice via `console.error`.
    // $FlowFixMe[prop-missing] - `removeListener` exists but is deprecated.
    RCTDeviceEventEmitter.removeListener(eventType, listener);
  }

  emit<TEvent: $Keys<TEventToArgsMap>>(
    eventType: TEvent,
    ...args: $ElementType<TEventToArgsMap, TEvent>
  ): void {
    // Generally, `RCTDeviceEventEmitter` is directly invoked. But this is
    // included for completeness.
    RCTDeviceEventEmitter.emit(eventType, ...args);
  }

  removeAllListeners<TEvent: $Keys<TEventToArgsMap>>(
    eventType?: ?TEvent,
  ): void {
    invariant(
      eventType != null,
      '`NativeEventEmitter.removeAllListener()` requires a non-null argument.',
    );
    this._nativeModule?.removeListeners(this.listenerCount(eventType));
    RCTDeviceEventEmitter.removeAllListeners(eventType);
  }

  listenerCount<TEvent: $Keys<TEventToArgsMap>>(eventType: TEvent): number {
    return RCTDeviceEventEmitter.listenerCount(eventType);
  }
}
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { ListView, StyleSheet, Text, TouchableHighlight, View } from 'react-native';
import AbstractComponent from './AbstractComponent';
import Icon from './Icon';
import Button from './Button';
import { Colors } from './styles';

const styles = StyleSheet.create({
  container: {
    borderBottomWidth: 1,
    borderTopWidth: 1
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    height: 45,
    alignItems: 'center',
    marginLeft: 15,
    paddingRight: 15
  },
  header: {
    width: 30
  },
  body: {
    flex: 1
  },
  text: {
    color: '#000'
  },
  separator: {
    height: 1,
    marginLeft: 15
  }
});

/**
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/5/25
 */
class List extends AbstractComponent {

  static propTypes = {
    bodyTextStyle: Text.propTypes.style,
    cellStyle: View.propTypes.style,
    items: PropTypes.array,
    separatorColor: PropTypes.string,
    onItemPress: PropTypes.func
  };

  static defaultProps = {
    alwaysBounceVertical: false,
    rowHasChanged: (r1, r2) => r1 !== r2,
    separatorColor: Colors.separator
  };

  state = {};

  constructor(props) {
    super(props);
    const {items, rowHasChanged} = props;
    const ds = new ListView.DataSource({rowHasChanged});
    this.state = {
      dataSource: ds.cloneWithRows(items)
    };
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.items !== nextProps.items) {
      this.setState({dataSource: this.state.dataSource.cloneWithRows(nextProps.items)});
    }
  }

  renderHeader(header) {
    return header || <View />;
  }

  renderBody(body) {
    const {bodyTextStyle} = this.props;
    if (!body || typeof body === 'string') {
      return (
        <Text style={[styles.body, bodyTextStyle]}>{body || ''}</Text>
      );
    }
    return body;
  }

  renderFooter(footer) {
    if (footer) {
      if (typeof footer === 'string') {
        return (
          <Text>{footer}</Text>
        );
      }
      return footer;
    }
    return (
      <Icon color="#000"
            name="angle-right"
            size={18}
      />
    );
  }

  renderRow(row, sectionID, rowID, highlightRow) {
    const {header, body, footer} = row;
    const {onItemPress, cellStyle} = this.props;
    return (
      <Button Comp={TouchableHighlight}
              containerStyle={[styles.row, cellStyle]}
              key={rowID}
              onPress={() => onItemPress && onItemPress(row, sectionID, rowID)}
              type="link"
              underlayColor={Colors.underlay}
      >
        {this.renderHeader(header)}
        {this.renderBody(body)}
        {this.renderFooter(footer)}
      </Button>
    );
  }

  renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
    const {separatorColor, items} = this.props;
    if (rowID === `${items.length - 1}`) {
      return null;
    }
    const style = {
      backgroundColor: adjacentRowHighlighted ? 'transparent' : separatorColor
    };
    return (
      <View key={`${sectionID}-${rowID}`}
            style={[styles.separator, style]}
      />
    );
  }

  render() {
    const {style, separatorColor, ...other} = this.props;
    return (
      <View style={[styles.container, {borderColor: separatorColor}, style]}>
        <ListView {...other}
          dataSource={this.state.dataSource}
          renderRow={this.renderRow}
          renderSeparator={this.renderSeparator}
        />
      </View>
    );
  }

}

export default List;
<commit_msg>footerTextStyle<commit_after>import React, { PropTypes } from 'react';
import { ListView, StyleSheet, Text, TouchableHighlight, View } from 'react-native';
import AbstractComponent from './AbstractComponent';
import Icon from './Icon';
import Button from './Button';
import { Colors } from './styles';

const styles = StyleSheet.create({
  container: {
    borderBottomWidth: 1,
    borderTopWidth: 1
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    height: 45,
    alignItems: 'center',
    marginLeft: 15,
    paddingRight: 15
  },
  header: {
    width: 30
  },
  body: {
    flex: 1
  },
  text: {
    color: '#000'
  },
  separator: {
    height: 1,
    marginLeft: 15
  }
});

/**
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/5/25
 */
class List extends AbstractComponent {

  static propTypes = {
    bodyTextStyle: Text.propTypes.style,
    cellStyle: View.propTypes.style,
    footerTextStyle: Text.propTypes.style,
    items: PropTypes.array,
    separatorColor: PropTypes.string,
    onItemPress: PropTypes.func
  };

  static defaultProps = {
    alwaysBounceVertical: false,
    rowHasChanged: (r1, r2) => r1 !== r2,
    separatorColor: Colors.separator,
    footerTextStyle: {
      color: '#b3b3b3'
    }
  };

  state = {};

  constructor(props) {
    super(props);
    const {items, rowHasChanged} = props;
    const ds = new ListView.DataSource({rowHasChanged});
    this.state = {
      dataSource: ds.cloneWithRows(items)
    };
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.items !== nextProps.items) {
      this.setState({dataSource: this.state.dataSource.cloneWithRows(nextProps.items)});
    }
  }

  renderHeader(header) {
    return header || <View />;
  }

  renderBody(body) {
    const {bodyTextStyle} = this.props;
    if (!body || typeof body === 'string') {
      return (
        <Text style={[styles.body, bodyTextStyle]}>{body || ''}</Text>
      );
    }
    return body;
  }

  renderFooter(footer) {
    if (footer) {
      if (typeof footer === 'string') {
        const {footerTextStyle} = this.props;
        return (
          <Text style={footerTextStyle}>{footer}</Text>
        );
      }
      return footer;
    }
    return (
      <Icon color="#000"
            name="angle-right"
            size={18}
      />
    );
  }

  renderRow(row, sectionID, rowID, highlightRow) {
    const {header, body, footer} = row;
    const {onItemPress, cellStyle} = this.props;
    return (
      <Button Comp={TouchableHighlight}
              containerStyle={[styles.row, cellStyle]}
              key={rowID}
              onPress={() => onItemPress && onItemPress(row, sectionID, rowID)}
              type="link"
              underlayColor={Colors.underlay}
      >
        {this.renderHeader(header)}
        {this.renderBody(body)}
        {this.renderFooter(footer)}
      </Button>
    );
  }

  renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
    const {separatorColor, items} = this.props;
    if (rowID === `${items.length - 1}`) {
      return null;
    }
    const style = {
      backgroundColor: adjacentRowHighlighted ? 'transparent' : separatorColor
    };
    return (
      <View key={`${sectionID}-${rowID}`}
            style={[styles.separator, style]}
      />
    );
  }

  render() {
    const {style, separatorColor, ...other} = this.props;
    return (
      <View style={[styles.container, {borderColor: separatorColor}, style]}>
        <ListView {...other}
                  dataSource={this.state.dataSource}
                  renderRow={this.renderRow}
                  renderSeparator={this.renderSeparator}
        />
      </View>
    );
  }

}

export default List;
<|endoftext|>


<commit_before>// test norm
var assert = require('assert'),
  error = require('../../../lib/util/error'),
  math = require('../../../index')();

describe('norm', function () {

  it('should return the absolute value of a boolean', function () {
    assert.equal(math.norm(true), 1);
    assert.equal(math.norm(true, 10), 1);
    assert.equal(math.norm(false), 0);
    assert.equal(math.norm(false, 10), 0);
  });

  it('should return the absolute value of a number', function () {
    assert.equal(math.norm(-4.2), 4.2);
    assert.equal(math.norm(-3.5), 3.5);
    assert.equal(math.norm(100), 100);
    assert.equal(math.norm(0), 0);
    assert.equal(math.norm(100, 10), 100);
  });

  it('should return the absolute value of a big number', function () {
    assert.deepEqual(math.norm(math.bignumber(-2.3)), math.bignumber(2.3));
    assert.deepEqual(math.norm(math.bignumber('5e500')), math.bignumber('5e500'));
    assert.deepEqual(math.norm(math.bignumber('-5e500')), math.bignumber('5e500'));
  });

  it('should return the norm of a complex number', function () {
    assert.equal(math.norm(math.complex(3, -4)), 5);
  });

  it('should return the norm of a vector', function () {
    // empty vector
    assert.equal(math.norm([]), 0.0);
    assert.equal(math.norm(math.matrix([])), 0.0);
    // p = Infinity
    assert.equal(math.norm([1, 2, -3], Number.POSITIVE_INFINITY), 3);
    assert.equal(math.norm(math.matrix([1, 2, -3]), Number.POSITIVE_INFINITY), 3);
    assert.equal(math.norm([1, 2, -3], 'inf'), 3);
    assert.equal(math.norm(math.matrix([1, 2, -3]), 'inf'), 3);
    // p = -Infinity
    assert.equal(math.norm([1, 2, -3], Number.NEGATIVE_INFINITY), 1);
    assert.equal(math.norm(math.matrix([1, 2, -3]), Number.NEGATIVE_INFINITY), 1);
    assert.equal(math.norm([1, 2, -3], '-inf'), 1);
    assert.equal(math.norm(math.matrix([1, 2, -3]), '-inf'), 1);
    // p == 1
    assert.equal(math.norm([-3, -4], 1), 7.0);
    assert.equal(math.norm(math.matrix([-3, -4]), 1), 7.0);
    // p - positive
    assert.equal(math.norm([3, 4], 2), 5.0);
    assert.equal(math.norm(math.matrix([3, 4]), 2), 5.0);
    // p - negative
    assert.equal(math.norm([3, 4], -2), 2.4);
    assert.equal(math.norm(math.matrix([3, 4]), -2), 2.4);
    // missing p (defaults to 2)
    assert.equal(math.norm([3, 4]), 5.0);
    assert.equal(math.norm(math.matrix([3, 4])), 5.0);
    // p == 'fro'
    assert.equal(math.norm([3, 4], 'fro'), 5.0);
    assert.equal(math.norm(math.matrix([3, 4]), 'fro'), 5.0);
  });

  it('should return the norm of a matrix', function () {
    // p = 1
    assert.equal(math.norm([[1, 2], [3, 4]], 1), 6);
    assert.equal(math.norm(math.matrix([[1, 2], [3, 4]]), 1), 6);
    // p = Infinity
    assert.equal(math.norm([[1, 2], [3, 4]], Number.POSITIVE_INFINITY), 7);
    assert.equal(math.norm(math.matrix([[1, 2], [3, 4]]), Number.POSITIVE_INFINITY), 7);
    assert.equal(math.norm([[1, 2], [3, 4]], 'inf'), 7);
    assert.equal(math.norm(math.matrix([[1, 2], [3, 4]]), 'inf'), 7);
    // p = 'fro'
    assert.equal(math.norm([[1, 2], [-3, -4]], 'fro'), math.sqrt(30));
    assert.equal(math.norm(math.matrix([[1, 2], [-3, -4]]), 'fro'), math.sqrt(30));
	// p - not implemented yet!
	assert.throws(function() {
	  math.norm(math.norm([[1, 2], [3, 4]], 2), 6);
	});
  });

  it('should throw an error in case of invalid number of arguments', function() {
    assert.throws(function () {math.norm()}, error.ArgumentsError);
    assert.throws(function () {math.norm(1, 2, 3)}, error.ArgumentsError);
  });

  it('should throw an error with a string', function () {
    assert.throws(function () {
      math.norm('a string');
    });
  });
});
<commit_msg>fixed build errors<commit_after>// test norm
var assert = require('assert'),
  error = require('../../../lib/error'),
  math = require('../../../index')();

describe('norm', function () {

  it('should return the absolute value of a boolean', function () {
    assert.equal(math.norm(true), 1);
    assert.equal(math.norm(true, 10), 1);
    assert.equal(math.norm(false), 0);
    assert.equal(math.norm(false, 10), 0);
  });

  it('should return the absolute value of a number', function () {
    assert.equal(math.norm(-4.2), 4.2);
    assert.equal(math.norm(-3.5), 3.5);
    assert.equal(math.norm(100), 100);
    assert.equal(math.norm(0), 0);
    assert.equal(math.norm(100, 10), 100);
  });

  it('should return the absolute value of a big number', function () {
    assert.deepEqual(math.norm(math.bignumber(-2.3)), math.bignumber(2.3));
    assert.deepEqual(math.norm(math.bignumber('5e500')), math.bignumber('5e500'));
    assert.deepEqual(math.norm(math.bignumber('-5e500')), math.bignumber('5e500'));
  });

  it('should return the norm of a complex number', function () {
    assert.equal(math.norm(math.complex(3, -4)), 5);
  });

  it('should return the norm of a vector', function () {
    // empty vector
    assert.equal(math.norm([]), 0.0);
    assert.equal(math.norm(math.matrix([])), 0.0);
    // p = Infinity
    assert.equal(math.norm([1, 2, -3], Number.POSITIVE_INFINITY), 3);
    assert.equal(math.norm(math.matrix([1, 2, -3]), Number.POSITIVE_INFINITY), 3);
    assert.equal(math.norm([1, 2, -3], 'inf'), 3);
    assert.equal(math.norm(math.matrix([1, 2, -3]), 'inf'), 3);
    // p = -Infinity
    assert.equal(math.norm([1, 2, -3], Number.NEGATIVE_INFINITY), 1);
    assert.equal(math.norm(math.matrix([1, 2, -3]), Number.NEGATIVE_INFINITY), 1);
    assert.equal(math.norm([1, 2, -3], '-inf'), 1);
    assert.equal(math.norm(math.matrix([1, 2, -3]), '-inf'), 1);
    // p == 1
    assert.equal(math.norm([-3, -4], 1), 7.0);
    assert.equal(math.norm(math.matrix([-3, -4]), 1), 7.0);
    // p - positive
    assert.equal(math.norm([3, 4], 2), 5.0);
    assert.equal(math.norm(math.matrix([3, 4]), 2), 5.0);
    // p - negative
    assert.equal(math.norm([3, 4], -2), 2.4);
    assert.equal(math.norm(math.matrix([3, 4]), -2), 2.4);
    // missing p (defaults to 2)
    assert.equal(math.norm([3, 4]), 5.0);
    assert.equal(math.norm(math.matrix([3, 4])), 5.0);
    // p == 'fro'
    assert.equal(math.norm([3, 4], 'fro'), 5.0);
    assert.equal(math.norm(math.matrix([3, 4]), 'fro'), 5.0);
  });

  it('should return the norm of a matrix', function () {
    // p = 1
    assert.equal(math.norm([[1, 2], [3, 4]], 1), 6);
    assert.equal(math.norm(math.matrix([[1, 2], [3, 4]]), 1), 6);
    // p = Infinity
    assert.equal(math.norm([[1, 2], [3, 4]], Number.POSITIVE_INFINITY), 7);
    assert.equal(math.norm(math.matrix([[1, 2], [3, 4]]), Number.POSITIVE_INFINITY), 7);
    assert.equal(math.norm([[1, 2], [3, 4]], 'inf'), 7);
    assert.equal(math.norm(math.matrix([[1, 2], [3, 4]]), 'inf'), 7);
    // p = 'fro'
    assert.equal(math.norm([[1, 2], [-3, -4]], 'fro'), math.sqrt(30));
    assert.equal(math.norm(math.matrix([[1, 2], [-3, -4]]), 'fro'), math.sqrt(30));
	// p - not implemented yet!
	assert.throws(function() {
	  math.norm(math.norm([[1, 2], [3, 4]], 2), 6);
	});
  });

  it('should throw an error in case of invalid number of arguments', function() {
    assert.throws(function () {math.norm()}, error.ArgumentsError);
    assert.throws(function () {math.norm(1, 2, 3)}, error.ArgumentsError);
  });

  it('should throw an error with a string', function () {
    assert.throws(function () {
      math.norm('a string');
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

module.exports = function (grunt) {
    [
        "node",
        "phantom",
        "rhino",
        "wscript"
    ].forEach(function (runtime) {
        var taskName = "exec:test" + runtime.charAt(0).toUpperCase() + runtime.substr(1) + "Verbose";
        grunt.registerTask(runtime, function () {
            var parameter;
            if (0 === arguments.length) {
                parameter = "";
            } else {
                parameter = ":" + [].slice.call(arguments, 0).join(":");
            }
            grunt.task.run(taskName + parameter);
        });
    });
};
<commit_msg>Nashorn shortcut (#220)<commit_after>"use strict";

module.exports = function (grunt) {
    [
        "node",
        "phantom",
        "rhino",
        "nashorn",
        "wscript"
    ].forEach(function (runtime) {
        var taskName = "exec:test" + runtime.charAt(0).toUpperCase() + runtime.substr(1) + "Verbose";
        grunt.registerTask(runtime, function () {
            var parameter;
            if (0 === arguments.length) {
                parameter = "";
            } else {
                parameter = ":" + [].slice.call(arguments, 0).join(":");
            }
            grunt.task.run(taskName + parameter);
        });
    });
};
<|endoftext|>


<commit_before>// [START rtdb_presence]
// Fetch the current user's ID from Firebase Authentication.
const uid = firebase.auth().currentUser.uid;

// Create a reference to this user's specific status node.
// This is where we will store data about being online/offline.
const userStatusDatabaseRef = firebase.database().ref(`/status/${uid}`);

// We'll create two constants which we will write to
// the Realtime database when this device is offline
// or online.
const isOffline = {
    state: "offline",
    last_seen: firebase.database.ServerValue.TIMESTAMP,
};

const isOnline = {
    state: "offline",
    last_seen: firebase.database.ServerValue.TIMESTAMP,
};

// Create a reference to the special ".info/connected" path in
// Realtime Database. This path returns `true` when connected
// and `false` when disconnected.
firebase.database().ref(".info/connected").on("value", function (snapshot) {
    // If we're not currently connected, don't do anything.
    if (snapshot.val() == false) {
        return;
    };

    // If we are currently connected, then use the 'onDisconnect()'
    // method to add a set which will only trigger once this
    // client has disconnected by closing the app,
    // losing internet, or any other means.
    userStatusDatabaseRef.onDisconnect().set(isOffline).then(function () {
        // The promise returned from .onDisconnect().set() will
        // resolve as soon as the server acknowledges the onDisconnect()
        // request, NOT once we've actually disconnected:
        // https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect

        // We can now safely set ourselves as "online" knowing that the
        // server will mark us as offline once we lose connection.
        userStatusDatabaseRef.set(isOnline);
    });
});
// [END rtdb_presence]

// [START rtdb_and_local_fs_presence]
[START_EXCLUDE]
[END_EXCLUDE]
const userStatusDatabaseRef = firebase.database().ref(`/status/${uid}`);
const userStatusFirestoreRef = firebase.firestore().doc(`/status/${uid}`);

firebase.database().ref(".info/connected").on("value", function (snapshot) {
    if (snapshot.val() == false) {
        return;
    };

    userStatusRef.onDisconnect().set(isOffline).then(function () {
        userStatusRef.set(isOnline);
    });
});
// [END rtdb_and_local_fs_presence]<commit_msg>Adds rtdb_and_local_fs_presence sample<commit_after>// [START rtdb_presence]
// Fetch the current user's ID from Firebase Authentication.
const uid = firebase.auth().currentUser.uid;

// Create a reference to this user's specific status node.
// This is where we will store data about being online/offline.
const userStatusDatabaseRef = firebase.database().ref(`/status/${uid}`);

// We'll create two constants which we will write to
// the Realtime database when this device is offline
// or online.
const isOffline = {
    state: "offline",
    last_seen: firebase.database.ServerValue.TIMESTAMP,
};

const isOnline = {
    state: "offline",
    last_seen: firebase.database.ServerValue.TIMESTAMP,
};

// Create a reference to the special ".info/connected" path in
// Realtime Database. This path returns `true` when connected
// and `false` when disconnected.
firebase.database().ref(".info/connected").on("value", function (snapshot) {
    // If we're not currently connected, don't do anything.
    if (snapshot.val() == false) {
        return;
    };

    // If we are currently connected, then use the 'onDisconnect()'
    // method to add a set which will only trigger once this
    // client has disconnected by closing the app,
    // losing internet, or any other means.
    userStatusDatabaseRef.onDisconnect().set(isOffline).then(function () {
        // The promise returned from .onDisconnect().set() will
        // resolve as soon as the server acknowledges the onDisconnect()
        // request, NOT once we've actually disconnected:
        // https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect

        // We can now safely set ourselves as "online" knowing that the
        // server will mark us as offline once we lose connection.
        userStatusDatabaseRef.set(isOnline);
    });
});
// [END rtdb_presence]

// [START rtdb_and_local_fs_presence]
[START_EXCLUDE]
[END_EXCLUDE]
const userStatusDatabaseRef = firebase.database().ref(`/status/${uid}`);
const userStatusFirestoreRef = firebase.firestore().doc(`/status/${uid}`);

firebase.database().ref(".info/connected").on("value", function (snapshot) {
    if (snapshot.val() == false) {
        return;
    };

    userStatusRef.onDisconnect().set(isOffline).then(function () {
        userStatusRef.set(isOnline);
    });
});
// [END rtdb_and_local_fs_presence]
<|endoftext|>


<commit_before>jQuery.fn.definePlugin('Slider', function ($) {
	'use strict';

	var names = {
		sliderClass: 'uilib-slider',
		pinClass: 'uilib-slider-pin',
		disabledClass: 'disabled',
		textClass:'uilib-text'
	};

	return {
		init: function(){
			this.markup();
			this.bindEvents();
			this.options.create.call(this);
			this.setValue(this.options.value);
		},
		getDefaults: function(){
			return {
				minValue: 0,
				maxValue: 100,
				value: 0,
				width: 80,
				preLabel: '',
				postLabel: '',
				className: 'default-uilib-slider-ui',
				toolTip: false,
				supportClick: true,
				slide: function () {},
				create: function () {}
			};
		},
		markup: function () {
			var leftOffset = this.$el.css('left');
			var style = {
				width : this.options.width
			};

			if(!this.$el.hasClass(names.sliderClass)){
				this.$el.addClass(names.sliderClass);
			}

			if(this.options.preLabel){
				this.$el.prepend('' + this.options.preLabel + '');
				style.left = 14;
			}

			this.$pin = $('
');
			this.$el.append(this.$pin);

			if(this.options.postLabel){
				this.$el.append('' + this.options.postLabel + '');
			}

			this.$el.addClass(names.sliderClass).css(style).addClass(this.options.className);

			this.$pin.addClass(names.pinClass);
			this.$pin.width(19);

			if(this.options.toolTip){
				this.$toolTip = $(_toolTipHtml());
				this.$pin.append(this.$toolTip.hide());
			}
		},
		getXFromEvent: function(event){
			var x = event.hasOwnProperty('offsetX') ?
					event.offsetX :
					event.clientX - event.target.getBoundingClientRect().left;
			return x / this.$el.width();
		},
		bindEvents: function () {
			var $body = $(window);
			var slider = this;
			if (slider.options.supportClick){
				this.$el.on('click', function(evt){
					if(evt.target === slider.$el[0]){
						var x = slider.getXFromEvent(evt);
						slider.setValue(slider.transform(x));
						slider.triggerChangeEvent(slider.getValue());
					}
				});
			}
			this.$pin.on('mousedown', function (evt) {
                if(slider.$toolTip && !slider.$toolTip.is(":visible")){
                    slider.$toolTip.show();
                }
				slider.currentPos = slider.$pin.position().left;
				slider.startDragPos = evt.pageX;
				slider.disableTextSelection(evt);
				function mousemove_handler(evt) {
					slider.setPosition(evt);
				}
				function mouseup_handler(evt) {
                    if(slider.$toolTip){
                        slider.$toolTip.hide();
                    }
					slider.enableTextSelection();
					$body.off('mousemove', mousemove_handler);
					$body.off('mouseup', mouseup_handler);
					slider.triggerChangeEvent(slider.getValue());
				}
				$body.on('mousemove', mousemove_handler);
				$body.on('mouseup', mouseup_handler);
			});
		},
		getValue: function () {
			return this.transform(this.options.value);
		},
		setValue: function (valueInRange) {
			var val;
			this.options.value = this.valueInRangeToInnerRange(valueInRange);
			if (this.options.value !== this.last_value) {
				this.last_value = this.options.value;
				val = this.getValue();
				this.$el.trigger('slide', val);
				if(this.options.toolTip){
					this.$toolTip.find('.'+names.textClass).text(Math.round(val));
				}
				this.options.slide.call(this, val);
			}
			return this.update();
		},
		transform: function (valueInRange) {
			return this.options.minValue + valueInRange * (this.options.maxValue - this.options.minValue);
		},
		valueInRangeToInnerRange: function (value) {
			value = value < this.options.minValue ? this.options.minValue : value;
			value = value > this.options.maxValue ? this.options.maxValue : value;
			return (value - this.options.minValue) / (this.options.maxValue - this.options.minValue);
		},
		disableTextSelection: function (evt) {
			document.body.focus();
			//prevent text selection in IE
			document.onselectstart = function () { return false; };
			//evt.target.ondragstart = function() { return false; };
		},
		enableTextSelection: function () {
			document.onselectstart = null;
		},
		setPosition: function (evt) {
			if (this.isDisabled()) { return; }
			var x = evt.pageX - this.startDragPos;
			var pos = this.currentPos + x;
			var width = this.$el.width() - this.$pin.width();
			if (pos < 0) { pos = 0; }
			if (pos > width) { pos = width; }
			this.options.value = this.transform(pos / width);
			this.setValue(this.options.value);
			this.startDragPos = evt.pageX;
			this.currentPos = pos;
		},
		update: function () {
			this.$pin.css({
				left : this.options.value * (this.$el.width() - this.$pin.width())
			});
			return this;
		},
		disable: function () {
			this.$el.addClass(names.disabledClass);
		},
		enable: function () {
			this.$el.removeClass(names.disabledClass);
		},
		isDisabled: function () {
			return this.$el.hasClass(names.disabledClass);
		}
	};

	function _toolTipHtml() {
        return '
' +
            '

' +
            '

' +
            '
';
    }

});<commit_msg>Turns out event does have undefined offsetX.<commit_after>jQuery.fn.definePlugin('Slider', function ($) {
	'use strict';

	var names = {
		sliderClass: 'uilib-slider',
		pinClass: 'uilib-slider-pin',
		disabledClass: 'disabled',
		textClass:'uilib-text'
	};

	return {
		init: function(){
			this.markup();
			this.bindEvents();
			this.options.create.call(this);
			this.setValue(this.options.value);
		},
		getDefaults: function(){
			return {
				minValue: 0,
				maxValue: 100,
				value: 0,
				width: 80,
				preLabel: '',
				postLabel: '',
				className: 'default-uilib-slider-ui',
				toolTip: false,
				supportClick: true,
				slide: function () {},
				create: function () {}
			};
		},
		markup: function () {
			var leftOffset = this.$el.css('left');
			var style = {
				width : this.options.width
			};

			if(!this.$el.hasClass(names.sliderClass)){
				this.$el.addClass(names.sliderClass);
			}

			if(this.options.preLabel){
				this.$el.prepend('' + this.options.preLabel + '');
				style.left = 14;
			}

			this.$pin = $('
');
			this.$el.append(this.$pin);

			if(this.options.postLabel){
				this.$el.append('' + this.options.postLabel + '');
			}

			this.$el.addClass(names.sliderClass).css(style).addClass(this.options.className);

			this.$pin.addClass(names.pinClass);
			this.$pin.width(19);

			if(this.options.toolTip){
				this.$toolTip = $(_toolTipHtml());
				this.$pin.append(this.$toolTip.hide());
			}
		},
		getXFromEvent: function(event){
			var x = event.offsetX !== undefined
					? event.offsetX
					: event.clientX - event.target.getBoundingClientRect().left;
			return x / this.$el.width();
		},
		bindEvents: function () {
			var $body = $(window);
			var slider = this;
			if (slider.options.supportClick){
				this.$el.on('click', function(evt){
					if(evt.target === slider.$el[0]){
						var x = slider.getXFromEvent(evt);
						slider.setValue(slider.transform(x));
						slider.triggerChangeEvent(slider.getValue());
					}
				});
			}
			this.$pin.on('mousedown', function (evt) {
                if(slider.$toolTip && !slider.$toolTip.is(":visible")){
                    slider.$toolTip.show();
                }
				slider.currentPos = slider.$pin.position().left;
				slider.startDragPos = evt.pageX;
				slider.disableTextSelection(evt);
				function mousemove_handler(evt) {
					slider.setPosition(evt);
				}
				function mouseup_handler(evt) {
                    if(slider.$toolTip){
                        slider.$toolTip.hide();
                    }
					slider.enableTextSelection();
					$body.off('mousemove', mousemove_handler);
					$body.off('mouseup', mouseup_handler);
					slider.triggerChangeEvent(slider.getValue());
				}
				$body.on('mousemove', mousemove_handler);
				$body.on('mouseup', mouseup_handler);
			});
		},
		getValue: function () {
			return this.transform(this.options.value);
		},
		setValue: function (valueInRange) {
			var val;
			this.options.value = this.valueInRangeToInnerRange(valueInRange);
			if (this.options.value !== this.last_value) {
				this.last_value = this.options.value;
				val = this.getValue();
				this.$el.trigger('slide', val);
				if(this.options.toolTip){
					this.$toolTip.find('.'+names.textClass).text(Math.round(val));
				}
				this.options.slide.call(this, val);
			}
			return this.update();
		},
		transform: function (valueInRange) {
			return this.options.minValue + valueInRange * (this.options.maxValue - this.options.minValue);
		},
		valueInRangeToInnerRange: function (value) {
			value = value < this.options.minValue ? this.options.minValue : value;
			value = value > this.options.maxValue ? this.options.maxValue : value;
			return (value - this.options.minValue) / (this.options.maxValue - this.options.minValue);
		},
		disableTextSelection: function (evt) {
			document.body.focus();
			//prevent text selection in IE
			document.onselectstart = function () { return false; };
			//evt.target.ondragstart = function() { return false; };
		},
		enableTextSelection: function () {
			document.onselectstart = null;
		},
		setPosition: function (evt) {
			if (this.isDisabled()) { return; }
			var x = evt.pageX - this.startDragPos;
			var pos = this.currentPos + x;
			var width = this.$el.width() - this.$pin.width();
			if (pos < 0) { pos = 0; }
			if (pos > width) { pos = width; }
			this.options.value = this.transform(pos / width);
			this.setValue(this.options.value);
			this.startDragPos = evt.pageX;
			this.currentPos = pos;
		},
		update: function () {
			this.$pin.css({
				left : this.options.value * (this.$el.width() - this.$pin.width())
			});
			return this;
		},
		disable: function () {
			this.$el.addClass(names.disabledClass);
		},
		enable: function () {
			this.$el.removeClass(names.disabledClass);
		},
		isDisabled: function () {
			return this.$el.hasClass(names.disabledClass);
		}
	};

	function _toolTipHtml() {
        return '
' +
            '

' +
            '

' +
            '
';
    }

});<|endoftext|>


<commit_before>/**
 * @file Middleware
 * @author Jim Bulkowski <jim.b@paperelectron.com>
 * @project Pomegranate
 * @license MIT {@link http://opensource.org/licenses/MIT}
 */

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var responseTime = require('response-time');
var serveStatic = require('serve-static');
var compress = require('compression');
var morgan = require('morgan');
var logCommon = morgan.compile(morgan.common);
var bodyParser = require('body-parser');
var session = require("express-session");
var RedisStore = require('connect-redis')(session);
var favicon = require('serve-favicon');

/**
 * Manages middlewares.
 * @module Middleware
 */

module.exports = function(logger, redis){

  return {
    Session: function(opts){
      if(!opts){
        logger.log('ExpressConfig: Session Middleware not loaded.')
        return false
      }

      var using = 'MemoryStore';
      var baseTTL = 60 * 60 * 24 * 7;
      var options = {
        name: opts.name || 'pomegranate.sid',
        secret: opts.secret || false,
        resave: opts.resave|| false,
        rolling: opts.rolling || false,
        saveUninitialized: opts.saveUninitialized || false,
        cookie: {maxAge: opts.ttl * 1000 ||  baseTTL * 1000}
      }

      if(!options.secret){
        logger.log('ExpressConfig: Session Middleware not loaded, session.secret is required')
        return false
      }

      if(opts.secure){
        options.secure = true
      }

      if(redis){
        using = 'Redis';
        options.store = new RedisStore({
          client: redis,
          prefix: 'silken_sess:',
          ttl: opts.ttl || baseTTL
        })
      }
      logger.log('ExpressConfig: Session Middleware loaded.');
      logger.log('ExpressConfig: Session Middleware using ' + using + ' storage engine.')
      return session(options)
    },

    Static: function (opts){
      try {
        var staticFileDir = fs.statSync(opts)
      }
      catch (e){
        logger.log('ExpressConfig: Static Middleware not loaded, path does not exist, or is not a directory.')
        return false
      }
      if(staticFileDir.isDirectory()) {
        logger.log('ExpressConfig: Static Middleware loaded.');
        logger.log('ExpressConfig: Serving static files from ' + opts);
        return serveStatic(opts)
      }
      logger.log('ExpressConfig: Static Middleware not loaded, path does not exist, or is not a directory.')
      return false
    },

    Favicon: function(options){
      var faviconIco;
      var iconPath = options + '/favicon.ico';
      try {
        faviconIco = fs.statSync(iconPath)
      }
      catch (e){
        logger.log('ExpressConfig: Favicon Middleware using default.');
      }

      logger.log('ExpressConfig: Favicon Middleware loaded.');
      var path = (faviconIco && faviconIco.isFile()) ? iconPath : __dirname + '/../../assets/favicon-32x32.png';
      return favicon(path)
    },

    Compression: function(options){
      logger.log('ExpressConfig: Compression Middleware loaded.')
      return compress()
    },

    ResponseTime: function(options){
      logger.log('ExpressConfig: ResponseTime Middleware loaded.')
      return responseTime()
    },

    Logger: function(options) {
      logger.log('ExpressConfig: Logging Middleware loaded.')
      return morgan(function(t, req, res) {

        var resObj = {
          'remote-addr': t['remote-addr'](req, res),
          'remote-user': t['remote-user'](req, res),
          'date': t['date'](req, res),
          'method': t['method'](req, res),
          'url': t['url'](req, res),
          'status': t['status'](req, res),
          'content-length': res['content-length'],
          'response-time': t['response-time'](req, res) + 'ms'
        };
        logger.requestHandled(logCommon(morgan, req, res), resObj);
      })

    },

    BodyParser: function(options) {
      logger.log('ExpressConfig: BodyParser Middleware loaded.')
      return bodyParser.json();
    },

    BodyParserURL: function(options) {
      logger.log('ExpressConfig: BodyParser URL encoded Middleware loaded.')
      return bodyParser.urlencoded();
    }
  }
}<commit_msg>Set extended = true in url encoded body parser, removes deprecation warning<commit_after>/**
 * @file Middleware
 * @author Jim Bulkowski <jim.b@paperelectron.com>
 * @project Pomegranate
 * @license MIT {@link http://opensource.org/licenses/MIT}
 */

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var responseTime = require('response-time');
var serveStatic = require('serve-static');
var compress = require('compression');
var morgan = require('morgan');
var logCommon = morgan.compile(morgan.common);
var bodyParser = require('body-parser');
var session = require("express-session");
var RedisStore = require('connect-redis')(session);
var favicon = require('serve-favicon');

/**
 * Manages middlewares.
 * @module Middleware
 */

module.exports = function(logger, redis){

  return {
    Session: function(opts){
      if(!opts){
        logger.log('ExpressConfig: Session Middleware not loaded.')
        return false
      }

      var using = 'MemoryStore';
      var baseTTL = 60 * 60 * 24 * 7;
      var options = {
        name: opts.name || 'pomegranate.sid',
        secret: opts.secret || false,
        resave: opts.resave|| false,
        rolling: opts.rolling || false,
        saveUninitialized: opts.saveUninitialized || false,
        cookie: {maxAge: opts.ttl * 1000 ||  baseTTL * 1000}
      }

      if(!options.secret){
        logger.log('ExpressConfig: Session Middleware not loaded, session.secret is required')
        return false
      }

      if(opts.secure){
        options.secure = true
      }

      if(redis){
        using = 'Redis';
        options.store = new RedisStore({
          client: redis,
          prefix: 'silken_sess:',
          ttl: opts.ttl || baseTTL
        })
      }
      logger.log('ExpressConfig: Session Middleware loaded.');
      logger.log('ExpressConfig: Session Middleware using ' + using + ' storage engine.')
      return session(options)
    },

    Static: function (opts){
      try {
        var staticFileDir = fs.statSync(opts)
      }
      catch (e){
        logger.log('ExpressConfig: Static Middleware not loaded, path does not exist, or is not a directory.')
        return false
      }
      if(staticFileDir.isDirectory()) {
        logger.log('ExpressConfig: Static Middleware loaded.');
        logger.log('ExpressConfig: Serving static files from ' + opts);
        return serveStatic(opts)
      }
      logger.log('ExpressConfig: Static Middleware not loaded, path does not exist, or is not a directory.')
      return false
    },

    Favicon: function(options){
      var faviconIco;
      var iconPath = options + '/favicon.ico';
      try {
        faviconIco = fs.statSync(iconPath)
      }
      catch (e){
        logger.log('ExpressConfig: Favicon Middleware using default.');
      }

      logger.log('ExpressConfig: Favicon Middleware loaded.');
      var path = (faviconIco && faviconIco.isFile()) ? iconPath : __dirname + '/../../assets/favicon-32x32.png';
      return favicon(path)
    },

    Compression: function(options){
      logger.log('ExpressConfig: Compression Middleware loaded.')
      return compress()
    },

    ResponseTime: function(options){
      logger.log('ExpressConfig: ResponseTime Middleware loaded.')
      return responseTime()
    },

    Logger: function(options) {
      logger.log('ExpressConfig: Logging Middleware loaded.')
      return morgan(function(t, req, res) {

        var resObj = {
          'remote-addr': t['remote-addr'](req, res),
          'remote-user': t['remote-user'](req, res),
          'date': t['date'](req, res),
          'method': t['method'](req, res),
          'url': t['url'](req, res),
          'status': t['status'](req, res),
          'content-length': res['content-length'],
          'response-time': t['response-time'](req, res) + 'ms'
        };
        logger.requestHandled(logCommon(morgan, req, res), resObj);
      })

    },

    BodyParser: function(options) {
      logger.log('ExpressConfig: BodyParser Middleware loaded.')
      return bodyParser.json();
    },

    BodyParserURL: function(options) {
      logger.log('ExpressConfig: BodyParser URL encoded Middleware loaded.')
      return bodyParser.urlencoded({extended: true});
    }
  }
}<|endoftext|>


<commit_before>function Executor (exec) {
    this.execImpl = exec || require('child_process').exec;
    this.stopped = false;
}

Executor.prototype.exec = function(script) {
    if (this.stopped) {
        return;
    }

    this.stopped = false;

    var self = this;
    this.execImpl(script, function(error, stdout, stderr) {
        self.exec(script);
    });
};

Executor.prototype.stop = function() {
    this.stopped = true;
}

module.exports = Executor;

<commit_msg>On error, emit an error event with stdout/err<commit_after>var util = require("util");
var events = require("events");

function Executor (exec) {
    this.execImpl = exec || require('child_process').exec;
    this.stopped = false;
}

util.inherits(Executor, events.EventEmitter);

Executor.prototype.exec = function(script) {
    if (this.stopped) {
        return;
    }

    this.stopped = false;

    var self = this;
    this.execImpl(script, function(error, stdout, stderr) {
        if (error !== null) {
            self.emit('error', stdout, stderr);
            console.log(stdout, stderr);
        }
        self.exec(script);
    });
};

Executor.prototype.stop = function() {
    this.stopped = true;
}

module.exports = Executor;

<|endoftext|>


<commit_before>var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var LocationSchema = new Schema({
	name: String,
	city: String,
	address: String,
	img: String,
	description: String,
	email: String,
	datatill_group_id: Number,
	bank_account: Number,
	bank_code: String,
	community_manager_name: String,
	community_manager_email: String,
	community_manager_tel: String,
	mail_template: String,
	xero_paypal_id: String,
	xero_creditcard_id: String,
	xero_eft_id: String,
	clay_id: String,
	nas_ip: String,
	_deleted: { type: Boolean, default: false, index: true }
});

LocationSchema.set("_perms", {
	admin: "crud",
	user: "r",
	all: "r"
});

module.exports = mongoose.model("Location", LocationSchema);
<commit_msg>Save xero_tax_type per location<commit_after>var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var LocationSchema = new Schema({
	name: String,
	city: String,
	address: String,
	img: String,
	description: String,
	email: String,
	datatill_group_id: Number,
	bank_account: Number,
	bank_code: String,
	community_manager_name: String,
	community_manager_email: String,
	community_manager_tel: String,
	mail_template: String,
	xero_paypal_id: String,
	xero_creditcard_id: String,
	xero_eft_id: String,
	xero_tax_type: String,
	clay_id: String,
	nas_ip: String,
	_deleted: { type: Boolean, default: false, index: true }
});

LocationSchema.set("_perms", {
	admin: "crud",
	user: "r",
	all: "r"
});

module.exports = mongoose.model("Location", LocationSchema);
<|endoftext|>


<commit_before>import Path from './path.js';

// innerHandler (character, index, string) {
//     if (string[index-1] === '\\') return;
//     if (character === '"') return '\\"';
//     if (character === '\t') return '\\t';
//     if (character === '\r') return '\\r';
//     if (character === '\n') return '\\n';
//     if (character === '\b') return '\\b';
//     if (character === '\'') return '\\\'';
// },
//
// updateString (value, index, string) {
//     return string.slice(0, index) + value + string.slice(index+1);
// },
//
// updateIndex (value, index) {
//     return index + value.length-1;
// },
//
// template (data) {
//
//     var first = data.indexOf('`');
//     var second = data.indexOf('`', first+1);
//
//     if (first === -1 || second === -1) return data;
//
//     var value;
//     var ends = 0;
//     var starts = 0;
//     var string = data;
//     var isInner = false;
//
//     for (var index = 0; index < string.length; index++) {
//         var character = string[index];
//
//         if (character === '`' && string[index-1] !== '\\') {
//
//             if (isInner) {
//                 ends++;
//                 value = '\'';
//                 isInner = false;
//                 string = this.updateString(value, index, string);
//                 index = this.updateIndex(value, index);
//             } else {
//                 starts++;
//                 value = '\'';
//                 isInner = true;
//                 string = this.updateString(value, index, string);
//                 index = this.updateIndex(value, index);
//             }
//
//         } else if (isInner) {
//             value = this.innerHandler(character, index, string);
//
//             if (value) {
//                 string = this.updateString(value, index, string);
//                 index = this.updateIndex(value, index);
//             }
//
//         }
//
//     }
//
//     string = string.replace(/\${(.*?)}/g, '\'+$1+\'');
//
//     if (starts === ends) {
//         return string;
//     } else {
//         throw new Error('import transformer missing backtick');
//     }
//
// },

const MODULES = {};

// https://regexr.com/4uq8k
const S_EXPORT = '^export\\b(?:\\s*(default)\\s*)?(?:\\s*(var|let|const|function|class)\\s*)?(?:\\s*(\\w+)\\s*)?';

// https://regexr.com/4uq22
const S_IMPORT = `
    import
    (?:
        (?:
            \\s+(\\w+)(?:\\s+|\\s*,\\s*)
        )
        ?
        (?:
            (?:\\s+(\\*\\s+as\\s+\\w+)\\s+)
            |
            (?:
                \\s*{\\s*
                (
                    (?:
                        (?:
                            (?:\\w+)
                            |
                            (?:\\w+\\s+as\\s+\\w+)
                        )
                        \\s*,?\\s*
                    )
                    *
                )
                \\s*}\\s*
            )
        )
        ?
        from
    )
    ?
    \\s*
    (?:"|')
    (.*?)
    (?:'|")
    (?:\\s*;)?
`.replace(/\s+/g, '');

const R_IMPORT = new RegExp(S_IMPORT);
const R_IMPORTS = new RegExp(S_IMPORT, 'g');
const R_EXPORT = new RegExp(S_EXPORT);
const R_EXPORTS = new RegExp(S_EXPORT, 'gm');
const R_TEMPLATES = /[^\\]`(.|[\r\n])*?[^\\]`/g;

const transform = function (code, url) {

    let before = `window.Oxe.loader.data["${url}"] = Promise.all([\n`;
    let after = ']).then(function ($MODULES) {\n';

    const templateMatches = code.match(R_TEMPLATES) || [];
    for (let i = 0; i < templateMatches.length; i++) {
        // console.log(templateMatches[i]);
        code = code.replace(templateMatches[i],
            templateMatches[i]
                .replace(/'/g, '\\\'')
                .replace(/^([^\\])?`/, '$1\'')
                .replace(/([^\\])?`$/, '$1\'')
                .replace(/\${(.*)?}/g, '\'+$1+\'')
                .replace(/\n/g, '\\n')
        );
    }
    // console.log(code);

    const parentImport = url.slice(0, url.lastIndexOf('/') + 1);
    const importMatches = code.match(R_IMPORTS) || [];
    // console.log(importMatches);
    for (let i = 0, l = importMatches.length; i < l; i++) {
        const importMatch = importMatches[i].match(R_IMPORT) || [];
        // console.log(importMatch);

        var rawImport = importMatch[0];
        var nameImport = importMatch[1]; // default
        var pathImport = importMatch[4] || importMatch[5];

        console.log(pathImport);
        if (pathImport.slice(0, 1) !== '/') {
            // pathImport = ImportPath(parentImport + '/' + pathImport);
            pathImport = Path.resolve(parentImport, pathImport);
        } else {
            // pathImport = ImportPath(pathImport);
            pathImport = Path.resolve(pathImport);
        }
        console.log(pathImport);

        before = before + '\twindow.Oxe.loader.load("' + pathImport + '"),\n';
        after = after + 'var ' + nameImport + ' = $MODULES[' + i + '].default;\n';

        code = code.replace(rawImport, '') || [];
    }

    let hasDefault = false;
    const exps = code.match(R_EXPORTS) || [];
    for (let i = 0, l = exps.length; i < l; i++) {
        const exp = exps[i].match(R_EXPORT) || [];
        const rawExport = exp[0];
        const defaultExport = exp[1] || '';
        const typeExport = exp[2] || '';
        const nameExport = exp[3] || '';
        if (defaultExport) {
            if (hasDefault) {
                code = code.replace(rawExport, `$DEFAULT = ${typeExport} ${nameExport}`);
            } else {
                hasDefault = true;
                code = code.replace(rawExport, `var $DEFAULT = ${typeExport} ${nameExport}`);
            }
        }
    }

    if (hasDefault) {
        code += '\n\nreturn { default: $DEFAULT };\n';
    }

    code = '"use strict";\n' + before + after + code + '});';

    return code;
};

const IMPORT = function (url) {
    // window._import.modules = window._import.modules || {};
    return new Promise(function (resolve, reject) {

        var a = window.document.createElement('a');
        a.setAttribute('href', url);
        url = a.href;

        // if (window._import.modules[url]) {
        if (MODULES[url]) {
            // return resolve(window._import.modules[url]);
            return resolve(MODULES[url]);
        }

        var script = document.createElement('script');

        var clean = function () {
            script.remove();
            URL.revokeObjectURL(script.src);
        };

        script.defer = 'defer';

        if ('noModule' in script) {
            script.type = 'module';
        }

        script.onerror = function () {
            reject(new Error('failed to import: ' + url));
            clean();
        };

        script.onload = function () {
            // resolve(window._import.modules[url]);
            resolve(MODULES[url]);
            clean();
        };

        if (false) {
        // if ('noModule' in script) {
            // var code = 'import * as m from "' + url + '"; window._import.modules["' + url + '"] = m;';
            var code = 'import * as m from "' + url + '"; Oxe.loader.data["' + url + '"] = m;';
            var blob = new Blob([ code ], { type: 'text/javascript' });

            script.src = URL.createObjectURL(blob);

            document.head.appendChild(script);
        } else {
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 || xhr.status === 0) {
                        var code = xhr.responseText;

                        code = transform(code, url);

                        var blob = new Blob([ code ], { type: 'text/javascript' });
                        script.src = URL.createObjectURL(blob);

                        document.head.appendChild(script);
                    } else {
                        reject(new Error('failed to import: ' + url));
                        clean();
                    }
                }
            };

            try {
                xhr.open('GET', url, true);
                xhr.send();
            } catch (e) {
                reject(new Error('failed to import: ' + url));
                clean();
            }

        }

    });
};

let native;
try {
    new Function('import("")');
    native = true;
} catch {
    native = false;
}

const load = async function (url) {
    if (!url) throw new Error('url argument required');
    // if (native) {
    if (false) {
        console.log('native import');
        return new Function('url', 'return import(url)')(url);
    } else {
        console.log('not native import');
        return IMPORT(url);
    }
};

const setup = async function (options = {}) {
    const { loads } = options;

    if (loads) {
        return Promise.all(loads.map(load => this.load(Path.resolve(load))));
    }

};

export default Object.freeze({
    data: MODULES,
    options: {},
    setup, load
});
<commit_msg>bug fixes and optimizations<commit_after>import Path from './path.js';

// https://regexr.com/4uued
const S_EXPORT = `
    ^export\\b
    (?:
        \\s*(default)\\s*
    )?
    (?:
        \\s*(var|let|const|function|class)\\s*
    )?
    (\\s*?:{\\s*)?
    (
        (?:\\w+\\s*,?\\s*)*
    )?
    (\\s*?:}\\s*)?
`.replace(/\s+/g, '');

// https://regexr.com/4uq22
const S_IMPORT = `
    import
    (?:
        (?:
            \\s+(\\w+)(?:\\s+|\\s*,\\s*)
        )
        ?
        (?:
            (?:\\s+(\\*\\s+as\\s+\\w+)\\s+)
            |
            (?:
                \\s*{\\s*
                (
                    (?:
                        (?:
                            (?:\\w+)
                            |
                            (?:\\w+\\s+as\\s+\\w+)
                        )
                        \\s*,?\\s*
                    )
                    *
                )
                \\s*}\\s*
            )
        )
        ?
        from
    )
    ?
    \\s*
    (?:"|')
    (.*?)
    (?:'|")
    (?:\\s*;)?
`.replace(/\s+/g, '');

const MODULES = {};
const R_IMPORT = new RegExp(S_IMPORT);
const R_EXPORT = new RegExp(S_EXPORT);
const R_IMPORTS = new RegExp(S_IMPORT, 'g');
const R_EXPORTS = new RegExp(S_EXPORT, 'gm');
const R_TEMPLATES = /[^\\]`(.|[\r\n])*?[^\\]`/g;

const transform = function (code, url) {

    let before = `window.Oxe.loader.data["${url}"] = Promise.all([\n`;
    let after = ']).then(function ($MODULES) {\n';

    const templateMatches = code.match(R_TEMPLATES) || [];
    for (let i = 0; i < templateMatches.length; i++) {
        const templateMatch = templateMatches[i];
        code = code.replace(templateMatch,
            templateMatch
                .replace(/'/g, '\\\'')
                .replace(/^([^\\])?`/, '$1\'')
                .replace(/([^\\])?`$/, '$1\'')
                .replace(/\${(.*)?}/g, '\'+$1+\'')
                .replace(/\n/g, '\\n')
        );
    }

    const parentImport = url.slice(0, url.lastIndexOf('/') + 1);
    const importMatches = code.match(R_IMPORTS) || [];
    for (let i = 0, l = importMatches.length; i < l; i++) {
        const importMatch = importMatches[i].match(R_IMPORT);
        if (!importMatch) continue;

        const rawImport = importMatch[0];
        const nameImport = importMatch[1]; // default
        const pathImport = importMatch[4] || importMatch[5];

        if (pathImport.slice(0, 1) !== '/') {
            pathImport = Path.resolve(parentImport, pathImport);
        } else {
            pathImport = Path.resolve(pathImport);
        }

        before = before + '\twindow.Oxe.loader.load("' + pathImport + '"),\n';
        after = after + 'var ' + nameImport + ' = $MODULES[' + i + '].default;\n';

        code = code.replace(rawImport, '') || [];
    }

    let hasDefault = false;
    const exportMatches = code.match(R_EXPORTS) || [];
    for (let i = 0, l = exportMatches.length; i < l; i++) {
        const exportMatch = exportMatches[i].match(R_EXPORT) || [];
        const rawExport = exportMatch[0];
        const defaultExport = exportMatch[1] || '';
        const typeExport = exportMatch[2] || '';
        const nameExport = exportMatch[3] || '';
        if (defaultExport) {
            if (hasDefault) {
                code = code.replace(rawExport, `$DEFAULT = ${typeExport} ${nameExport}`);
            } else {
                hasDefault = true;
                code = code.replace(rawExport, `var $DEFAULT = ${typeExport} ${nameExport}`);
            }
        }
    }

    if (hasDefault) {
        code += '\n\nreturn { default: $DEFAULT };\n';
    }

    code = '"use strict";\n' + before + after + code + '});';

    return code;
};

const IMPORT = function (url) {
    return new Promise(function (resolve, reject) {

        const a = window.document.createElement('a');
        a.href = url;
        url = a.href;

        if (MODULES[url]) {
            return resolve(MODULES[url]);
        }

        const script = document.createElement('script');

        const clean = function () {
            script.remove();
            URL.revokeObjectURL(script.src);
        };

        script.defer = 'defer';

        if ('noModule' in script) {
            script.type = 'module';
        }

        script.onerror = function () {
            reject(new Error(`failed to import: ${url}`));
            clean();
        };

        script.onload = function () {
            resolve(MODULES[url]);
            clean();
        };

        if (false) {
        // if ('noModule' in script) {
            console.log('noModule yes');
            const code = 'import * as m from "' + url + '"; Oxe.loader.data["' + url + '"] = m;';
            const blob = new Blob([ code ], { type: 'text/javascript' });
            script.src = URL.createObjectURL(blob);
            window.document.head.appendChild(script);
        } else {
            console.log('noModule no');
            const xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 || xhr.status === 0) {
                        const code = transform(xhr.responseText, url);
                        const blob = new Blob([ code ], { type: 'text/javascript' });
                        script.src = URL.createObjectURL(blob);
                        window.document.head.appendChild(script);
                    } else {
                        reject(new Error(`failed to import: ${url}`));
                        clean();
                    }
                }
            };

            try {
                xhr.open('GET', url, true);
                xhr.send();
            } catch (e) {
                reject(new Error(`failed to import: ${url}`));
                clean();
            }

        }

    });
};

let native;
try {
    new Function('import("")');
    native = true;
} catch {
    native = false;
}

const load = async function (url) {
    if (!url) throw new Error('Oxe.loader.load - url argument required');

    url = Path.resolve(url);

    if (native) {
    // if (false) {
        console.log('native import');
        return new Function('url', 'return import(url)')(url);
    } else {
        console.log('not native import');
        return IMPORT(url);
    }

};

const setup = async function (options = {}) {
    const { loads } = options;

    if (loads) {
        return Promise.all(loads.map(load => this.load(load)));
    }

};

export default Object.freeze({
    data: MODULES,
    options: {},
    setup, load
});
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';

class Cell extends PureComponent {
  static propTypes = {
    align: PropTypes.oneOf(['left', 'center', 'right']),
    backgroundColor: PropTypes.oneOf(['transparent', 'white', 'neutral']),
    border: PropTypes.oneOf(['none', 'around', 'left', 'right']),
    bordered: PropTypes.bool,
    children: PropTypes.any,
    className: PropTypes.string,
    flex: PropTypes.oneOf(['min-width', '1', '2', '3', '4']),
    soft: PropTypes.bool,
    strong: PropTypes.bool,
  };

  static defaultProps = {
    align: 'left',
    backgroundColor: 'transparent',
    border: 'none',
    flex: '1',
    soft: false,
    strong: false,
  };

  render() {
    const { align, backgroundColor, border, children, className, flex, soft, strong, ...others } = this.props;

    const classNames = cx(
      theme['cell'],
      theme[`align-${align}`],
      theme[`flex-${flex}`],
      theme[`has-background-${backgroundColor}`],
      theme[`has-border-${border}`],
      {
        [theme['is-soft']]: soft,
        [theme['is-strong']]: strong,
      },
      className,
    );

    return (

        {children}

    );
  }
}

export default Cell;
<commit_msg>Removed the obsolete transparent background option<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';

class Cell extends PureComponent {
  static propTypes = {
    align: PropTypes.oneOf(['left', 'center', 'right']),
    backgroundColor: PropTypes.oneOf(['white', 'neutral']),
    border: PropTypes.oneOf(['none', 'around', 'left', 'right']),
    bordered: PropTypes.bool,
    children: PropTypes.any,
    className: PropTypes.string,
    flex: PropTypes.oneOf(['min-width', '1', '2', '3', '4']),
    soft: PropTypes.bool,
    strong: PropTypes.bool,
  };

  static defaultProps = {
    align: 'left',
    backgroundColor: 'transparent',
    border: 'none',
    flex: '1',
    soft: false,
    strong: false,
  };

  render() {
    const { align, backgroundColor, border, children, className, flex, soft, strong, ...others } = this.props;

    const classNames = cx(
      theme['cell'],
      theme[`align-${align}`],
      theme[`flex-${flex}`],
      theme[`has-background-${backgroundColor}`],
      theme[`has-border-${border}`],
      {
        [theme['is-soft']]: soft,
        [theme['is-strong']]: strong,
      },
      className,
    );

    return (

        {children}

    );
  }
}

export default Cell;
<|endoftext|>