<commit_before>var spawn = require('child_process').spawn;
var path = require('path');
var chokidar = require('chokidar');
var colors = require('colors/safe');
var configPath = '';

RegExp.prototype.toJSON = RegExp.prototype.toString;

var watcher = function(config) {
    var noConfigFound = false;

    config = config || path.resolve(process.cwd(), 'watcherConfig.js');

    if (config.constructor === String) {
        var resolvedPath = path.resolve(config);
        configPath = resolvedPath;

        try {
            config = require(resolvedPath);
        } catch (e) {
            config = {};
            configPath = '';
            noConfigFound = true;
        }
    }

    config = ensureConfigValues(config);

    if (noConfigFound) {
        console.log(colors.yellow('Couldn\'t find the config file »' + resolvedPath + '«. Will use default values.'));
        console.log(colors.yellow('Default config values are:'));
        console.log(JSON.stringify(config, null, 2));
        console.log();
    } else {
        console.log(colors.green('Using following config:'));
        console.log(JSON.stringify(config, null, 2));
        console.log();
    }

    setupCommandsOnStart(config);
    setupCommandsOnChange(config);
};

var ensureConfigValues = function(config) {
    config.directory = config.directory || process.cwd();
    config.delay = config.delay || 1000;
    config.ignore = config.ignore || [];
    config.commandsOnStart = config.commandsOnStart || [];
    config.commandsOnChange = config.commandsOnChange || [];

    return config;
};

var setupCommandsOnStart = function(config) {
    for (var index in config.commandsOnStart) {
        spawnCommand(config.commandsOnStart[index].command);
    }
};

var setupCommandsOnChange = function(config) {
    var timeoutID = 0;
    var allEvents = [];

    if (config.commandsOnChange.length) {
        var directoryToWatch = config.directory.indexOf('/') !== 0 ? path.resolve(process.cwd(), config.directory) : config.directory;

        var watcher = chokidar.watch(directoryToWatch, {
            ignoreInitial: true,
            ignored: config.ignore
        });

        watcher.on('all', function(event, path) {
            clearTimeout(timeoutID);
            allEvents.push([event, path]);

            if (configPath && event === 'change' && configPath === path) { // The config file changed
                delete require.cache[configPath];
                config = require(configPath);
                config = ensureConfigValues(config);
                console.log(colors.green('Config file changed, reloaded it. The new values are:'));
                console.log(JSON.stringify(config, null, 2));
                console.log();
                allEvents = [];
                return;
            }

            timeoutID = setTimeout(function() {
                console.log(colors.green('Executing callbacks for the following events:'));
                console.log(JSON.stringify(allEvents, null, 2));
                console.log();

                for (var index in config.commandsOnChange) {
                    var commandString;

                    if (config.commandsOnChange[index].command.constructor === String) {
                        spawnCommand(config.commandsOnChange[index].command);
                    } else if (config.commandsOnChange[index].command.constructor === Function) {
                        for (var i = 0; i < allEvents.length; i++) {
                            var event = allEvents[i][0];
                            var file = allEvents[i][1];
                            var callbackResult = config.commandsOnChange[index].command(event, file);
                            spawnCommand(callbackResult);
                        }
                    }
                }

                allEvents = [];
            }, config.delay);
        });
    }
};

var spawnCommand = function(commandString) {
    var command = parseCommand(commandString);
    var arguments = parseArguments(commandString);

    if (command) {
        console.log(colors.green('Spawning command:'), command);
        console.log(colors.green('with the following arguments:'));
        console.log(JSON.stringify(arguments, null, 2));
        console.log();

        var child = spawn(command, arguments, {
            stdio: 'inherit'
        });

        child.on('exit', function() {
            console.log();
        });
    }
}

var parseCommand = function(command) {
    var quoted = false;
    var parsedCommand = '';

    if (!command) {
        return parsedCommand;
    }

    for (var i = 0; i < command.length; i++) {
        var char = command.charAt(i);
        var previousChar = i > 0 ? command.charAt(i - 1) : '';

        if (char === ' ') {
            if (quoted || previousChar === '\\') {
                parsedCommand += char;
            } else {
                return parsedCommand;
            }
        } else if (char === '"' || char === '\'') {
            if (quoted) {
                return parsedCommand;
            }

            quoted = true;
        } else {
            parsedCommand += char;
        }
    }

    return parsedCommand;
}

var parseArguments = function(command) {
    var quoted = false;
    var parentheses = 0;
    var brackets = 0;
    var braces = 0;
    var parsedArguments = [];

    if (!command) {
        return parsedArguments;
    }

    var currentArgument = '';
    var arguments = command.replace(parseCommand(command), '').trim();

    var addArgument = function() {
        currentArgument = currentArgument.trim();

        if (currentArgument.indexOf('"') === 0 && currentArgument.match(/"$/)) {
            currentArgument = currentArgument.substring(1, currentArgument.length - 1);
        }

        if (currentArgument !== '') {
            parsedArguments.push(currentArgument);
        }

        currentArgument = '';
        quoted = false;
        var parentheses = 0;
        var brackets = 0;
        var braces = 0;
    };

    for (var i = 0; i < arguments.length; i++) {
        var char = arguments[i];
        var previousChar = i > 0 ? arguments.charAt(i - 1) : '';

        if (char === ' ') {
            if (quoted || previousChar === '\\') {
                currentArgument += char;
            } else {
                addArgument();
            }
        } else if (char === '"' || char === '\'') {
            currentArgument += char;

            if (quoted && !parentheses && !brackets && !braces) {
                addArgument();
            } else if (quoted) {
                quoted = false;
            } else {
                quoted = true;
            }
        } else if (char === '(') {
            currentArgument += char;
            parentheses++;

        } else if (char === ')') {
            currentArgument += char;
            parentheses--;

            if (!parentheses && !brackets && !braces && !quoted) {
                addArgument();
            }
        } else if (char === '[') {
            currentArgument += char;
            brackets++;
        } else if (char === ']') {
            currentArgument += char;
            brackets--;

            if (!parentheses && !brackets && !braces && !quoted) {
                addArgument();
            }
        } else if (char === '{') {
            currentArgument += char;
            braces++;
        } else if (char === '}') {
            currentArgument += char;
            braces--;

            if (!parentheses && !brackets && !braces && !quoted) {
                addArgument();
            }
        } else {
            currentArgument += char;
        }
    }

    if (currentArgument) {
        addArgument();
    }

    return parsedArguments;
};

module.exports = watcher;
<commit_msg>Kill the spawned processes on exit<commit_after>var spawn = require('child_process').spawn;
var path = require('path');
var chokidar = require('chokidar');
var colors = require('colors/safe');
var configPath = '';
var spawnedCommands = [];

RegExp.prototype.toJSON = RegExp.prototype.toString;

var watcher = function(config) {
    var noConfigFound = false;

    config = config || path.resolve(process.cwd(), 'watcherConfig.js');

    if (config.constructor === String) {
        var resolvedPath = path.resolve(config);
        configPath = resolvedPath;

        try {
            config = require(resolvedPath);
        } catch (e) {
            config = {};
            configPath = '';
            noConfigFound = true;
        }
    }

    config = ensureConfigValues(config);

    if (noConfigFound) {
        console.log(colors.yellow('Couldn\'t find the config file »' + resolvedPath + '«. Will use default values.'));
        console.log(colors.yellow('Default config values are:'));
        console.log(JSON.stringify(config, null, 2));
        console.log();
    } else {
        console.log(colors.green('Using following config (' + configPath + '):'));
        console.log(JSON.stringify(config, null, 2));
        console.log();
    }

    setupCommandsOnStart(config);
    setupCommandsOnChange(config);
};

var ensureConfigValues = function(config) {
    config.directory = config.directory || process.cwd();
    config.delay = config.delay || 1000;
    config.ignore = config.ignore || [];
    config.commandsOnStart = config.commandsOnStart || [];
    config.commandsOnChange = config.commandsOnChange || [];

    return config;
};

var setupCommandsOnStart = function(config) {
    for (var index in config.commandsOnStart) {
        var command = spawnCommand(config.commandsOnStart[index].command);
        spawnedCommands.push(command);
    }
};

var setupCommandsOnChange = function(config) {
    var timeoutID = 0;
    var allEvents = [];

    if (config.commandsOnChange.length) {
        var directoryToWatch = config.directory.indexOf('/') !== 0 ? path.resolve(process.cwd(), config.directory) : config.directory;

        var watcher = chokidar.watch(directoryToWatch, {
            ignoreInitial: true,
            ignored: config.ignore
        });

        watcher.on('all', function(event, path) {
            clearTimeout(timeoutID);
            allEvents.push([event, path]);

            if (configPath && event === 'change' && configPath === path) { // The config file changed
                delete require.cache[configPath];
                config = require(configPath);
                config = ensureConfigValues(config);
                console.log(colors.green('Config file changed, reloaded it. The new values are:'));
                console.log(JSON.stringify(config, null, 2));
                console.log();
                allEvents = [];
                return;
            }

            timeoutID = setTimeout(function() {
                console.log(colors.green('Executing callbacks for the following events:'));
                console.log(JSON.stringify(allEvents, null, 2));
                console.log();

                for (var index in config.commandsOnChange) {
                    var commandString;

                    if (config.commandsOnChange[index].command.constructor === String) {
                        spawnCommand(config.commandsOnChange[index].command);
                    } else if (config.commandsOnChange[index].command.constructor === Function) {
                        for (var i = 0; i < allEvents.length; i++) {
                            var event = allEvents[i][0];
                            var file = allEvents[i][1];
                            var callbackResult = config.commandsOnChange[index].command(event, file);
                            spawnCommand(callbackResult);
                        }
                    }
                }

                allEvents = [];
            }, config.delay);
        });
    }
};

var spawnCommand = function(commandString) {
    var command = parseCommand(commandString);
    var arguments = parseArguments(commandString);

    if (command) {
        console.log(colors.green('Spawning command:'), command);
        console.log(colors.green('with the following arguments:'));
        console.log(JSON.stringify(arguments, null, 2));
        console.log();

        var child = spawn(command, arguments, {
            stdio: 'inherit'
        });

        child.on('exit', function() {
            console.log();
        });

        return child;
    }

    return null;
}

process.on('exit', function(code) {
    for (var index in spawnedCommands) {
        var command = spawnedCommands[index];

        if (command) {
            command.kill();
        }
    }
});

var parseCommand = function(command) {
    var quoted = false;
    var parsedCommand = '';

    if (!command) {
        return parsedCommand;
    }

    for (var i = 0; i < command.length; i++) {
        var char = command.charAt(i);
        var previousChar = i > 0 ? command.charAt(i - 1) : '';

        if (char === ' ') {
            if (quoted || previousChar === '\\') {
                parsedCommand += char;
            } else {
                return parsedCommand;
            }
        } else if (char === '"' || char === '\'') {
            if (quoted) {
                return parsedCommand;
            }

            quoted = true;
        } else {
            parsedCommand += char;
        }
    }

    return parsedCommand;
}

var parseArguments = function(command) {
    var quoted = false;
    var parentheses = 0;
    var brackets = 0;
    var braces = 0;
    var parsedArguments = [];

    if (!command) {
        return parsedArguments;
    }

    var currentArgument = '';
    var arguments = command.replace(parseCommand(command), '').trim();

    var addArgument = function() {
        currentArgument = currentArgument.trim();

        if (currentArgument.indexOf('"') === 0 && currentArgument.match(/"$/)) {
            currentArgument = currentArgument.substring(1, currentArgument.length - 1);
        }

        if (currentArgument !== '') {
            parsedArguments.push(currentArgument);
        }

        currentArgument = '';
        quoted = false;
        var parentheses = 0;
        var brackets = 0;
        var braces = 0;
    };

    for (var i = 0; i < arguments.length; i++) {
        var char = arguments[i];
        var previousChar = i > 0 ? arguments.charAt(i - 1) : '';

        if (char === ' ') {
            if (quoted || previousChar === '\\') {
                currentArgument += char;
            } else {
                addArgument();
            }
        } else if (char === '"' || char === '\'') {
            currentArgument += char;

            if (quoted && !parentheses && !brackets && !braces) {
                addArgument();
            } else if (quoted) {
                quoted = false;
            } else {
                quoted = true;
            }
        } else if (char === '(') {
            currentArgument += char;
            parentheses++;

        } else if (char === ')') {
            currentArgument += char;
            parentheses--;

            if (!parentheses && !brackets && !braces && !quoted) {
                addArgument();
            }
        } else if (char === '[') {
            currentArgument += char;
            brackets++;
        } else if (char === ']') {
            currentArgument += char;
            brackets--;

            if (!parentheses && !brackets && !braces && !quoted) {
                addArgument();
            }
        } else if (char === '{') {
            currentArgument += char;
            braces++;
        } else if (char === '}') {
            currentArgument += char;
            braces--;

            if (!parentheses && !brackets && !braces && !quoted) {
                addArgument();
            }
        } else {
            currentArgument += char;
        }
    }

    if (currentArgument) {
        addArgument();
    }

    return parsedArguments;
};

module.exports = watcher;
<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs')

process.chdir(__dirname)

const packageFile = '../build/package.json'
const typingFile = '../build/index.d.ts'
const packageData = JSON.parse(fs.readFileSync(packageFile))
packageData.scripts = void 0
const unUseDevDependencies = [
  'babel-eslint',
  'babel-eslint',
  'babel-preset-es2015',
  'babel-preset-react',
  'babel-preset-stage-0',
  'conventional-changelog-cli',
  'cross-env',
  'eslint',
  'eslint-config-airbnb',
  'eslint-plugin-babel',
  'eslint-plugin-import',
  'eslint-plugin-jsx-a11y',
  'eslint-plugin-react',
  'fs-extra',
  'husky',
  'npm-run-all',
  'tslint',
  'tslint-eslint-rules',
  'tslint-no-circular-imports'
]
for (const devDependencies of unUseDevDependencies) {
  packageData.devDependencies[devDependencies] = void 0
}

fs.writeFileSync(packageFile, JSON.stringify(packageData, null, 2))

fs.writeFileSync(typingFile, fs.readFileSync(typingFile, 'utf8') + '\n' + fs.readFileSync('../typings/index.d.ts', 'utf8'))
<commit_msg>fix: Fixed package.json devDependencies modules<commit_after>const path = require('path')
const fs = require('fs')

process.chdir(__dirname)

const packageFile = '../build/package.json'
const typingFile = '../build/index.d.ts'
const packageData = JSON.parse(fs.readFileSync(packageFile))
packageData.scripts = void 0
packageData.devDependencies = void 0

fs.writeFileSync(packageFile, JSON.stringify(packageData, null, 2))

fs.writeFileSync(typingFile, fs.readFileSync(typingFile, 'utf8') + '\n' + fs.readFileSync('../typings/index.d.ts', 'utf8'))
<|endoftext|>


<commit_before>"use strict";

/**
 * Great Circle calculation
 * @author  Kevin Ulrich
 * @class  greatCircle
 */
class greatCircle {

	/**
	 * Constructor
	 * @param  {object} opts Option-Object. Accepts properties 'sort' ('asc' || 'desc' || false) and limit (positive integer || false)
	 */
	constructor(opts) {
		if(typeof opts != 'object') opts = {};

		this.sort = greatCircle._getValidSort(opts.sort);
		this.limit = greatCircle._getValidLimit(opts.limit);
	}

	/**
	 * Calculate a list of points. Can override default 'sort' and 'limit' by property.
	 * @param  {object} opts Option-Object. Accepts properties from (valid point), to (array of or single valid point), sort (see constructor), limit (see constructor)
	 * @return {array}      The resulting distance list with given points and distances
	 */
	calc(opts) {
		if(typeof opts.from != 'object' || typeof opts.from.lat == 'undefined' || typeof opts.from.lon == 'undefined') throw "greatCircle: From needs to be an object with at least lat and lon";
		if(typeof opts.to != 'object') throw "greatCircle: To needs to be an object with at least lat and lon";

		var tempSort = typeof opts.sort != 'undefined' ? greatCircle._getValidSort(opts.sort) : this.sort;
		var tempLimit = typeof opts.limit != 'undefined' ? greatCircle._getValidLimit(opts.limit) : this.limit;

		var from = greatCircle._getValidPoint(opts.from);
		var to = greatCircle._getValidPointList(opts.to);

		var distances = greatCircle._getDistanceList(from, to);

		if(tempSort !== false) distances = greatCircle._sortDistanceList(distances, tempSort);
		if(tempLimit !== false) distances = greatCircle._limitDistanceList(distances, tempLimit);

		return distances;
	}

	/**
	 * The raw calculation according to the haversine formula.
	 * Big thanks to http://www.movable-type.co.uk/scripts/latlong.html for the brilliant explanation of
	 * different methods of determining great circle distance!
	 * @param  {object} from A valid point
	 * @param  {object} to   A valid point
	 * @return {number}      Distance in meters
	 * @static
	 */
	static getDistanceBetween(from, to) {
		from = greatCircle._getValidPoint(from);
		to = greatCircle._getValidPoint(to);

		var radLatFrom = greatCircle.floatToRadians(from.lat);
		var radLatTo = greatCircle.floatToRadians(to.lat);

		var radDeltaLat = greatCircle.floatToRadians(to.lat - from.lat);
		var radDeltaLon = greatCircle.floatToRadians(to.lon - from.lon);

		var a = Math.sin(radDeltaLat / 2) * Math.sin(radDeltaLat / 2) +
		        Math.cos(radLatFrom) * Math.cos(radLatTo) *
		        Math.sin(radDeltaLon / 2) * Math.sin(radDeltaLon / 2);

		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

		// Precision less than a meter is not really accurate here

		return parseInt(greatCircle.earthRadius * c);
	}

	/**
	 * Limit a list to a number of items
	 * @param  {object} list  The Array/Object to limit
	 * @param  {number} limit Number of allowed items as integer
	 * @return {object}       Truncated Array/Object
	 * @static
	 */
	static _limitDistanceList(list, limit) {
		limit = greatCircle._getValidLimit(limit);

		if(limit === false) return [];

		var limitedArray = [];

		for(var item in list) {
			if(item == limit) break;
			limitedArray.push(list[item]);
		}

		return limitedArray;
	}

	/**
	 * Sort a list of distances (as determined by the distance property of items)
	 * @param  {object} list      List of distances, as returned by _getDistanceList()
	 * @param  {mixed} direction A valid direction ('asc' || 'desc' || false)
	 * @return {object}           The sorted List
	 * @static
	 */
	static _sortDistanceList(list, direction) {
		direction = greatCircle._getValidSort(direction);

		// Use selection sort for now

		var sortedList = [];

		while(list.length > 0) {
			let maxIdx = 0;

			for(var item in list) {
				let thisItem = list[item];

				if(typeof thisItem.distance == 'undefined') continue;

				if(thisItem.distance >= list[maxIdx].distance) {
					maxIdx = item;
				}
			}

			sortedList.push(list.splice(maxIdx, 1)[0]);
		}

		if(direction == 'asc') sortedList.reverse();

		return sortedList;
	}

	/**
	 * Get a list of distances for from to each to point
	 * @param  {object} from A valid point
	 * @param  {object} to   An array of or a single valid point
	 * @return {object}      An Array containing the distances for from to each to point.
	 * @static
	 */
	static _getDistanceList(from, to) {
		from = greatCircle._getValidPoint(from);
		to = greatCircle._getValidPointList(to);

		var distanceList = [];

		for(var item in to) {
			try {
				let distance = greatCircle.getDistanceBetween(from, to[item]);
				distanceList.push({from: from, to: to[item], distance: distance});
			} catch(e) {
				continue;
			}
		}

		return distanceList;
	}

	/**
	 * Check/Clean/Format a given list for validity.
	 * @param  {object} list The list to check
	 * @return {object}      An Array containing valid points
	 * @static
	 */
	static _getValidPointList(list) {
		try {
			if(!(list instanceof Array)) return [greatCircle._getValidPoint(list)];
		} catch(e) {
			return [];
		}

		var cleanList = [];

		for(var item in list) {
			try {
				cleanList.push(greatCircle._getValidPoint(list[item]));
			} catch(e) {
				continue;
			}
		}

		return cleanList;
	}

	/**
	 * Check/Clean/Format a given point for validity
	 * @param  {object} point The point to check
	 * @return {object}       A valid point
	 * @static
	 */
	static _getValidPoint(point) {
		if(typeof point == 'undefined') throw "greatCircle: No coordinates given";
		if(isNaN(point.lat) || isNaN(point.lon)) throw "greatCircle: Invalid coordinates";
		if(parseFloat(point.lat) < -180 || parseFloat(point.lat) > 180) throw "greatCircle: Invalid coordinates";
		if(parseFloat(point.lon) < -180 || parseFloat(point.lon) > 180) throw "greatCircle: Invalid coordinates";

		var cleanPoint = {lat: parseFloat(point.lat), lon: parseFloat(point.lon)};

		if(typeof point.payload != 'undefined') cleanPoint.payload = point.payload;

		return cleanPoint;
	}

	/**
	 * Get a valid sorting parameter. Either 'asc', 'desc', or false for no sorting.
	 * @param  {mixed} input Input to check
	 * @return {mixed}       Valid sorting parameter for use with further functions
	 * @static
	 */
	static _getValidSort(input) {
		return (input && input == 'asc') ? 'asc' : (input && input == 'desc') ? 'desc' : false;
	}

	/**
	 * Get a valid limit parameter. Can either be false or a positive integer
	 * @param  {mixed} input Input to check
	 * @return {mixed}       Valid limit parameter
	 * @static
	 */
	static _getValidLimit(input) {
		return (typeof input == 'boolean') ? false : (input === null) ? false : isNaN(input) ? false : (parseInt(input) > 0) ? parseInt(input) : false;
	}

	/**
	 * Convert a degree as floating point number to degree radians
	 * @param  {number} number The input degree
	 * @return {number}        Degree Radians
	 * @static
	 */
	static floatToRadians(number) {
		return number * Math.PI / 180;
	}
}

/**
 * The earths radius as required by the haversine formula
 * @type {Number}
 * @static
 */
greatCircle.earthRadius = 6371000;

module.exports = greatCircle;<commit_msg>Refactor List-Sorting for Readability<commit_after>"use strict";

/**
 * Great Circle calculation
 * @author  Kevin Ulrich
 * @class  greatCircle
 */
class greatCircle {

	/**
	 * Constructor
	 * @param  {object} opts Option-Object. Accepts properties 'sort' ('asc' || 'desc' || false) and limit (positive integer || false)
	 */
	constructor(opts) {
		if(typeof opts != 'object') opts = {};

		this.sort = greatCircle._getValidSort(opts.sort);
		this.limit = greatCircle._getValidLimit(opts.limit);
	}

	/**
	 * Calculate a list of points. Can override default 'sort' and 'limit' by property.
	 * @param  {object} opts Option-Object. Accepts properties from (valid point), to (array of or single valid point), sort (see constructor), limit (see constructor)
	 * @return {array}      The resulting distance list with given points and distances
	 */
	calc(opts) {
		if(typeof opts.from != 'object' || typeof opts.from.lat == 'undefined' || typeof opts.from.lon == 'undefined') throw "greatCircle: From needs to be an object with at least lat and lon";
		if(typeof opts.to != 'object') throw "greatCircle: To needs to be an object with at least lat and lon";

		var tempSort = typeof opts.sort != 'undefined' ? greatCircle._getValidSort(opts.sort) : this.sort;
		var tempLimit = typeof opts.limit != 'undefined' ? greatCircle._getValidLimit(opts.limit) : this.limit;

		var from = greatCircle._getValidPoint(opts.from);
		var to = greatCircle._getValidPointList(opts.to);

		var distances = greatCircle._getDistanceList(from, to);

		if(tempSort !== false) distances = greatCircle._sortDistanceList(distances, tempSort);
		if(tempLimit !== false) distances = greatCircle._limitDistanceList(distances, tempLimit);

		return distances;
	}

	/**
	 * The raw calculation according to the haversine formula.
	 * Big thanks to http://www.movable-type.co.uk/scripts/latlong.html for the brilliant explanation of
	 * different methods of determining great circle distance!
	 * @param  {object} from A valid point
	 * @param  {object} to   A valid point
	 * @return {number}      Distance in meters
	 * @static
	 */
	static getDistanceBetween(from, to) {
		from = greatCircle._getValidPoint(from);
		to = greatCircle._getValidPoint(to);

		var radLatFrom = greatCircle.floatToRadians(from.lat);
		var radLatTo = greatCircle.floatToRadians(to.lat);

		var radDeltaLat = greatCircle.floatToRadians(to.lat - from.lat);
		var radDeltaLon = greatCircle.floatToRadians(to.lon - from.lon);

		var a = Math.sin(radDeltaLat / 2) * Math.sin(radDeltaLat / 2) +
		        Math.cos(radLatFrom) * Math.cos(radLatTo) *
		        Math.sin(radDeltaLon / 2) * Math.sin(radDeltaLon / 2);

		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

		// Precision less than a meter is not really accurate here

		return parseInt(greatCircle.earthRadius * c);
	}

	/**
	 * Limit a list to a number of items
	 * @param  {object} list  The Array/Object to limit
	 * @param  {number} limit Number of allowed items as integer
	 * @return {object}       Truncated Array/Object
	 * @static
	 */
	static _limitDistanceList(list, limit) {
		limit = greatCircle._getValidLimit(limit);

		if(limit === false) return [];

		var limitedArray = [];

		for(var item in list) {
			if(item == limit) break;
			limitedArray.push(list[item]);
		}

		return limitedArray;
	}

	/**
	 * Sort a list of distances (as determined by the distance property of items)
	 * @param  {object} list      List of distances, as returned by _getDistanceList()
	 * @param  {mixed} direction A valid direction ('asc' || 'desc' || false)
	 * @return {object}           The sorted List
	 * @static
	 */
	static _sortDistanceList(list, direction) {
		direction = greatCircle._getValidSort(direction);

		// Use selection sort for now

		var sortedList = [];

		while(list.length > 0) {
			sortedList.push(greatCircle._spliceLargestListItem(list));
		}

		if(direction == 'asc') sortedList.reverse();

		return sortedList;
	}

	/**
	 * Get the list item with the largest distance, remove it from the list
	 * and return it
	 * @param {object} list       List of distances, as returned by _getDistanceList()
	 * @return {object}           The sorted List
	 * @static
	 */
	static _spliceLargestListItem(list) {
		var maxIdx = 0;

		for(var item in list) {
			let thisItem = list[item];

			if(typeof thisItem.distance == 'undefined') continue;

			if(thisItem.distance >= list[maxIdx].distance) {
				maxIdx = item;
			}
		}

		return list.splice(maxIdx, 1)[0];
	}

	/**
	 * Get a list of distances for from to each to point
	 * @param  {object} from A valid point
	 * @param  {object} to   An array of or a single valid point
	 * @return {object}      An Array containing the distances for from to each to point.
	 * @static
	 */
	static _getDistanceList(from, to) {
		from = greatCircle._getValidPoint(from);
		to = greatCircle._getValidPointList(to);

		var distanceList = [];

		for(var item in to) {
			try {
				let distance = greatCircle.getDistanceBetween(from, to[item]);
				distanceList.push({from: from, to: to[item], distance: distance});
			} catch(e) {
				continue;
			}
		}

		return distanceList;
	}

	/**
	 * Check/Clean/Format a given list for validity.
	 * @param  {object} list The list to check
	 * @return {object}      An Array containing valid points
	 * @static
	 */
	static _getValidPointList(list) {
		try {
			if(!(list instanceof Array)) return [greatCircle._getValidPoint(list)];
		} catch(e) {
			return [];
		}

		var cleanList = [];

		for(var item in list) {
			try {
				cleanList.push(greatCircle._getValidPoint(list[item]));
			} catch(e) {
				continue;
			}
		}

		return cleanList;
	}

	/**
	 * Check/Clean/Format a given point for validity
	 * @param  {object} point The point to check
	 * @return {object}       A valid point
	 * @static
	 */
	static _getValidPoint(point) {
		if(typeof point == 'undefined') throw "greatCircle: No coordinates given";
		if(isNaN(point.lat) || isNaN(point.lon)) throw "greatCircle: Invalid coordinates";
		if(parseFloat(point.lat) < -180 || parseFloat(point.lat) > 180) throw "greatCircle: Invalid coordinates";
		if(parseFloat(point.lon) < -180 || parseFloat(point.lon) > 180) throw "greatCircle: Invalid coordinates";

		var cleanPoint = {lat: parseFloat(point.lat), lon: parseFloat(point.lon)};

		if(typeof point.payload != 'undefined') cleanPoint.payload = point.payload;

		return cleanPoint;
	}

	/**
	 * Get a valid sorting parameter. Either 'asc', 'desc', or false for no sorting.
	 * @param  {mixed} input Input to check
	 * @return {mixed}       Valid sorting parameter for use with further functions
	 * @static
	 */
	static _getValidSort(input) {
		return (input && input == 'asc') ? 'asc' : (input && input == 'desc') ? 'desc' : false;
	}

	/**
	 * Get a valid limit parameter. Can either be false or a positive integer
	 * @param  {mixed} input Input to check
	 * @return {mixed}       Valid limit parameter
	 * @static
	 */
	static _getValidLimit(input) {
		return (typeof input == 'boolean') ? false : (input === null) ? false : isNaN(input) ? false : (parseInt(input) > 0) ? parseInt(input) : false;
	}

	/**
	 * Convert a degree as floating point number to degree radians
	 * @param  {number} number The input degree
	 * @return {number}        Degree Radians
	 * @static
	 */
	static floatToRadians(number) {
		return number * Math.PI / 180;
	}
}

/**
 * The earths radius as required by the haversine formula
 * @type {Number}
 * @static
 */
greatCircle.earthRadius = 6371000;

module.exports = greatCircle;<|endoftext|>


<commit_before>/**
 *
 * tweet model
 *
 * @param {type} app
 * @returns {tweetsModel}
 */
var tweetModel = function(app) {

    var collection = 'tweet';
    var Schema = app.mongoose.Schema;
    var mixedType = Schema.Types.Mixed;

    /**
     * possible values:
     * String / Number / Date / Buffer / Boolean / Mixed / ObjectId / Array
     *
     * @type tweetsModel.Schema
     */
    var tweetSchema = new Schema({
        jamendo_track_id: {type: String, trim: true, required: true, index: true},
        twitter_user_id: {type: String, trim: true, required: true},
        twitter_user_name: {type: String, trim: true},
        twitter_user_image: {type: String, trim: true},
        twitter_tweet_date: Date,
        twitter_tweet_id: {type: String, trim: true, required: true, index: {unique: true}},
        twitter_tweet_original_text: {type: String, trim: true}
    },
    {safe: true, wtimeout: 10000}); // return errors and 10 seconds timeout

    // should mongoose checks if indexes exist on every startup?
    tweetSchema.set('autoIndex', true);

    this.model = app.mongoose.model(collection, tweetSchema);

};

/**
 *
 * save a single object
 *
 * @returns {undefined}
 */
tweetModel.prototype.saveOne = function(data, callback) {

    console.log('save a single object');

    tweet = new this.model(data);

    tweet.save(callback);

};

/**
 *
 * save multiple objects
 *
 * @returns {undefined}
 */
tweetModel.prototype.saveAll = function() {

    console.log('save multiple objects');

};

/**
 *
 * delete a single object
 *
 * @returns {undefined}
 */
tweetModel.prototype.deleteOne = function() {

    console.log('delete a single object');

};

/**
 *
 * delete multiple objects
 *
 * @returns {undefined}
 */
tweetModel.prototype.deleteAll = function() {

    console.log('delete multiple objects');

};

/**
 *
 * find a single object
 *
 * @returns {undefined}
 */
tweetModel.prototype.findOne = function() {

    console.log('find a single object');

};

/**
 *
 * find multiple objects
 *
 * @returns {undefined}
 */
tweetModel.prototype.findAll = function() {

    console.log('find multiple objects');

};

tweetModel.prototype.mapReduce = function(options, callback) {

    console.log('tweetModel -> mapReduce');

    var mapReduceContainer = {};

    mapReduceContainer.map = tweetsMap;
    mapReduceContainer.reduce = tweetsReduce;

    tweet = new this.model();

    tweet.mapReduce(mapReduceContainer, callback)

};

var tweetsMap = function() {

    return emit(this.jam_unit + '-' + this.jam_id, this.tw_userid);

}

var tweetsReduce = function(jam_richid, tw_users) {

    jam_richid = jam_richid.split("-");

    var jam_unit = jam_richid[0];
    var jam_id = jam_richid[1];
    var reduceVal = {id: jam_id, unit: jam_unit, count_tot: 0, count_uniq: 0, users: []};

    for (var i; i < this.tw_users.length; i++) {

        if (reduceVal.users.indexOf(this.tw_users[i]) == -1) {

            reduceVal.users.push(this.tw_users[i]);
            reduceVal.count_uniq++;

        }

        reduceVal.count_tot++;

    }

    return reduceVal;

}

module.exports = tweetModel;<commit_msg>Update tweet.js<commit_after>/**
 *
 * tweet model
 *
 * @param {type} app
 * @returns {tweetsModel}
 */
var tweetModel = function(app) {

    var collection = 'tweet';
    var Schema = app.mongoose.Schema;
    var mixedType = Schema.Types.Mixed;

    /**
     * possible values:
     * String / Number / Date / Buffer / Boolean / Mixed / ObjectId / Array
     *
     * @type tweetsModel.Schema
     */
    var tweetSchema = new Schema({
        jamendo_track_id: {type: String, trim: true, required: true, index: true},
        twitter_user_id: {type: String, trim: true, required: true},
        twitter_user_name: {type: String, trim: true},
        twitter_user_image: {type: String, trim: true},
        twitter_tweet_date: Date,
        twitter_tweet_id: {type: String, trim: true, required: true, index: {unique: true}},
        twitter_tweet_original_text: {type: String, trim: true}
    },
    {safe: true, wtimeout: 10000}); // return errors and 10 seconds timeout

    // should mongoose checks if indexes exist on every startup?
    tweetSchema.set('autoIndex', true);

    this.model = app.mongoose.model(collection, tweetSchema);

};

/**
 *
 * save a single object
 *
 * @returns {undefined}
 */
tweetModel.prototype.saveOne = function(data, callback) {

    console.log('save a single object');

    tweet = new this.model(data);

    tweet.save(callback);

};

/**
 *
 * save multiple objects
 *
 * @returns {undefined}
 */
tweetModel.prototype.saveAll = function() {

    console.log('save multiple objects');

};

/**
 *
 * delete a single object
 *
 * @returns {undefined}
 */
tweetModel.prototype.deleteOne = function() {

    console.log('delete a single object');

};

/**
 *
 * delete multiple objects
 *
 * @returns {undefined}
 */
tweetModel.prototype.deleteAll = function() {

    console.log('delete multiple objects');

};

/**
 *
 * find a single object
 *
 * @returns {undefined}
 */
tweetModel.prototype.findOne = function() {

    console.log('find a single object');

};

/**
 *
 * find multiple objects
 *
 * @returns {undefined}
 */
tweetModel.prototype.findAll = function() {

    console.log('find multiple objects');

};

tweetModel.prototype.mapReduce = function(options, callback) {

    console.log('tweetModel -> mapReduce');

    var mapReduceContainer = {};

    var dateOject = new Date();

    var oneDayAgo = dateOject.getDate()-1;
    var oneWeekAgo = dateOject.getDate()-7;

    mapReduceContainer.map = tweetsMap;
    mapReduceContainer.reduce = tweetsReduce;
    mapReduceContainer.query = { twitter_tweet_date : { $gt : oneDayAgo }};

    tweet = new this.model();

    tweet.mapReduce(mapReduceContainer, callback)

};

var tweetsMap = function() {

    return emit(this.jam_unit + '-' + this.jam_id, this.tw_userid);

}

var tweetsReduce = function(jam_richid, tw_users) {

    jam_richid = jam_richid.split("-");

    var jam_unit = jam_richid[0];
    var jam_id = jam_richid[1];
    var reduceVal = {id: jam_id, unit: jam_unit, count_tot: 0, count_uniq: 0, users: []};

    for (var i; i < this.tw_users.length; i++) {

        if (reduceVal.users.indexOf(this.tw_users[i]) == -1) {

            reduceVal.users.push(this.tw_users[i]);
            reduceVal.count_uniq++;

        }

        reduceVal.count_tot++;

    }

    return reduceVal;

}

module.exports = tweetModel;
<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/**
 * Container is responsible for the video rendering and state
 */

var UIObject = require('../../base/ui_object');
var Styler = require('../../base/styler');
var Events = require('../../base/events')
var find = require('lodash.find')

class Container extends UIObject {
  get name() { return 'Container' }
  get attributes() { return { class: 'container', 'data-container': '' } }
  get events() {
    return {
      'click': 'clicked',
      'dblclick': 'dblClicked',
      'doubleTap': 'dblClicked',
      'mouseenter': 'mouseEnter',
      'mouseleave': 'mouseLeave'
    }
  }

  constructor(options) {
    super(options);
    this.currentTime = 0
    this.playback = options.playback;
    this.settings = this.playback.settings;
    this.isReady = false;
    this.mediaControlDisabled = false;
    this.plugins = [this.playback];
    this.bindEvents();
  }

  bindEvents() {
    this.listenTo(this.playback, Events.PLAYBACK_PROGRESS, this.progress);
    this.listenTo(this.playback, Events.PLAYBACK_TIMEUPDATE, this.timeUpdated);
    this.listenTo(this.playback, Events.PLAYBACK_READY, this.ready);
    this.listenTo(this.playback, Events.PLAYBACK_BUFFERING, this.buffering);
    this.listenTo(this.playback, Events.PLAYBACK_BUFFERFULL, this.bufferfull);
    this.listenTo(this.playback, Events.PLAYBACK_SETTINGSUPDATE, this.settingsUpdate);
    this.listenTo(this.playback, Events.PLAYBACK_LOADEDMETADATA, this.loadedMetadata);
    this.listenTo(this.playback, Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate);
    this.listenTo(this.playback, Events.PLAYBACK_BITRATE, this.updateBitrate);
    this.listenTo(this.playback, Events.PLAYBACK_PLAYBACKSTATE, this.playbackStateChanged);
    this.listenTo(this.playback, Events.PLAYBACK_DVR, this.playbackDvrStateChanged);
    this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_DISABLE, this.disableMediaControl);
    this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_ENABLE, this.enableMediaControl);
    this.listenTo(this.playback, Events.PLAYBACK_ENDED, this.ended);
    this.listenTo(this.playback, Events.PLAYBACK_PLAY, this.playing);
    this.listenTo(this.playback, Events.PLAYBACK_ERROR, this.error);
  }

  playbackStateChanged() {
    this.trigger(Events.CONTAINER_PLAYBACKSTATE);
  }

  playbackDvrStateChanged(dvrInUse) {
    this.settings = this.playback.settings
    this.dvrInUse = dvrInUse
    this.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, dvrInUse)
  }

  updateBitrate(newBitrate) {
    this.trigger(Events.CONTAINER_BITRATE, newBitrate)
  }

  statsReport(metrics) {
    this.trigger(Events.CONTAINER_STATS_REPORT, metrics)
  }

  getPlaybackType() {
    return this.playback.getPlaybackType()
  }

  isDvrEnabled() {
    return !!this.playback.dvrEnabled
  }

  isDvrInUse() {
    return !!this.dvrInUse
  }

  destroy() {
    this.trigger(Events.CONTAINER_DESTROYED, this, this.name);
    this.playback.destroy();
    this.plugins.forEach((plugin) => plugin.destroy())
    this.$el.remove();
  }

  setStyle(style) {
    this.$el.css(style);
  }

  animate(style, duration) {
    return this.$el.animate(style, duration).promise();
  }

  ready() {
    this.isReady = true;
    this.trigger(Events.CONTAINER_READY, this.name);
  }

  isPlaying() {
    return this.playback.isPlaying();
  }

  getCurrentTime() {
    return this.currentTime
  }

  getDuration() {
    return this.playback.getDuration();
  }

  error(errorObj) {
    this.trigger(Events.CONTAINER_ERROR, {error: errorObj, container: this}, this.name);
  }

  loadedMetadata(duration) {
    this.trigger(Events.CONTAINER_LOADEDMETADATA, duration);
  }

  timeUpdated(position, duration) {
    this.currentTime = position
    this.trigger(Events.CONTAINER_TIMEUPDATE, position, duration, this.name)
  }

  progress(startPosition, endPosition, duration) {
    this.trigger(Events.CONTAINER_PROGRESS, startPosition, endPosition, duration, this.name);
  }

  playing() {
    this.trigger(Events.CONTAINER_PLAY, this.name);
  }

  play() {
    this.playback.play();
  }

  stop() {
    this.trigger(Events.CONTAINER_STOP, this.name);
    this.playback.stop();
    this.currentTime = 0
  }

  pause() {
    this.playback.pause();
    this.trigger(Events.CONTAINER_PAUSE, this.name);
  }

  ended() {
    this.trigger(Events.CONTAINER_ENDED, this, this.name);
    this.currentTime = 0
  }

  clicked() {
    this.trigger(Events.CONTAINER_CLICK, this, this.name);
  }

  dblClicked() {
    this.trigger(Events.CONTAINER_DBLCLICK, this, this.name);
  }

  setCurrentTime(time) {
    this.trigger(Events.CONTAINER_SEEK, time, this.name);
    this.playback.seek(time);
  }

  setVolume(value) {
    this.trigger(Events.CONTAINER_VOLUME, value, this.name);
    this.playback.volume(value);
  }

  fullscreen() {
    this.trigger(Events.CONTAINER_FULLSCREEN, this.name);
  }

  buffering() {
    this.trigger(Events.CONTAINER_STATE_BUFFERING, this.name);
  }

  bufferfull() {
    this.trigger(Events.CONTAINER_STATE_BUFFERFULL, this.name);
  }

  addPlugin(plugin) {
    this.plugins.push(plugin);
  }

  hasPlugin(name) {
    return !!this.getPlugin(name);
  }

  getPlugin(name) {
    return find(this.plugins, (plugin) => { return plugin.name === name });
  }

  mouseEnter() {
    this.trigger(Events.CONTAINER_MOUSE_ENTER)
  }

  mouseLeave() {
    this.trigger(Events.CONTAINER_MOUSE_LEAVE)
  }

  settingsUpdate() {
    this.settings = this.playback.settings;
    this.trigger(Events.CONTAINER_SETTINGSUPDATE);
  }

  highDefinitionUpdate() {
    this.trigger(Events.CONTAINER_HIGHDEFINITIONUPDATE);
  }

  isHighDefinitionInUse() {
    return this.playback.isHighDefinitionInUse()
  }

  disableMediaControl() {
    this.mediaControlDisabled = true;
    this.trigger(Events.CONTAINER_MEDIACONTROL_DISABLE);
  }

  enableMediaControl() {
    this.mediaControlDisabled = false;
    this.trigger(Events.CONTAINER_MEDIACONTROL_ENABLE);
  }

  render() {
    var style = Styler.getStyleFor('container');
    this.$el.append(style);
    this.$el.append(this.playback.render().el);
    return this;
  }
}

module.exports = Container;
<commit_msg>container: start using PLAYBACK_PAUSE event (closes #436)<commit_after>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/**
 * Container is responsible for the video rendering and state
 */

var UIObject = require('../../base/ui_object');
var Styler = require('../../base/styler');
var Events = require('../../base/events')
var find = require('lodash.find')

class Container extends UIObject {
  get name() { return 'Container' }
  get attributes() { return { class: 'container', 'data-container': '' } }
  get events() {
    return {
      'click': 'clicked',
      'dblclick': 'dblClicked',
      'doubleTap': 'dblClicked',
      'mouseenter': 'mouseEnter',
      'mouseleave': 'mouseLeave'
    }
  }

  constructor(options) {
    super(options);
    this.currentTime = 0
    this.playback = options.playback;
    this.settings = this.playback.settings;
    this.isReady = false;
    this.mediaControlDisabled = false;
    this.plugins = [this.playback];
    this.bindEvents();
  }

  bindEvents() {
    this.listenTo(this.playback, Events.PLAYBACK_PROGRESS, this.progress);
    this.listenTo(this.playback, Events.PLAYBACK_TIMEUPDATE, this.timeUpdated);
    this.listenTo(this.playback, Events.PLAYBACK_READY, this.ready);
    this.listenTo(this.playback, Events.PLAYBACK_BUFFERING, this.buffering);
    this.listenTo(this.playback, Events.PLAYBACK_BUFFERFULL, this.bufferfull);
    this.listenTo(this.playback, Events.PLAYBACK_SETTINGSUPDATE, this.settingsUpdate);
    this.listenTo(this.playback, Events.PLAYBACK_LOADEDMETADATA, this.loadedMetadata);
    this.listenTo(this.playback, Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate);
    this.listenTo(this.playback, Events.PLAYBACK_BITRATE, this.updateBitrate);
    this.listenTo(this.playback, Events.PLAYBACK_PLAYBACKSTATE, this.playbackStateChanged);
    this.listenTo(this.playback, Events.PLAYBACK_DVR, this.playbackDvrStateChanged);
    this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_DISABLE, this.disableMediaControl);
    this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_ENABLE, this.enableMediaControl);
    this.listenTo(this.playback, Events.PLAYBACK_ENDED, this.ended);
    this.listenTo(this.playback, Events.PLAYBACK_PLAY, this.playing);
    this.listenTo(this.playback, Events.PLAYBACK_PAUSE, this.paused);
    this.listenTo(this.playback, Events.PLAYBACK_ERROR, this.error);
  }

  playbackStateChanged() {
    this.trigger(Events.CONTAINER_PLAYBACKSTATE);
  }

  playbackDvrStateChanged(dvrInUse) {
    this.settings = this.playback.settings
    this.dvrInUse = dvrInUse
    this.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, dvrInUse)
  }

  updateBitrate(newBitrate) {
    this.trigger(Events.CONTAINER_BITRATE, newBitrate)
  }

  statsReport(metrics) {
    this.trigger(Events.CONTAINER_STATS_REPORT, metrics)
  }

  getPlaybackType() {
    return this.playback.getPlaybackType()
  }

  isDvrEnabled() {
    return !!this.playback.dvrEnabled
  }

  isDvrInUse() {
    return !!this.dvrInUse
  }

  destroy() {
    this.trigger(Events.CONTAINER_DESTROYED, this, this.name);
    this.playback.destroy();
    this.plugins.forEach((plugin) => plugin.destroy())
    this.$el.remove();
  }

  setStyle(style) {
    this.$el.css(style);
  }

  animate(style, duration) {
    return this.$el.animate(style, duration).promise();
  }

  ready() {
    this.isReady = true;
    this.trigger(Events.CONTAINER_READY, this.name);
  }

  isPlaying() {
    return this.playback.isPlaying();
  }

  getCurrentTime() {
    return this.currentTime
  }

  getDuration() {
    return this.playback.getDuration();
  }

  error(errorObj) {
    this.trigger(Events.CONTAINER_ERROR, {error: errorObj, container: this}, this.name);
  }

  loadedMetadata(duration) {
    this.trigger(Events.CONTAINER_LOADEDMETADATA, duration);
  }

  timeUpdated(position, duration) {
    this.currentTime = position
    this.trigger(Events.CONTAINER_TIMEUPDATE, position, duration, this.name)
  }

  progress(startPosition, endPosition, duration) {
    this.trigger(Events.CONTAINER_PROGRESS, startPosition, endPosition, duration, this.name);
  }

  playing() {
    this.trigger(Events.CONTAINER_PLAY, this.name);
  }

  paused() {
    this.trigger(Events.CONTAINER_PAUSE, this.name);
  }

  play() {
    this.playback.play();
  }

  stop() {
    this.trigger(Events.CONTAINER_STOP, this.name);
    this.playback.stop();
    this.currentTime = 0
  }

  pause() {
    this.playback.pause();
  }

  ended() {
    this.trigger(Events.CONTAINER_ENDED, this, this.name);
    this.currentTime = 0
  }

  clicked() {
    this.trigger(Events.CONTAINER_CLICK, this, this.name);
  }

  dblClicked() {
    this.trigger(Events.CONTAINER_DBLCLICK, this, this.name);
  }

  setCurrentTime(time) {
    this.trigger(Events.CONTAINER_SEEK, time, this.name);
    this.playback.seek(time);
  }

  setVolume(value) {
    this.trigger(Events.CONTAINER_VOLUME, value, this.name);
    this.playback.volume(value);
  }

  fullscreen() {
    this.trigger(Events.CONTAINER_FULLSCREEN, this.name);
  }

  buffering() {
    this.trigger(Events.CONTAINER_STATE_BUFFERING, this.name);
  }

  bufferfull() {
    this.trigger(Events.CONTAINER_STATE_BUFFERFULL, this.name);
  }

  addPlugin(plugin) {
    this.plugins.push(plugin);
  }

  hasPlugin(name) {
    return !!this.getPlugin(name);
  }

  getPlugin(name) {
    return find(this.plugins, (plugin) => { return plugin.name === name });
  }

  mouseEnter() {
    this.trigger(Events.CONTAINER_MOUSE_ENTER)
  }

  mouseLeave() {
    this.trigger(Events.CONTAINER_MOUSE_LEAVE)
  }

  settingsUpdate() {
    this.settings = this.playback.settings;
    this.trigger(Events.CONTAINER_SETTINGSUPDATE);
  }

  highDefinitionUpdate() {
    this.trigger(Events.CONTAINER_HIGHDEFINITIONUPDATE);
  }

  isHighDefinitionInUse() {
    return this.playback.isHighDefinitionInUse()
  }

  disableMediaControl() {
    this.mediaControlDisabled = true;
    this.trigger(Events.CONTAINER_MEDIACONTROL_DISABLE);
  }

  enableMediaControl() {
    this.mediaControlDisabled = false;
    this.trigger(Events.CONTAINER_MEDIACONTROL_ENABLE);
  }

  render() {
    var style = Styler.getStyleFor('container');
    this.$el.append(style);
    this.$el.append(this.playback.render().el);
    return this;
  }
}

module.exports = Container;
<|endoftext|>


<commit_before>const path = require("path");
const webpack = require("webpack");
const process = require("process");
const express = require("express");
const proxy = require("http-proxy-middleware");
const fs = require("fs-extra");

import build from "./build";
import getWebpackConfig from "../config/getWebpackClientConfig";
import getAssetPath from "../lib/getAssetPath";

import { getLogger } from "../lib/server/logger";
const LOGGER = getLogger();

const APP_ROOT = process.cwd();
const APP_CONFIG_PATH = path.join(APP_ROOT, "src", "config", "application.js");
const APP_SERVER_CONFIG_PATH = path.join(APP_ROOT, "src", "config", "application.server.js");
const ASSET_PATH = getAssetPath();

const IS_PRODUCTION = process.env.NODE_ENV === "production";

// @TODO Make this value a function rather than a global, or better yet, get it passed in
const PUBLIC_PATH = ASSET_PATH;

process.env.NODE_PATH = path.join(__dirname, "../..");

module.exports = function () {
  // clean the slate by removing `webpack-asset.json` before building a new one
  fs.removeSync(path.join(process.cwd(), "webpack-assets.json"));

  const compiler = webpack(getWebpackConfig(APP_ROOT, APP_CONFIG_PATH, IS_PRODUCTION));

  const appServerConfig = require(APP_SERVER_CONFIG_PATH).default;
  const server = Object.assign({protocol: "http", host: "0.0.0.0", port: 8888}, appServerConfig);
  const assetPort = appServerConfig.assetPort || 8880;

  if (!IS_PRODUCTION) {
    const app = express();
    app.use(require("webpack-dev-middleware")(compiler, {
      noInfo: true,
      publicPath: PUBLIC_PATH
    }));
    app.use(require("webpack-hot-middleware")(compiler));

    // Proxy http requests from server to client in development mode
    app.use(proxy({
      changeOrigin: false,
      target: `${server.protocol}://${server.host}:${assetPort}`,
      logLevel: LOGGER.level,
      logProvider: () => {
        return LOGGER;
      },
      onError: (err, req, res) => {
        // When the client is restarting, show our polling message
        res.status(200).sendFile("poll.html", {root: path.join(__dirname, "../lib")});
      }
    }));

    app.listen(server.port, server.host, function (error) {
      if (error) {
        LOGGER.error(error);
        return;
      }

      LOGGER.info(`Server running on ${server.protocol}://${server.host}:${server.port}`);
    });
  }
  else {
    build();
  }
};

<commit_msg>Updating the means of accessing application server config to guardrail for when there is no application server config file<commit_after>const path = require("path");
const webpack = require("webpack");
const process = require("process");
const express = require("express");
const proxy = require("http-proxy-middleware");
const fs = require("fs-extra");

import build from "./build";
import getWebpackConfig from "../config/getWebpackClientConfig";
import getAssetPath from "../lib/getAssetPath";
import loadServerConfig from "../lib/server/loadServerConfig";

import { getLogger } from "../lib/server/logger";
const LOGGER = getLogger();

const APP_ROOT = process.cwd();
const APP_CONFIG_PATH = path.join(APP_ROOT, "src", "config", "application.js");
const ASSET_PATH = getAssetPath();

const IS_PRODUCTION = process.env.NODE_ENV === "production";

// @TODO Make this value a function rather than a global, or better yet, get it passed in
const PUBLIC_PATH = ASSET_PATH;

process.env.NODE_PATH = path.join(__dirname, "../..");

module.exports = function () {
  // clean the slate by removing `webpack-asset.json` before building a new one
  fs.removeSync(path.join(process.cwd(), "webpack-assets.json"));

  const compiler = webpack(getWebpackConfig(APP_ROOT, APP_CONFIG_PATH, IS_PRODUCTION));

  const appServerConfig = loadServerConfig();
  const server = Object.assign({protocol: "http", host: "0.0.0.0", port: 8888}, appServerConfig);
  const assetPort = appServerConfig.assetPort || 8880;

  if (!IS_PRODUCTION) {
    const app = express();
    app.use(require("webpack-dev-middleware")(compiler, {
      noInfo: true,
      publicPath: PUBLIC_PATH
    }));
    app.use(require("webpack-hot-middleware")(compiler));

    // Proxy http requests from server to client in development mode
    app.use(proxy({
      changeOrigin: false,
      target: `${server.protocol}://${server.host}:${assetPort}`,
      logLevel: LOGGER.level,
      logProvider: () => {
        return LOGGER;
      },
      onError: (err, req, res) => {
        // When the client is restarting, show our polling message
        res.status(200).sendFile("poll.html", {root: path.join(__dirname, "../lib")});
      }
    }));

    app.listen(server.port, server.host, function (error) {
      if (error) {
        LOGGER.error(error);
        return;
      }

      LOGGER.info(`Server running on ${server.protocol}://${server.host}:${server.port}`);
    });
  }
  else {
    build();
  }
};

<|endoftext|>


<commit_before>/*
 *      This file is part of GPaste.
 *
 *      Copyright 2014 Marc-Antoine Perennou <Marc-Antoine@Perennou.com>
 *
 *      GPaste is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 3 of the License, or
 *      (at your option) any later version.
 *
 *      GPaste is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with GPaste.  If not, see <http://www.gnu.org/licenses/>.
 */
/* -*- mode: js2; js2-basic-offset: 4; indent-tabs-mode: nil -*- */

const Lang = imports.lang;

const PopupMenu = imports.ui.popupMenu;

const Clutter = imports.gi.Clutter;
const Pango = imports.gi.Pango;
const St = imports.gi.St;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();

const DeleteItemPart = Me.imports.deleteItemPart;

const GPasteItem = new Lang.Class({
    Name: 'GPasteItem',
    Extends: PopupMenu.PopupMenuItem,

    _init: function(client, settings, index) {
        this.parent("");

        this._client = client;
        this._settings = settings;
        this._index = index;

        this.connect('activate', function(actor, event) {
            client.select(index, null);
        });

        this.actor.connect('key-press-event', Lang.bind(this, this._onKeyPressed));

        this.actor.add(new DeleteItemPart.GPasteDeleteItemPart(client, index), { expand: true, x_align: St.Align.END });

        if (index == 0)
            this.label.set_style("font-weight: bold;");

        this._clientChangedId = client.connect('changed', Lang.bind(this, this._resetText));
        this._resetText();

        this._settingsChangedId = settings.connect('changed::element-size', Lang.bind(this, this._resetTextSize));
        this.label.clutter_text.ellipsize = Pango.EllipsizeMode.END;
        this._resetTextSize();

        this.actor.connect('destroy', Lang.bind(this, this._onDestroy));
    },

    get text() {
        return this.label.get_text();
    },

    _resetText: function() {
        this._client.get_element(this._index, Lang.bind(this, function(client, result) {
            let text = client.get_element_finish(result);
            this.label.clutter_text.set_text(text.replace(/\n/g, ' '));
        }));
    },

    _resetTextSize: function() {
        this.label.clutter_text.max_length = this._settings.get_element_size();
    },

    _onKeyPressed: function(actor, event) {
        let symbol = event.get_key_symbol();
        if (symbol == Clutter.KEY_BackSpace || symbol == Clutter.KEY_Delete) {
            this._client.delete(this._index, null);
            return Clutter.EVENT_STOP;
        }
        return Clutter.EVENT_PROPAGATE;
    },

    _onDestroy: function() {
        this._client.disconnect(this._clientChangedId);
        this._settings.disconnect(this._settingsChangedId);
    }
});
<commit_msg>gnome-shell: display tweak<commit_after>/*
 *      This file is part of GPaste.
 *
 *      Copyright 2014 Marc-Antoine Perennou <Marc-Antoine@Perennou.com>
 *
 *      GPaste is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 3 of the License, or
 *      (at your option) any later version.
 *
 *      GPaste is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with GPaste.  If not, see <http://www.gnu.org/licenses/>.
 */
/* -*- mode: js2; js2-basic-offset: 4; indent-tabs-mode: nil -*- */

const Lang = imports.lang;

const PopupMenu = imports.ui.popupMenu;

const Clutter = imports.gi.Clutter;
const Pango = imports.gi.Pango;
const St = imports.gi.St;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();

const DeleteItemPart = Me.imports.deleteItemPart;

const GPasteItem = new Lang.Class({
    Name: 'GPasteItem',
    Extends: PopupMenu.PopupMenuItem,

    _init: function(client, settings, index) {
        this.parent("");

        this._client = client;
        this._settings = settings;
        this._index = index;

        this.connect('activate', function(actor, event) {
            client.select(index, null);
        });

        this.actor.connect('key-press-event', Lang.bind(this, this._onKeyPressed));

        this.actor.add(new DeleteItemPart.GPasteDeleteItemPart(client, index), { expand: true, x_align: St.Align.END });

        if (index == 0)
            this.label.set_style("font-weight: bold;");

        this._clientChangedId = client.connect('changed', Lang.bind(this, this._resetText));
        this._resetText();

        this._settingsChangedId = settings.connect('changed::element-size', Lang.bind(this, this._resetTextSize));
        this.label.clutter_text.ellipsize = Pango.EllipsizeMode.END;
        this._resetTextSize();

        this.actor.connect('destroy', Lang.bind(this, this._onDestroy));
    },

    get text() {
        return this.label.get_text();
    },

    _resetText: function() {
        this._client.get_element(this._index, Lang.bind(this, function(client, result) {
            let text = client.get_element_finish(result);
            this.label.clutter_text.set_text(text.replace(/[\t\n\r]/g, ' '));
        }));
    },

    _resetTextSize: function() {
        this.label.clutter_text.max_length = this._settings.get_element_size();
    },

    _onKeyPressed: function(actor, event) {
        let symbol = event.get_key_symbol();
        if (symbol == Clutter.KEY_BackSpace || symbol == Clutter.KEY_Delete) {
            this._client.delete(this._index, null);
            return Clutter.EVENT_STOP;
        }
        return Clutter.EVENT_PROPAGATE;
    },

    _onDestroy: function() {
        this._client.disconnect(this._clientChangedId);
        this._settings.disconnect(this._settingsChangedId);
    }
});
<|endoftext|>


<commit_before>//quick & dirty theme switcher, written to potentially work as a bookmarklet
(function($){
	$.themeswitcher = function(){
		if( $('[data-url=themeswitcher]').length ){ return; }
		var themesDir = 'http://jquerymobile.com/test/themes/',
			themes = ['default','valencia'],
			currentPage = $.mobile.activePage,
			menuPage = $( '
' +
						'
' +
							'
Switch Theme:
'+
						'
'+
						'

'+
					'
' )
					.appendTo( $.mobile.pageContainer ),
			menu = menuPage.find('ul');

		//menu items
		$.each(themes, function( i ){
			$('
' + themes[ i ].charAt(0).toUpperCase() + themes[ i ].substr(1) + '
')
				.click(function(){
					addTheme( themes[i] );
					return false;
				})
				.appendTo(menu);
		});

		//remover, adder
		function addTheme(theme){
			$('head').append( '<link rel=\'stylesheet\' href=\''+ themesDir + theme +'/\' />' );
		}

		//create page, listview
		menuPage.page();

	};
})(jQuery);
<commit_msg>updated to use namespaced data attrs<commit_after>//quick & dirty theme switcher, written to potentially work as a bookmarklet
(function($){
	$.themeswitcher = function(){
		if( $('[data-url=themeswitcher]').length ){ return; }
		var themesDir = 'http://jquerymobile.com/test/themes/',
			themes = ['default','valencia'],
			currentPage = $.mobile.activePage,
			menuPage = $( '
' +
						'
' +
							'
Switch Theme:
'+
						'
'+
						'

'+
					'
' )
					.appendTo( $.mobile.pageContainer ),
			menu = menuPage.find('ul');

		//menu items
		$.each(themes, function( i ){
			$('
' + themes[ i ].charAt(0).toUpperCase() + themes[ i ].substr(1) + '
')
				.click(function(){
					addTheme( themes[i] );
					return false;
				})
				.appendTo(menu);
		});

		//remover, adder
		function addTheme(theme){
			$('head').append( '<link rel=\'stylesheet\' href=\''+ themesDir + theme +'/\' />' );
		}

		//create page, listview
		menuPage.page();

	};
})(jQuery);
<|endoftext|>


<commit_before>module.exports.up = async function (knex) {
  await knex.schema.createTable('settings', function (table) {
    table.string('key').primary()
    table.string('value')
  })

  await knex.schema.createTable('users', function (table) {
    table.increments('id')
    table.string('email').unique()
    table.string('passwordHash', 60)
    table.index('email')
  })

  await knex.schema.createTable('meters', function (table) {
    table.string('id').primary()
    table.string('type')
    table.integer('ownerUserId')
    table.foreign('ownerUserId').references('users.id')
  })

  await knex.schema.createTable('authTokens', function (table) {
    table.string('token', 64).primary().notNullable()
    table.integer('ownerUserId')
    table.foreign('ownerUserId').references('users.id')
  })

  await knex.schema.createTable('telegrams', function (table) {
    table.increments('id')
    table.integer('ownerUserId')
    table.foreign('ownerUserId').references('users.id')
    table.binary('telegram')
    table.timestamp('uploadTimestamp', true).defaultTo(knex.fn.now())
  })

  await knex.schema.createTable('electricityReadings', function (table) {
    table.string('meterId')
    table.timestamp('timestamp', true)
    table.float('totalConsumptionKwhLow')
    table.float('totalConsumptionKwhHigh')
    table.float('totalProductionKwhLow')
    table.float('totalProductionKwhHigh')
    table.float('currentConsumptionKw')
    table.float('currentProductionKw')
    table.primary(['meterId', 'timestamp'])
  })

  await knex.schema.createTable('gasReadings', function (table) {
    table.integer('meterId')
    table.timestamp('timestamp', true)
    table.float('totalConsumptionM3')
    table.primary(['meterId', 'timestamp'])
  })
}

module.exports.down = async function (knex) {
  await knex.schema.dropTable('gasReadings')
  await knex.schema.dropTable('electricityReadings')
  await knex.schema.dropTable('telegrams')
  await knex.schema.dropTable('authTokens')
  await knex.schema.dropTable('meters')
  await knex.schema.dropTable('users')
  await knex.schema.dropTable('settings')
}
<commit_msg>Meter ID is a string here too<commit_after>module.exports.up = async function (knex) {
  await knex.schema.createTable('settings', function (table) {
    table.string('key').primary()
    table.string('value')
  })

  await knex.schema.createTable('users', function (table) {
    table.increments('id')
    table.string('email').unique()
    table.string('passwordHash', 60)
    table.index('email')
  })

  await knex.schema.createTable('meters', function (table) {
    table.string('id').primary()
    table.string('type')
    table.integer('ownerUserId')
    table.foreign('ownerUserId').references('users.id')
  })

  await knex.schema.createTable('authTokens', function (table) {
    table.string('token', 64).primary().notNullable()
    table.integer('ownerUserId')
    table.foreign('ownerUserId').references('users.id')
  })

  await knex.schema.createTable('telegrams', function (table) {
    table.increments('id')
    table.integer('ownerUserId')
    table.foreign('ownerUserId').references('users.id')
    table.binary('telegram')
    table.timestamp('uploadTimestamp', true).defaultTo(knex.fn.now())
  })

  await knex.schema.createTable('electricityReadings', function (table) {
    table.string('meterId')
    table.timestamp('timestamp', true)
    table.float('totalConsumptionKwhLow')
    table.float('totalConsumptionKwhHigh')
    table.float('totalProductionKwhLow')
    table.float('totalProductionKwhHigh')
    table.float('currentConsumptionKw')
    table.float('currentProductionKw')
    table.primary(['meterId', 'timestamp'])
  })

  await knex.schema.createTable('gasReadings', function (table) {
    table.string('meterId')
    table.timestamp('timestamp', true)
    table.float('totalConsumptionM3')
    table.primary(['meterId', 'timestamp'])
  })
}

module.exports.down = async function (knex) {
  await knex.schema.dropTable('gasReadings')
  await knex.schema.dropTable('electricityReadings')
  await knex.schema.dropTable('telegrams')
  await knex.schema.dropTable('authTokens')
  await knex.schema.dropTable('meters')
  await knex.schema.dropTable('users')
  await knex.schema.dropTable('settings')
}
<|endoftext|>


<commit_before>const yelp = require('yelp-fusion');
const db = require('./../db/dbconnect.js').connection;

var chooseTasks = function(restaurants, size) {
  var tasks = [];
  var numTasks = size || 3;

  for (var i = 0; i < numTasks; i++) {
    var random = Math.floor( Math.random() * restaurants.length );
    tasks.push( restaurants.splice(random, 1)[0] );
  }
  return tasks;
};

let getUserPrefsFromDb = function(user, callback) {
  let id = user.id ? user.id : 2;
  db.query('SELECT * FROM users WHERE id = ?', id, function(err, results) {
    if (err) {
      callback(err, null);
    } else {
      callback(null, results);
    }
  });
};

let setProfilePrefsInDb = function(user, callback) {
  // This function is not being used in the app, because the multi-user & sessions were never implemented.
  // Only the funcion below, updateProfilePrefsInDb is being used to update user data for the single user.
  var queryData = [user.username, user.password, user.location, user.preferences];
  db.query('INSERT INTO users (username, password, location, preferences) VALUES (?, ?, ?, ?)', queryData, function(err, results) {
    if (err) {
      callback(err, null);
    } else {
      callback(null, results);
    }
  });
};

let updateProfilePrefsInDb = function(user, callback) {
  var queryData = [user.location, user.preferences, user.username];
  db.query('UPDATE users SET location = ?, preferences = ? WHERE username = ?', queryData, function(err, results) {
    if (err) {
      console.log('update error: ', err);
      callback(err, null);
    } else {
      callback(null, results);
    }
  });
};

let setQuestInDb = function(dataFromYelp, callback) {
  var defaultUserID = 1;
  var queryData = [];
  for (var i = 0; i < dataFromYelp.length; i++) {
    queryData.push(dataFromYelp[i].name);
    queryData.push(dataFromYelp[i].id);
    queryData.push(dataFromYelp[i].price);
    queryData.push(dataFromYelp[i].rating);
    queryData.push(dataFromYelp[i].location.address1);
    queryData.push(dataFromYelp[i].location.zip_code);
  }
  queryData.push(defaultUserID);
  for (var i = 0; i < dataFromYelp.length; i++) {
    queryData.push(dataFromYelp[i].id);
  }

  var queryStringBegin = 'BEGIN; ';
  var queryStringInsertRestaurant = 'INSERT IGNORE INTO restaurants (name, yelpId, price, rating, address, zip_code) VALUES (?, ?, ?, ?, ?, ?); ';
  var queryStringInsertQuestFields = 'INSERT INTO quests (creator, task1, task1Completed, task2, task2Completed, task3, task3Completed) ';
  var queryStringInsertQuestValues = 'VALUES (?, (SELECT id FROM restaurants WHERE yelpId = ?), 0, (SELECT id FROM restaurants WHERE yelpId = ?), 0, (SELECT id FROM restaurants WHERE yelpId = ?), 0); ';
  var fullQueryString = queryStringBegin.concat(queryStringInsertRestaurant, queryStringInsertRestaurant, queryStringInsertRestaurant, queryStringInsertQuestFields, queryStringInsertQuestValues, 'COMMIT;');

  db.query(fullQueryString, queryData, function(err, results) {
    if (err) {
      callback(err, null);
    } else {
      callback(null, results);
    }
  });
};

module.exports.getUserPrefsFromDb = getUserPrefsFromDb;
module.exports.setProfilePrefsInDb = setProfilePrefsInDb;
module.exports.updateProfilePrefsInDb = updateProfilePrefsInDb;
module.exports.setQuestInDb = setQuestInDb;
module.exports.chooseTasks = chooseTasks;
<commit_msg>"changed another 1 to 2"<commit_after>const yelp = require('yelp-fusion');
const db = require('./../db/dbconnect.js').connection;

var chooseTasks = function(restaurants, size) {
  var tasks = [];
  var numTasks = size || 3;

  for (var i = 0; i < numTasks; i++) {
    var random = Math.floor( Math.random() * restaurants.length );
    tasks.push( restaurants.splice(random, 1)[0] );
  }
  return tasks;
};

let getUserPrefsFromDb = function(user, callback) {
  let id = user.id ? user.id : 2;
  db.query('SELECT * FROM users WHERE id = ?', id, function(err, results) {
    if (err) {
      callback(err, null);
    } else {
      callback(null, results);
    }
  });
};

let setProfilePrefsInDb = function(user, callback) {
  // This function is not being used in the app, because the multi-user & sessions were never implemented.
  // Only the funcion below, updateProfilePrefsInDb is being used to update user data for the single user.
  var queryData = [user.username, user.password, user.location, user.preferences];
  db.query('INSERT INTO users (username, password, location, preferences) VALUES (?, ?, ?, ?)', queryData, function(err, results) {
    if (err) {
      callback(err, null);
    } else {
      callback(null, results);
    }
  });
};

let updateProfilePrefsInDb = function(user, callback) {
  var queryData = [user.location, user.preferences, user.username];
  db.query('UPDATE users SET location = ?, preferences = ? WHERE username = ?', queryData, function(err, results) {
    if (err) {
      console.log('update error: ', err);
      callback(err, null);
    } else {
      callback(null, results);
    }
  });
};

let setQuestInDb = function(dataFromYelp, callback) {
  var defaultUserID = 2;
  var queryData = [];
  for (var i = 0; i < dataFromYelp.length; i++) {
    queryData.push(dataFromYelp[i].name);
    queryData.push(dataFromYelp[i].id);
    queryData.push(dataFromYelp[i].price);
    queryData.push(dataFromYelp[i].rating);
    queryData.push(dataFromYelp[i].location.address1);
    queryData.push(dataFromYelp[i].location.zip_code);
  }
  queryData.push(defaultUserID);
  for (var i = 0; i < dataFromYelp.length; i++) {
    queryData.push(dataFromYelp[i].id);
  }

  var queryStringBegin = 'BEGIN; ';
  var queryStringInsertRestaurant = 'INSERT IGNORE INTO restaurants (name, yelpId, price, rating, address, zip_code) VALUES (?, ?, ?, ?, ?, ?); ';
  var queryStringInsertQuestFields = 'INSERT INTO quests (creator, task1, task1Completed, task2, task2Completed, task3, task3Completed) ';
  var queryStringInsertQuestValues = 'VALUES (?, (SELECT id FROM restaurants WHERE yelpId = ?), 0, (SELECT id FROM restaurants WHERE yelpId = ?), 0, (SELECT id FROM restaurants WHERE yelpId = ?), 0); ';
  var fullQueryString = queryStringBegin.concat(queryStringInsertRestaurant, queryStringInsertRestaurant, queryStringInsertRestaurant, queryStringInsertQuestFields, queryStringInsertQuestValues, 'COMMIT;');

  db.query(fullQueryString, queryData, function(err, results) {
    if (err) {
      callback(err, null);
    } else {
      callback(null, results);
    }
  });
};

module.exports.getUserPrefsFromDb = getUserPrefsFromDb;
module.exports.setProfilePrefsInDb = setProfilePrefsInDb;
module.exports.updateProfilePrefsInDb = updateProfilePrefsInDb;
module.exports.setQuestInDb = setQuestInDb;
module.exports.chooseTasks = chooseTasks;
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

Menubar.Status = function ( editor ) {

	var container = new UI.Panel();
	container.setClass( 'menu right' );

	var checkbox = new UI.Checkbox( editor.config.getKey( 'autosave' ) );
	checkbox.onChange( function () {

		editor.config.setKey( 'autosave', this.getValue() );

	} );
	container.add( checkbox );

	var title = new UI.Panel();
	title.setClass( 'title' );
	title.setTextContent( 'Autosave' );
	container.add( title );

	editor.signals.savingStarted.add( function () {

		title.setTextDecoration( 'underline' );

	} );

	editor.signals.savingFinished.add( function () {

		title.setTextDecoration( 'none' );

	} );

	return container;

};
<commit_msg>Editor: Save scene when enabling autosave.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

Menubar.Status = function ( editor ) {

	var container = new UI.Panel();
	container.setClass( 'menu right' );

	var checkbox = new UI.Checkbox( editor.config.getKey( 'autosave' ) );
	checkbox.onChange( function () {

		var value = this.getValue();

		editor.config.setKey( 'autosave', value );

		if ( value === true ) {

			editor.signals.sceneGraphChanged.dispatch();

		}

	} );
	container.add( checkbox );

	var title = new UI.Panel();
	title.setClass( 'title' );
	title.setTextContent( 'Autosave' );
	container.add( title );

	editor.signals.savingStarted.add( function () {

		title.setTextDecoration( 'underline' );

	} );

	editor.signals.savingFinished.add( function () {

		title.setTextDecoration( 'none' );

	} );

	return container;

};
<|endoftext|>


<commit_before>/**
 * @author Camille Reynders
 * @version 0.2.0
 * @namespace
 */
var dijon = {
	/**
	 * framework version number
	 * @constant
	 * @type String
	 */
	VERSION : '0.5.0'
};//dijon

  //======================================//
 // dijon.System
//======================================//

/**
 * @class dijon.System
 * @constructor
*/
dijon.System = function(){
	/** @private */
	this._mappings = {};

	/** @private */
	this._outlets = {};

    /** @private */
    this._handlers = {};

    /** @private */
    this._callbacks = {};

    this.strictInjections = true;
};//dijon.System

dijon.System.prototype = {

	/**
	 * @private
	 * @param {Class} clazz
	 */
	_createAndSetupInstance : function( key, clazz ){
		var instance = new clazz();
		this.injectInto( key, instance );
		if( "setup" in instance ) instance.setup.call( instance );
		return instance;
	},

	/**
	 * @private
	 * @param {String} key
	 * @param {Boolean} overrideRules
	 * @return {Object}
	 */
	_retrieveFromCacheOrCreate : function( key, overrideRules ){
        if( overrideRules == undefined ) overrideRules = false;
        if( this._mappings.hasOwnProperty( key ) ){
            var config = this._mappings[ key ];
            var output = null;
            if( !overrideRules && config.isSingleton ){
                if( config.object == null  ){
                    config.object = this._createAndSetupInstance( key, config.clazz );
                }
                output = config.object;
            }else{
                if( config.clazz ) output = this._createAndSetupInstance( key, config.clazz );
            }
        }else{
            throw new Error( this.fqn + " is missing a rule for " + key );
        }
		return output
	},

	/**
	 * defines propertyName as an injection point for the class mapped to targetKey to be injected with an instance
	 * of the class mapped to sourceKey.
	 * @param {String} target the class the injection point is applied to.
	 * @param {String} outlet the name of the property used as an injection point.

	 * [!] MUST BE STRING
	 * @param {String} source the key to the value that will be injected
     * @see dijon.System#removeOutlet
	 */
	mapOutlet : function( source, target, outlet ){
        if( target == undefined ) target = "global";
        if( outlet == undefined ) outlet = source;
        if( ! this._outlets.hasOwnProperty( target ) ) this._outlets[ target ] = {};
		this._outlets[ target ][ outlet ] = source
	},

	/**
	 * Create (if possible) or retrieve an instance of the class mapped to key
	 * @param {Object} key
	 * @return {Object}
	 */
	getInstance : function( key ){
		return this._retrieveFromCacheOrCreate( key );
	},

	/**
	 * When asked for an instance of the class whenAskedFor or object whenAskedFor inject the instance useValue.
	 * @param {String} key
	 * @param {Object} useValue
	 */
	mapValue : function( key, useValue ){
		this._mappings[ key ]= {
            clazz : null,
            object : useValue,
            isSingleton : true
		}
	},

	/**
	 * Does a rule exist to satsify such a request?
	 * @param {String} key
	 * @return {Boolean}
	 */
	hasMapping : function( key ){
		return this._mappings.hasOwnProperty( key );
	},

	/**
	 * When asked for an instance of the class whenAskedFor or for object whenAskedFor inject a new instance of instantiateClass.
	 * @param {String} key
	 * @param {Class} clazz
	 */
	mapClass : function( key, clazz ){
		this._mappings[ key ]= {
				clazz : clazz,
				object : null,
				isSingleton : false
        }
	},

    /**
     * When asked for an instance of the class whenAskedFor or object whenAskedFor inject an instance of useSingletonOf.
     * @param {String} key
     * @param {Class} clazz
     */
    mapSingleton : function( key, clazz ){
        this._mappings[ key ] = {
            clazz : clazz,
            object : null,
            isSingleton : true
        }
    },

	/**
	 * create an instance of the class mapped to keyOrClass and fulfill it's mapped dependencies

	 * WILL ALWAYS CREATE A NEW INSTANCE, even if keyOrClass was mapped otherwise or
	 * even when keyOrClass was not mapped.
	 * @param {Class} keyOrClass
	 * @return {Object}
	 */
	instantiate : function( key ){
		return this._retrieveFromCacheOrCreate( key, true );
	},

	/**
	 * Perform an injection into an object, satisfying all it's dependencies
	 * @param {Object} instance
	 */
	injectInto : function( key, instance ){
        var o = [];
        if( this._outlets.hasOwnProperty( 'global' ) ) o.push( this._outlets[ 'global' ] );
        if( this._outlets.hasOwnProperty( key ) ) o.push( this._outlets[ key ] );
        for( var i in o ){
            var l = o [ i ];
            for( var outlet in l ){
                var source = l[ outlet ];
                //must be "in" [!]
                if( ! this.strictInjections || outlet in instance ) instance[ outlet ] = this.getInstance( source );
            }
        }

        return instance;
	},

	/**
	 * Remove a rule from the System
	 * @param {String} key
	 */
	unmap : function( key ){
		delete this._mappings[ key ];
	},

	/**
	 * removes an injection point mapping for a given class mapped to key
	 * @param {Object} key
	 * @param {String} propertyName MUST BE STRING
	 * @see dijon.System#addOutlet
	 */
	unmapOutlet : function( target, outlet ){
		delete this._outlets[ target ][ outlet ];
	},

    /**
     *
     * @param {String} eventName
     * @param {String} key
     * @param {String|Function} [handler=eventName]
     * @param {Boolean} [oneShot=false]
     */
    mapHandler : function( eventName, key, handler, oneShot ){
        if( handler == undefined ) handler = eventName;
        if( oneShot == undefined ) oneShot = false;
        if( ! this._handlers.hasOwnProperty( eventName ) ){
            this._handlers[ eventName ] = {};
        }
        this._handlers[ eventName ][ key ] = {
            handler : handler,
            oneShot: oneShot
        };
    },

    /**
     *
     * @param {String} eventName
     * @param {String} key
     */
    unmapHandler : function( eventName, key  ){
        if( this._handlers.hasOwnProperty( eventName ) && this._handlers[ eventName ].hasOwnProperty( key ) ){
            delete this._handlers[ eventName ][ key ];
        }
    },

    /**
     *
     * @param {String} eventName
     * @param {Function} callback
     * @param {Boolean} [oneShot=false]
     */
    addCallback : function( eventName, callback, oneShot ){
        if( oneShot == undefined ) oneShot = false;
        if( ! this._callbacks.hasOwnProperty( eventName ) ){
            this._callbacks[ eventName ] = [];
        }
        this._callbacks[ eventName ].push( {
            callback : callback,
            oneShot : oneShot
        } );
    },

    /**
     *
     * @param {String} eventName
     * @param {Function} callback
     */
    removeCallback : function( eventName, callback ){
        if( this._callbacks.hasOwnProperty( eventName ) ){
            var configs = this._callbacks[ eventName ];
            for( var i in configs ){
                var config = configs[ i ];
                if( config.callback === callback ) configs.splice( i, 1 );
            }
        }
    },

    /**
     *
     * @param {String} eventName
     */
    notify : function( eventName ){
        var args = Array.prototype.slice( arguments );
        if( this._handlers.hasOwnProperty( eventName ) ){
            var handlers = this._handlers[ eventName ];
            for( var key in handlers ){
                var config = handlers[ key ];
                var instance = this.getInstance( key );
                var handler;
                if( typeof config.handler == "string" ){
                    handler = instance[ config.handler ];
                }else{
                    handler = config.handler;
                }
                if( config.oneShot ) this.unmapHandler( key, eventName );
                handler.apply( instance, args );
            }
        }
        if( this._callbacks.hasOwnProperty( eventName ) ){
            var callbacks = this._callbacks[ eventName ];
            for( var i in callbacks ){
                var config = callbacks[ i ];
                if( config.oneShot ) callbacks.splice( i, 1 );
                config.callback.apply( null, args );
            }
        }
    }

};//dijon.System.prototype

/*
    system.addHandler( 'userController', 'loginStart' );
    system.notify( 'loginStart' );
 */
<commit_msg>added exceptuon throws<commit_after>/**
 * @author Camille Reynders
 * @version 0.2.0
 * @namespace
 */
var dijon = {
	/**
	 * framework version number
	 * @constant
	 * @type String
	 */
	VERSION : '0.5.0'
};//dijon

  //======================================//
 // dijon.System
//======================================//

/**
 * @class dijon.System
 * @constructor
*/
dijon.System = function(){
	/** @private */
	this._mappings = {};

	/** @private */
	this._outlets = {};

    /** @private */
    this._handlers = {};

    /** @private */
    this._callbacks = {};

    this.strictInjections = true;
};//dijon.System

dijon.System.prototype = {

	/**
	 * @private
	 * @param {Class} clazz
	 */
	_createAndSetupInstance : function( key, clazz ){
		var instance = new clazz();
		this.injectInto( key, instance );
		if( "setup" in instance ) instance.setup.call( instance );
		return instance;
	},

	/**
	 * @private
	 * @param {String} key
	 * @param {Boolean} overrideRules
	 * @return {Object}
	 */
	_retrieveFromCacheOrCreate : function( key, overrideRules ){
        if( overrideRules == undefined ) overrideRules = false;
        if( this._mappings.hasOwnProperty( key ) ){
            var config = this._mappings[ key ];
            var output = null;
            if( !overrideRules && config.isSingleton ){
                if( config.object == null  ){
                    config.object = this._createAndSetupInstance( key, config.clazz );
                }
                output = config.object;
            }else{
                if( config.clazz ) output = this._createAndSetupInstance( key, config.clazz );
            }
        }else{
            throw new Error( 1020 );
        }
		return output
	},

	/**
	 * defines propertyName as an injection point for the class mapped to targetKey to be injected with an instance
	 * of the class mapped to sourceKey.
	 * @param {String} target the class the injection point is applied to.
	 * @param {String} outlet the name of the property used as an injection point.

	 * [!] MUST BE STRING
	 * @param {String} source the key to the value that will be injected
     * @see dijon.System#removeOutlet
	 */
	mapOutlet : function( source, target, outlet ){
	    if( source == undefined ) throw new Error( 1010 );
        if( target == undefined ) target = "global";
        if( outlet == undefined ) outlet = source;
        if( ! this._outlets.hasOwnProperty( target ) ) this._outlets[ target ] = {};
		this._outlets[ target ][ outlet ] = source
	},

	/**
	 * Create (if possible) or retrieve an instance of the class mapped to key
	 * @param {Object} key
	 * @return {Object}
	 */
	getInstance : function( key ){
	    if( key == undefined ) throw new Error( 1010 )
		return this._retrieveFromCacheOrCreate( key );
	},

	/**
	 * When asked for an instance of the class whenAskedFor or object whenAskedFor inject the instance useValue.
	 * @param {String} key
	 * @param {Object} useValue
	 */
	mapValue : function( key, useValue ){
	    if( key == undefined ) throw new Error( 1010 );
		this._mappings[ key ]= {
            clazz : null,
            object : useValue,
            isSingleton : true
		}
	},

	/**
	 * Does a rule exist to satsify such a request?
	 * @param {String} key
	 * @return {Boolean}
	 */
	hasMapping : function( key ){
	    if( key == undefined ) throw new Error( 1010 );
		return this._mappings.hasOwnProperty( key );
	},

	/**
	 * When asked for an instance of the class whenAskedFor or for object whenAskedFor inject a new instance of instantiateClass.
	 * @param {String} key
	 * @param {Class} clazz
	 */
	mapClass : function( key, clazz ){
	    if( key == undefined ) throw new Error( 1010 );
	    if( key == undefined ) throw new Error( 1010 );
		this._mappings[ key ]= {
				clazz : clazz,
				object : null,
				isSingleton : false
        }
	},

    /**
     * When asked for an instance of the class whenAskedFor or object whenAskedFor inject an instance of useSingletonOf.
     * @param {String} key
     * @param {Class} clazz
     */
    mapSingleton : function( key, clazz ){
        if( key == undefined ) throw new Error( 1010 );
        if( key == undefined ) throw new Error( 1010 );
        this._mappings[ key ] = {
            clazz : clazz,
            object : null,
            isSingleton : true
        }
    },

	/**
	 * create an instance of the class mapped to keyOrClass and fulfill it's mapped dependencies

	 * WILL ALWAYS CREATE A NEW INSTANCE, even if keyOrClass was mapped otherwise or
	 * even when keyOrClass was not mapped.
	 * @param {Class} keyOrClass
	 * @return {Object}
	 */
	instantiate : function( key ){
        if( key == undefined ) throw new Error( 1010 );
		return this._retrieveFromCacheOrCreate( key, true );
	},

	/**
	 * Perform an injection into an object, satisfying all it's dependencies
	 * @param {String} key
	 * @param {Object} instance
	 */
	injectInto : function( key, instance ){
        if( key == undefined ) throw new Error( 1010 );
        if( instance == undefined ) throw new Error( 1010 );
        var o = [];
        if( this._outlets.hasOwnProperty( 'global' ) ) o.push( this._outlets[ 'global' ] );
        if( this._outlets.hasOwnProperty( key ) ) o.push( this._outlets[ key ] );
        for( var i in o ){
            var l = o [ i ];
            for( var outlet in l ){
                var source = l[ outlet ];
                //must be "in" [!]
                if( ! this.strictInjections || outlet in instance ) instance[ outlet ] = this.getInstance( source );
            }
        }

        return instance;
	},

	/**
	 * Remove a rule from the System
	 * @param {String} key
	 */
	unmap : function( key ){
        if( key == undefined ) throw new Error( 1010 );
		delete this._mappings[ key ];
	},

	/**
	 * removes an injection point mapping for a given class mapped to key
	 * @param {String} key
	 * @param {String} propertyName MUST BE STRING
	 * @see dijon.System#addOutlet
	 */
	unmapOutlet : function( target, outlet ){
        if( target == undefined ) throw new Error( 1010 );
        if( outlet == undefined ) throw new Error( 1010 );
		delete this._outlets[ target ][ outlet ];
	},

    /**
     *
     * @param {String} eventName
     * @param {String} key
     * @param {String|Function} [handler=eventName]
     * @param {Boolean} [oneShot=false]
     */
    mapHandler : function( eventName, key, handler, oneShot ){
        if( eventName == undefined ) throw new Error( 1010 );
        if( key == undefined ) throw new Error( 1010 );
        if( handler == undefined ) handler = eventName;
        if( oneShot == undefined ) oneShot = false;
        if( ! this._handlers.hasOwnProperty( eventName ) ){
            this._handlers[ eventName ] = {};
        }
        if( ! this._handlers[eventName].hasOwnProperty( key ) ){
            this._handlers[eventName][key] = [];
        }
        this._handlers[ eventName ][ key ].push( {
            handler : handler,
            oneShot: oneShot
        } );
    },

    /**
     *
     * @param {String} eventName
     * @param {String} key
     * @param {String | Function} [handler=eventName]
     */
    unmapHandler : function( eventName, key, handler  ){
        if( eventName == undefined ) throw new Error( 1010 );
        if( key == undefined ) throw new Error( 1010 );
        if( handler == undefined ) handler = eventName;
        if( this._handlers.hasOwnProperty( eventName ) && this._handlers[ eventName ].hasOwnProperty( key ) ){
            var handlers = this._handlers[ eventName ][ key ];
            for( var i in handlers ){
                if( handlers[ i ] == handler ){
                    handlers.splice( i, 1 );
                    return;
                }
            }
        }
    },

    /**
     *
     * @param {String} eventName
     * @param {Function} callback
     * @param {Boolean} [oneShot=false]
     */
    addCallback : function( eventName, callback, oneShot ){
        if( eventName == undefined ) throw new Error( 1010 );
        if( callback == undefined ) throw new Error( 1010 );
        if( oneShot == undefined ) oneShot = false;
        if( ! this._callbacks.hasOwnProperty( eventName ) ){
            this._callbacks[ eventName ] = [];
        }
        this._callbacks[ eventName ].push( {
            callback : callback,
            oneShot : oneShot
        } );
    },

    /**
     *
     * @param {String} eventName
     * @param {Function} callback
     */
    removeCallback : function( eventName, callback ){
        if( eventName == undefined ) throw new Error( 1010 );
        if( callback == undefined ) throw new Error( 1010 );
        if( this._callbacks.hasOwnProperty( eventName ) ){
            var configs = this._callbacks[ eventName ];
            for( var i in configs ){
                var config = configs[ i ];
                if( config.callback === callback ) configs.splice( i, 1 );
            }
        }
    },

    /**
     *
     * @param {String} eventName
     */
    notify : function( eventName ){
        if( eventName == undefined ) throw new Error( 1010 );
        var args = Array.prototype.slice( arguments );
        if( this._handlers.hasOwnProperty( eventName ) ){
            var handlers = this._handlers[ eventName ];
            for( var key in handlers ){
                var configs = handlers[ key ];
                var instance = this.getInstance( key );
                for( var i in configs ){
                    var handler;
                    var config = configs[ i ];
                    if( typeof config.handler == "string" ){
                        handler = instance[ config.handler ];
                    }else{
                        handler = config.handler;
                    }
                    if( config.oneShot ) this.unmapHandler( key, eventName, config.handler );
                    handler.apply( instance, args );
                }
            }
        }
        if( this._callbacks.hasOwnProperty( eventName ) ){
            var callbacks = this._callbacks[ eventName ];
            for( var i in callbacks ){
                var config = callbacks[ i ];
                if( config.oneShot ) callbacks.splice( i, 1 );
                config.callback.apply( null, args );
            }
        }
    }

};//dijon.System.prototype

/*
    system.addHandler( 'userController', 'loginStart' );
    system.notify( 'loginStart' );
 */
<|endoftext|>


<commit_before>$(document).ready(
		 $(".datepicker").each(function() {
			 locale = $('html').attr('lang');

		//	 $(replaceId($(this).attr('id'))).val($("#"+replaceId($(this).attr('id'))+"_alt").val());

			$.datepicker.setDefaults($.datepicker.regional[locale]);
			$(this).datepicker({
				altField :"#"+replaceId($(this).attr('id'))+"_alt",
				altFormat : "yy-mm-dd",
				gotoCurrent : true,
				onSelect : function() {
					$("form").trigger("oninput");
				},
				changeMonth : true,
				changeYear : true,
				yearRange: '1970:2040',
				firstDay: 1
			}).on('keyup',
					function() {
						$(this).datepicker("hide");
						var date='';
						try {
							switch(locale) {
						    case 'de':
						    	date = $.datepicker.parseDate('dd.mm.yy', $(this).val());
						        break;
						    case 'en':
						    	date = $.datepicker.parseDate('mm/dd/yy', $(this).val());
						        break;
						    default:
						        break;
						    }
								var day = ("0" + (date.getDate())).slice(-2);
								var year = date.getFullYear();
								// JavaScript months are 0-11
								var month = ("0" + (date.getMonth() + 1))
										.slice(-2);
								$("#"+replaceId($(this).attr('id'))+"_alt").val(
										year + '-' + month + '-' + day);
						} catch (e) {
							$("#"+replaceId($(this).attr('id'))+"_alt").val('invalid date');
						}
					});
		 })
		);

function replaceId(oldId){
	return oldId.replace(/\./g,"\\.");
}<commit_msg>#7 change the trigger type, when date is selected<commit_after>$(document).ready(
		 $(".datepicker").each(function() {
			 locale = $('html').attr('lang');

		//	 $(replaceId($(this).attr('id'))).val($("#"+replaceId($(this).attr('id'))+"_alt").val());

			$.datepicker.setDefaults($.datepicker.regional[locale]);
			$(this).datepicker({
				altField :"#"+replaceId($(this).attr('id'))+"_alt",
				altFormat : "yy-mm-dd",
				gotoCurrent : true,
				onSelect : function() {
					$("form").trigger("submit");
				},
				changeMonth : true,
				changeYear : true,
				yearRange: '1970:2040',
				firstDay: 1
			}).on('keyup',
					function() {
						$(this).datepicker("hide");
						var date='';
						try {
							switch(locale) {
						    case 'de':
						    	date = $.datepicker.parseDate('dd.mm.yy', $(this).val());
						        break;
						    case 'en':
						    	date = $.datepicker.parseDate('mm/dd/yy', $(this).val());
						        break;
						    default:
						        break;
						    }
								var day = ("0" + (date.getDate())).slice(-2);
								var year = date.getFullYear();
								// JavaScript months are 0-11
								var month = ("0" + (date.getMonth() + 1))
										.slice(-2);
								$("#"+replaceId($(this).attr('id'))+"_alt").val(
										year + '-' + month + '-' + day);
						} catch (e) {
							$("#"+replaceId($(this).attr('id'))+"_alt").val('invalid date');
						}
					});
		 })
		);

function replaceId(oldId){
	return oldId.replace(/\./g,"\\.");
}<|endoftext|>