<commit_before>'use strict';

var dgram       = require('dgram')
  , Q           = require('q')
  , _           = require('underscore')
  , util        = require('util')
  , events      = require('events')
  , qtmrt       = require('./qtmrt')
  , writeUInt32 = require('./helpers').writeUInt32
  , mixin       = require('./helpers').mixin
  , Mangler     = require('./mangler')
  , Packet      = require('./packet')
  , Command     = require('./command')
  , Logger      = require('./logger')
;

_.str = require('underscore.string');

var Api = function(options) {
	this.net               = require('net');
	this.client            = null;
	this.response          = null;
	this.deferredResponse  = null;
	this.promiseQueue      = [];
	this.issuedCommands    = [];
	this.logger            = new Logger();
	this.mangler           = new Mangler();
	this.isStreaming       = false;
	this.currentPacketSize = false;

	events.EventEmitter.call(this);

	if (1 > arguments.length)
		options = {};

	this.options = _.defaults(options, {
		debug: false,
		frequency: 100,
		discoverPort: 22226,
	});

	this.frequency(this.options.frequency);
};

Api.prototype = (function()
{
	var bootstrap = function()
	{
		// Disable Nagle's algorithm.
		this.client.setNoDelay(true);

		this.client.on('data', function(chunk) {
			this.mangler.read(chunk, { fun: receivePacket, thisArg: this });
		}.bind(this));

		this.client.on('end', function() {
			this.logger.log('Disconnected', 'white', 'bold');
		}.bind(this));
	},

	setupUdp = function(port)
	{
		var s = dgram.createSocket('udp4');

		s.on('message', function(chunk) {
			this.mangler.read(chunk, { fun: receivePacket, thisArg: this });
		}.bind(this));

		s.bind(port, this.host, function() { });
	},

	log = function(msg, color, style)
	{
		this.logger.logPacket(msg, color, style);
	},

	receivePacket = function(data)
	{
		var packet = Packet.create(data)
		  , command = this.issuedCommands.pop()
		;

		if (qtmrt.COMMAND === packet.type)
			packet.type = qtmrt.COMMAND_RESPONSE;

		if (this.options.debug)
			this.logger.logPacket(packet);

		if (qtmrt.EVENT === packet.type)
		{
			if ('GetState' === command.data)
				this.promiseQueue.pop().resolve({ id: packet.eventId, name: packet.eventName });

			this.emit('event', packet.eventName, packet);
		}
		else if (qtmrt.XML === packet.type)
		{
			this.promiseQueue.pop().resolve(packet.toJson());
		}
		else if (qtmrt.C3D_FILE === packet.type)
		{
		}
		else if (qtmrt.COMMAND_RESPONSE === packet.type)
		{
			if (_.str.startsWith(command.data, 'ByteOrder'))
				this.promiseQueue.pop().resolve(/little endian/.test(packet.data) ? 'little endian' : 'big endian');

			else if (_.str.startsWith(command.data, 'QTMVersion'))
			{
				var human   = 'QTM ' + packet.data.replace('QTM Version is ', '').slice(0, -1)
				  , version = human.match(/QTM (\d+)\.(\d+) (?:(?:Beta)|(?:Alpha))? \(build (\d+)\)/)
				;
				this.promiseQueue.pop().resolve({ major: version[1], minor: version[2], build: version[3], human: human });
			}

			else
				this.promiseQueue.pop().resolve(packet);
		}
		else if (command && _.str.startsWith(command.data, 'GetCurrentFrame'))
		{
			this.promiseQueue.pop().resolve(packet.toJson());
		}
		else if (qtmrt.DATA !== packet.type)
		{
			this.promiseQueue.pop().resolve(packet);
		}
		else if (qtmrt.DATA === packet.type)
		{
			this.emit('frame', packet);
		}

	},

	isConnected = function()
	{
		if (_.isNull(this.client))
			return Q.reject(new Error('Not connected to QTM. Connect and try again.'));
	},

	connect = function(port, host, major, minor)
	{
		if (!_.isNull(this.client))
			return Q.reject();

		if (1 > arguments.length)
			port = 22223;

		if (2 > arguments.length)
			host = 'localhost';

		if (3 > arguments.length)
		{
			major = 1;
			minor = 12;
		}
		else
		{
			if (!_.isNumber(major))
				throw new TypeError('Major version must be a number');

			if (!_.isNumber(major))
				throw new TypeError('Minor version must be a number');
		}

		this.host = host;
		this.port = port;

		var self = this
		  , deferredCommand  = Q.defer()
		;

		var responsePromise = promiseResponse.call(this);

		if (this.options.debug)
			this.logger.log('Connecting to ' + host + ':' + port, 'white', 'bold');

		this.client = this.net.connect(port, host, function() { });
		this.issuedCommands.unshift('Connect');
		bootstrap.call(this);

		responsePromise
			.then(function(packet) {
				if ('QTM RT Interface connected\0' === packet.data.toString())
				{
					send.call(self, Command.version(major, minor))
						.then(function(data) {
							deferredCommand.resolve();
						})
						.catch(function(err) {
							deferredCommand.reject(new Error(err));
						});
				}
				else
				{
					deferredCommand.reject(new Error(packet.data.toString()));
				}
			})
			.catch(function(err) {
				console.log(err);
			});

		return deferredCommand.promise;
	},

	qtmVersion      = function() { return send.call(this, Command.qtmVersion()); },
	byteOrder       = function() { return send.call(this, Command.byteOrder()); },
	getState        = function() { return send.call(this, Command.getState()); },
	getParameters   = function() { return send.call(this, Command.getParameters.apply(Command, arguments)); },
	setParameters   = function() { return send.call(this, Command.setParameters.apply(Command, arguments)); },
	getCurrentFrame = function() { return send.call(this, Command.getCurrentFrame.apply(Command, arguments)); },
	releaseControl  = function() { return send.call(this, Command.releaseControl()); },
	newMeasurement  = function() { return send.call(this, Command.newMeasurement()); },
	close           = function() { return send.call(this, Command.close()); },
	start           = function() { return send.call(this, Command.start()); },
	stop            = function() { return send.call(this, Command.stop()); },
	trig            = function() { return send.call(this, Command.trig()); },

	// XXX: Not tested with C3D file reply.
	getCaptureC3D = function() { return send.call(this, Command.getCaptureC3D()); },
	// XXX: Not tested with QTM file reply.
	getCaptureQtm = function() { return send.call(this, Command.getCaptureQtm()); },

	streamFrames = function(options)
	{
		if (this.isStreaming)
			return Q.reject('Could not start streaming, already streaming');

		this.isStreaming = true;

		if (_.isUndefined(options.frequency))
			options.frequency = this.options.frequency;

		if (!_.isUndefined(options.udpPort) && (_.isUndefined(options.udpAddress) || 'localhost' === options.updAddress || '127.0.0.1' === options.udpAddress))
			setupUdp.call(this, options.udpPort);

		return send.call(this, Command.streamFrames.apply(Command, [options]));
	},

	stopStreaming = function()
	{
		if (!this.isStreaming)
		{
			this.logger.log('Cannot stop streaming, not currently streaming', 'red');
			return;
		}

		this.isStreaming = false;
		return send.call(this, Command.stopStreaming());
	},

	takeControl = function(pass)
	{
		if (!_.isUndefined(pass) && !_.isString(pass))
			throw new TypeError('Password must be a string');

		return send.call(this, Command.takeControl(pass));
	},

	load = function(filename)
	{
		if (1 > arguments.length)
			throw new TypeError('No filename specified');

		if (!_.isString(filename))
			throw new TypeError('Filename must be a string');

		return send.call(this, Command.load(filename));
	},

	save = function(filename, overwrite)
	{
		if (1 > arguments.length)
			throw new TypeError('No filename specified');

		if (!_.isString(filename))
			throw new TypeError('Filename must be a string');

		if (1 < arguments.length)
			overwrite = 'overwrite';

		return send.call(this, Command.save(filename, overwrite));
	},

	loadProject = function(projectPath)
	{
		if (1 > arguments.length)
			throw new TypeError('No project path specified');

		if (!_.isString(projectPath))
			throw new TypeError('Project path must be a string');

		return send.call(this, Command.loadProject(projectPath));
	},

	setQtmEvent = function(label)
	{
		if (1 > arguments.length)
			throw new TypeError('No label specified');

		if (!_.isString(label))
			throw new TypeError('Label must be a string');

		return send.call(this, Command.setQtmEvent(label));
	},

	send = function(command)
	{
		isConnected.call(this);
		var promise = Q.resolve();

		if (!_.str.startsWith(command.data, 'StreamFrames'))
			promise = promiseResponse.call(this);

		this.issuedCommands.unshift(command);

		command.isResponse = false;

		this.client.write(command.buffer, 'utf8', function(data) {
			if (this.options.debug)
				this.logger.logPacket(command);
		}.bind(this));

		return promise;
	},

	promiseResponse = function()
	{
		var deferredResponse = Q.defer();
		this.promiseQueue.unshift(deferredResponse);
		return deferredResponse.promise;
	},

	disconnect = function()
	{
		isConnected.call(this);
		this.client.end();
	},

	discover = function(port)
	{
		if (_.isUndefined(port))
			port = this.options.discoverPort;

		var server = dgram.createSocket('udp4')
		  , receivePort = port + 1
		  , self = this
		;

		server.on('error', function (err) {
			console.log('Server error:\n' + err.stack);
			server.close();
		});

		server.on('message', function (msg, rinfo) {
			writeUInt32(msg, 7, 4);

			if (self.options.debug)
				self.logger.logPacket(Packet.create(msg, rinfo.address, rinfo.port));
		});

		server.on('listening', function () {
			var address = server.address();
		});

		server.bind(receivePort);

		// Create discover packet.
		var buf = new Buffer(10);
		buf.writeUInt32LE(10, 0);
		buf.writeUInt32LE(7, 4);
		buf.writeUInt16BE(receivePort, 8);

		var client = dgram.createSocket('udp4')
		  //, address = 'ff02::1'
		  , address = '255.255.255.255'
		;

		client.bind();
		client.on('listening', function () {
			client.setBroadcast(true);
			client.send(buf, 0, buf.length, port, address, function(err, bytes) {
				client.close();
			});

			if (self.options.debug)
				self.logger.logPacket(Packet.create(buf));
		});
	},

	frequency = function(freq)
	{
		if (isNaN(freq) && freq !== 'AllFrames')
			throw new TypeError('Frequency must be a number or \'AllFrames\'');

		this.options.frequency = freq;
	};

	return {
		'log':              log,
		'connect':          connect,
		'qtmVersion':       qtmVersion,
		'byteOrder':        byteOrder,
		'getState':         getState,
		'getParameters':    getParameters,
		'setParameters':    setParameters,
		'getCurrentFrame':  getCurrentFrame,
		'stopStreaming':    stopStreaming,
		'streamFrames':     streamFrames,
		'takeControl':      takeControl,
		'releaseControl':   releaseControl,
		'newMeasurement':   newMeasurement,
		'close':            close,
		'start':            start,
		'stop':             stop,
		'load':             load,
		'save':             save,
		'loadProject':      loadProject,
		'getCaptureC3D':    getCaptureC3D,
		'getCaptureQtm':    getCaptureQtm,
		'trig':             trig,
		'setQtmEvent':      setQtmEvent,
		'disconnect':       disconnect,
		'discover':         discover,
		'frequency':        frequency,
	};
})();

mixin(Api.prototype, events.EventEmitter.prototype);

module.exports = Api;
<commit_msg>Fixed issue with no more data-event.<commit_after>'use strict';

var dgram       = require('dgram')
  , Q           = require('q')
  , _           = require('underscore')
  , util        = require('util')
  , events      = require('events')
  , qtmrt       = require('./qtmrt')
  , writeUInt32 = require('./helpers').writeUInt32
  , mixin       = require('./helpers').mixin
  , Mangler     = require('./mangler')
  , Packet      = require('./packet')
  , Command     = require('./command')
  , Logger      = require('./logger')
;

_.str = require('underscore.string');

var Api = function(options) {
	this.net               = require('net');
	this.client            = null;
	this.response          = null;
	this.deferredResponse  = null;
	this.promiseQueue      = [];
	this.issuedCommands    = [];
	this.logger            = new Logger();
	this.mangler           = new Mangler();
	this.isStreaming       = false;
	this.currentPacketSize = false;

	events.EventEmitter.call(this);

	if (1 > arguments.length)
		options = {};

	this.options = _.defaults(options, {
		debug: false,
		frequency: 100,
		discoverPort: 22226,
	});

	this.frequency(this.options.frequency);
};

Api.prototype = (function()
{
	var bootstrap = function()
	{
		// Disable Nagle's algorithm.
		this.client.setNoDelay(true);

		this.client.on('data', function(chunk) {
			this.mangler.read(chunk, { fun: receivePacket, thisArg: this });
		}.bind(this));

		this.client.on('end', function() {
			this.logger.log('Disconnected', 'white', 'bold');
		}.bind(this));
	},

	setupUdp = function(port)
	{
		var s = dgram.createSocket('udp4');

		s.on('message', function(chunk) {
			this.mangler.read(chunk, { fun: receivePacket, thisArg: this });
		}.bind(this));

		s.bind(port, this.host, function() { });
	},

	log = function(msg, color, style)
	{
		this.logger.logPacket(msg, color, style);
	},

	receivePacket = function(data)
	{
		var packet = Packet.create(data)
		  , command = packet.type === qtmrt.DATA ? null : this.issuedCommands.pop()
		;

		if (qtmrt.COMMAND === packet.type)
			packet.type = qtmrt.COMMAND_RESPONSE;

		if (this.options.debug)
			this.logger.logPacket(packet);

		if (qtmrt.EVENT === packet.type)
		{
			if ('GetState' === command.data)
				this.promiseQueue.pop().resolve({ id: packet.eventId, name: packet.eventName });

			this.emit('event', packet.eventName, packet);
		}
		else if (qtmrt.XML === packet.type)
		{
			this.promiseQueue.pop().resolve(packet.toJson());
		}
		else if (qtmrt.C3D_FILE === packet.type)
		{
		}
		else if (qtmrt.COMMAND_RESPONSE === packet.type)
		{
			if (_.str.startsWith(command.data, 'ByteOrder'))
				this.promiseQueue.pop().resolve(/little endian/.test(packet.data) ? 'little endian' : 'big endian');

			else if (_.str.startsWith(command.data, 'QTMVersion'))
			{
				var human   = 'QTM ' + packet.data.replace('QTM Version is ', '').slice(0, -1)
				  , version = human.match(/QTM (\d+)\.(\d+) (?:(?:Beta)|(?:Alpha))? \(build (\d+)\)/)
				;
				this.promiseQueue.pop().resolve({ major: version[1], minor: version[2], build: version[3], human: human });
			}

			else
				this.promiseQueue.pop().resolve(packet);
		}
		else if (command && _.str.startsWith(command.data, 'GetCurrentFrame'))
		{
			this.promiseQueue.pop().resolve(packet.toJson());
		}
		else if (qtmrt.DATA !== packet.type)
		{
			this.promiseQueue.pop().resolve(packet);
		}
		else if (qtmrt.DATA === packet.type)
		{
			this.emit('frame', packet);
		}

	},

	isConnected = function()
	{
		if (_.isNull(this.client))
			return Q.reject(new Error('Not connected to QTM. Connect and try again.'));
	},

	connect = function(port, host, major, minor)
	{
		if (!_.isNull(this.client))
			return Q.reject();

		if (1 > arguments.length)
			port = 22223;

		if (2 > arguments.length)
			host = 'localhost';

		if (3 > arguments.length)
		{
			major = 1;
			minor = 12;
		}
		else
		{
			if (!_.isNumber(major))
				throw new TypeError('Major version must be a number');

			if (!_.isNumber(major))
				throw new TypeError('Minor version must be a number');
		}

		this.host = host;
		this.port = port;

		var self = this
		  , deferredCommand  = Q.defer()
		;

		var responsePromise = promiseResponse.call(this);

		if (this.options.debug)
			this.logger.log('Connecting to ' + host + ':' + port, 'white', 'bold');

		this.client = this.net.connect(port, host, function() { });
		this.issuedCommands.unshift('Connect');
		bootstrap.call(this);

		responsePromise
			.then(function(packet) {
				if ('QTM RT Interface connected\0' === packet.data.toString())
				{
					send.call(self, Command.version(major, minor))
						.then(function(data) {
							deferredCommand.resolve();
						})
						.catch(function(err) {
							deferredCommand.reject(new Error(err));
						});
				}
				else
				{
					deferredCommand.reject(new Error(packet.data.toString()));
				}
			})
			.catch(function(err) {
				console.log(err);
			});

		return deferredCommand.promise;
	},

	qtmVersion      = function() { return send.call(this, Command.qtmVersion()); },
	byteOrder       = function() { return send.call(this, Command.byteOrder()); },
	getState        = function() { return send.call(this, Command.getState()); },
	getParameters   = function() { return send.call(this, Command.getParameters.apply(Command, arguments)); },
	setParameters   = function() { return send.call(this, Command.setParameters.apply(Command, arguments)); },
	getCurrentFrame = function() { return send.call(this, Command.getCurrentFrame.apply(Command, arguments)); },
	releaseControl  = function() { return send.call(this, Command.releaseControl()); },
	newMeasurement  = function() { return send.call(this, Command.newMeasurement()); },
	close           = function() { return send.call(this, Command.close()); },
	start           = function() { return send.call(this, Command.start()); },
	stop            = function() { return send.call(this, Command.stop()); },
	trig            = function() { return send.call(this, Command.trig()); },

	// XXX: Not tested with C3D file reply.
	getCaptureC3D = function() { return send.call(this, Command.getCaptureC3D()); },
	// XXX: Not tested with QTM file reply.
	getCaptureQtm = function() { return send.call(this, Command.getCaptureQtm()); },

	streamFrames = function(options)
	{
		if (this.isStreaming)
			return Q.reject('Could not start streaming, already streaming');

		this.isStreaming = true;

		if (_.isUndefined(options.frequency))
			options.frequency = this.options.frequency;

		if (!_.isUndefined(options.udpPort) && (_.isUndefined(options.udpAddress) || 'localhost' === options.updAddress || '127.0.0.1' === options.udpAddress))
			setupUdp.call(this, options.udpPort);

		return send.call(this, Command.streamFrames.apply(Command, [options]));
	},

	stopStreaming = function()
	{
		if (!this.isStreaming)
		{
			this.logger.log('Cannot stop streaming, not currently streaming', 'red');
			return;
		}

		this.isStreaming = false;
		return send.call(this, Command.stopStreaming());
	},

	takeControl = function(pass)
	{
		if (!_.isUndefined(pass) && !_.isString(pass))
			throw new TypeError('Password must be a string');

		return send.call(this, Command.takeControl(pass));
	},

	load = function(filename)
	{
		if (1 > arguments.length)
			throw new TypeError('No filename specified');

		if (!_.isString(filename))
			throw new TypeError('Filename must be a string');

		return send.call(this, Command.load(filename));
	},

	save = function(filename, overwrite)
	{
		if (1 > arguments.length)
			throw new TypeError('No filename specified');

		if (!_.isString(filename))
			throw new TypeError('Filename must be a string');

		if (1 < arguments.length)
			overwrite = 'overwrite';

		return send.call(this, Command.save(filename, overwrite));
	},

	loadProject = function(projectPath)
	{
		if (1 > arguments.length)
			throw new TypeError('No project path specified');

		if (!_.isString(projectPath))
			throw new TypeError('Project path must be a string');

		return send.call(this, Command.loadProject(projectPath));
	},

	setQtmEvent = function(label)
	{
		if (1 > arguments.length)
			throw new TypeError('No label specified');

		if (!_.isString(label))
			throw new TypeError('Label must be a string');

		return send.call(this, Command.setQtmEvent(label));
	},

	send = function(command)
	{
		isConnected.call(this);
		var promise = Q.resolve();

		// Don't expect a reply on the StreamFrames command.
		if (!_.str.startsWith(command.data, 'StreamFrames'))
			promise = promiseResponse.call(this);

		this.issuedCommands.unshift(command);

		command.isResponse = false;

		this.client.write(command.buffer, 'utf8', function(data) {
			if (this.options.debug)
				this.logger.logPacket(command);
		}.bind(this));

		return promise;
	},

	promiseResponse = function()
	{
		var deferredResponse = Q.defer();
		this.promiseQueue.unshift(deferredResponse);
		return deferredResponse.promise;
	},

	disconnect = function()
	{
		isConnected.call(this);
		this.client.end();
	},

	discover = function(port)
	{
		if (_.isUndefined(port))
			port = this.options.discoverPort;

		var server = dgram.createSocket('udp4')
		  , receivePort = port + 1
		  , self = this
		;

		server.on('error', function (err) {
			console.log('Server error:\n' + err.stack);
			server.close();
		});

		server.on('message', function (msg, rinfo) {
			writeUInt32(msg, 7, 4);

			if (self.options.debug)
				self.logger.logPacket(Packet.create(msg, rinfo.address, rinfo.port));
		});

		server.on('listening', function () {
			var address = server.address();
		});

		server.bind(receivePort);

		// Create discover packet.
		var buf = new Buffer(10);
		buf.writeUInt32LE(10, 0);
		buf.writeUInt32LE(7, 4);
		buf.writeUInt16BE(receivePort, 8);

		var client = dgram.createSocket('udp4')
		  //, address = 'ff02::1'
		  , address = '255.255.255.255'
		;

		client.bind();
		client.on('listening', function () {
			client.setBroadcast(true);
			client.send(buf, 0, buf.length, port, address, function(err, bytes) {
				client.close();
			});

			if (self.options.debug)
				self.logger.logPacket(Packet.create(buf));
		});
	},

	frequency = function(freq)
	{
		if (isNaN(freq) && freq !== 'AllFrames')
			throw new TypeError('Frequency must be a number or \'AllFrames\'');

		this.options.frequency = freq;
	};

	return {
		'log':              log,
		'connect':          connect,
		'qtmVersion':       qtmVersion,
		'byteOrder':        byteOrder,
		'getState':         getState,
		'getParameters':    getParameters,
		'setParameters':    setParameters,
		'getCurrentFrame':  getCurrentFrame,
		'stopStreaming':    stopStreaming,
		'streamFrames':     streamFrames,
		'takeControl':      takeControl,
		'releaseControl':   releaseControl,
		'newMeasurement':   newMeasurement,
		'close':            close,
		'start':            start,
		'stop':             stop,
		'load':             load,
		'save':             save,
		'loadProject':      loadProject,
		'getCaptureC3D':    getCaptureC3D,
		'getCaptureQtm':    getCaptureQtm,
		'trig':             trig,
		'setQtmEvent':      setQtmEvent,
		'disconnect':       disconnect,
		'discover':         discover,
		'frequency':        frequency,
	};
})();

mixin(Api.prototype, events.EventEmitter.prototype);

module.exports = Api;
<|endoftext|>


<commit_before>/*! colorful-background-css-generator 2014-09-12 */
function ColorfulBackgroundGenerator(){this.layers=[]}function ColorfulBackgroundLayer(a,b,c,d,e,f){void 0===a&&(a=45),this.degree=a,void 0===b&&(b=200),this.hue=b,void 0===c&&(c=100),this.saturation=c,void 0===d&&(d=70),this.lightness=d,void 0===e&&(e=0),this.positionColor=e,void 0===f&&(f=70),this.positionTransparency=f}ColorfulBackgroundGenerator.prototype.getNumberOfLayers=function(){return this.layers.length},ColorfulBackgroundGenerator.prototype.getLayerByIndex=function(a){return void 0===a?!1:a>=this.getNumberOfLayers()?!1:this.layers[a]},ColorfulBackgroundGenerator.prototype.addLayer=function(a,b){void 0===b||b>this.getNumberOfLayers()?this.layers.push(a):this.layers.splice(b,0,a)},ColorfulBackgroundGenerator.prototype.deleteLayer=function(a){this.layers.splice(a,1)},ColorfulBackgroundGenerator.prototype.getCSS=function(a,b){var c=this.getCSSProperty();return(void 0===b||b===!1)&&(c=this.getCSSProperty("-webkit-")+c),void 0===a||a===!1?c.trim():c},ColorfulBackgroundGenerator.prototype.getCSSProperty=function(a){for(var b="background:\n		",c=this.getNumberOfLayers(),d=c-1;d>=0;d--)b+=0===d?this.layers[d].getCSSProperty(!0,a):this.layers[d].getCSSProperty(!1,a);return b},ColorfulBackgroundGenerator.prototype.getCSSAsText=function(){return".colorful {\n	"+this.getCSS(!0)+"}"},ColorfulBackgroundGenerator.prototype.assignStyleToElementId=function(a){var b=document.getElementById(a);this.assignStyleToElement(b)},ColorfulBackgroundGenerator.prototype.assignStyleToElement=function(a){a.setAttribute("style",this.getCSS())},ColorfulBackgroundLayer.prototype.getCSSProperty=function(a,b){var c="";void 0!==b&&(c=b);var d=this.hue+", "+this.saturation+"%, "+this.lightness+"%";return c=c+"linear-gradient("+this.getDegreeForVendor(b)+"deg, hsla("+d+", 1) "+this.positionColor+"%, hsla("+d+", 0) "+this.positionTransparency+"%)",c+=void 0===a||a===!1?",\n		":";\n	"},ColorfulBackgroundLayer.prototype.getDegreeForVendor=function(a){if("-webkit-"===a){var b=360-parseInt(this.degree)+90;return b>=360&&(b-=360),b}return this.degree};<commit_msg>Added the MIT License.<commit_after>/*! colorful-background-css-generator 2014-09-12 */
/*
The MIT License (MIT)

Copyright (c) 2014 webcore-it

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function ColorfulBackgroundGenerator(){this.layers=[]}function ColorfulBackgroundLayer(a,b,c,d,e,f){void 0===a&&(a=45),this.degree=a,void 0===b&&(b=200),this.hue=b,void 0===c&&(c=100),this.saturation=c,void 0===d&&(d=70),this.lightness=d,void 0===e&&(e=0),this.positionColor=e,void 0===f&&(f=70),this.positionTransparency=f}ColorfulBackgroundGenerator.prototype.getNumberOfLayers=function(){return this.layers.length},ColorfulBackgroundGenerator.prototype.getLayerByIndex=function(a){return void 0===a?!1:a>=this.getNumberOfLayers()?!1:this.layers[a]},ColorfulBackgroundGenerator.prototype.addLayer=function(a,b){void 0===b||b>this.getNumberOfLayers()?this.layers.push(a):this.layers.splice(b,0,a)},ColorfulBackgroundGenerator.prototype.deleteLayer=function(a){this.layers.splice(a,1)},ColorfulBackgroundGenerator.prototype.getCSS=function(a,b){var c=this.getCSSProperty();return(void 0===b||b===!1)&&(c=this.getCSSProperty("-webkit-")+c),void 0===a||a===!1?c.trim():c},ColorfulBackgroundGenerator.prototype.getCSSProperty=function(a){for(var b="background:\n		",c=this.getNumberOfLayers(),d=c-1;d>=0;d--)b+=0===d?this.layers[d].getCSSProperty(!0,a):this.layers[d].getCSSProperty(!1,a);return b},ColorfulBackgroundGenerator.prototype.getCSSAsText=function(){return".colorful {\n	"+this.getCSS(!0)+"}"},ColorfulBackgroundGenerator.prototype.assignStyleToElementId=function(a){var b=document.getElementById(a);this.assignStyleToElement(b)},ColorfulBackgroundGenerator.prototype.assignStyleToElement=function(a){a.setAttribute("style",this.getCSS())},ColorfulBackgroundLayer.prototype.getCSSProperty=function(a,b){var c="";void 0!==b&&(c=b);var d=this.hue+", "+this.saturation+"%, "+this.lightness+"%";return c=c+"linear-gradient("+this.getDegreeForVendor(b)+"deg, hsla("+d+", 1) "+this.positionColor+"%, hsla("+d+", 0) "+this.positionTransparency+"%)",c+=void 0===a||a===!1?",\n		":";\n	"},ColorfulBackgroundLayer.prototype.getDegreeForVendor=function(a){if("-webkit-"===a){var b=360-parseInt(this.degree)+90;return b>=360&&(b-=360),b}return this.degree};
<|endoftext|>


<commit_before>'use strict';

/*jshint expr: true*/

const expect = require( 'chai' ).expect;

const MODULE_PATH = 'lib/event_types/api/index';

const vandium = require( '../../../../' );

const apiHandler = require( '../../../../' + MODULE_PATH );

describe( MODULE_PATH, function() {

    describe( 'handler', function() {

        it( 'normal operation', function( done ) {

            let handler = apiHandler();

            handler.GET( {}, function() { return 'get called'; });
            handler.DELETE( {}, function() { return 'delete called'; });

            handler.PUT( {

                body: {

                    name: vandium.types.string().trim().required()
                }

            }, ( evt ) => {

                expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                return 'put called';
            });

            let event = require( './put-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: {}, body: 'put called', isBase64Encoded: false } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with cookie', function( done ) {

            let handler = apiHandler();

            handler.PUT( {

                body: {

                    name: vandium.types.string().trim().required()
                }

            }, ( evt ) => {

                expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                expect( evt.cookies ).to.eql( {

                    firstcookie: 'chocolate',
                  secondcookie: 'chip',
                  thirdcookie: 'strawberry'
                });

                return 'put called';
            });

            let event = require( './put-with-cookies-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: {}, body: 'put called', isBase64Encoded: false } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with headers and cors', function( done ) {

            let handler = apiHandler();

            handler.PUT( {

                body: {

                    name: vandium.types.string().trim().required()
                }

            }, ( evt ) => {

                expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                return 'put called';
            });

            handler.headers( {

                header1: 'HEADER1',
                header2: 'HEADER2'
            });

            handler.cors( {

                allowOrigin: 'https://whatever.vandium.io',
                allowCredentials: true
            });

            let event = require( './put-event.json'  );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( {

                        statusCode: 200,
                        headers: {
                            header1: 'HEADER1',
                            header2: 'HEADER2',
                            "Access-Control-Allow-Credentials": "true",
                            "Access-Control-Allow-Origin": "https://whatever.vandium.io"
                        },
                        isBase64Encoded: false,
                        body: 'put called'
                    });

                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with base64 encoded binary', function( done ) {

            let handler = apiHandler();
            let sampleBase64Png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==';

            handler.GET( {}, ( evt ) => {
                return {
                    headers: {
                        'Content-Type': 'image/png'
                    },
                    isBase64Encoded: true,
                    body: sampleBase64Png
                }
            });

            let event = require( './get-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: { 'Content-Type': 'image/png'}, body: sampleBase64Png, isBase64Encoded: true } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with result containing a Buffer instance', function( done ) {

            let handler = apiHandler();
            let sampleBase64Png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==';

            handler.GET( () => {
                return {
                    headers: {
                        'Content-Type': 'image/png'
                    },
                    body: Buffer.from( sampleBase64Png, 'base64' )
                }
            });

            let event = require( './get-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: { 'Content-Type': 'image/png'}, body: sampleBase64Png, isBase64Encoded: true } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with result containing a Buffer instance', function( done ) {

            let handler = apiHandler();
            let sampleBase64Png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==';

            handler.header( 'Content-Type', 'image/png' )
                   .GET( () => {

                    return Buffer.from( sampleBase64Png, 'base64' );
                });

            let event = require( './get-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: { 'Content-Type': 'image/png'}, body: sampleBase64Png, isBase64Encoded: true } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'handle JWT failure', function( done ) {

            let handler = apiHandler()
                .jwt( {

                    algorithm: 'HS256',
                    key: 'secret'
                })
                .PUT( ( evt ) => {

                    expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                    return 'put called';
                });

            let event = require( './put-event.json'  );

            handler( event, {}, (err,result) => {

                try {

                    expect( result.statusCode ).to.equal( 403 );
                    expect( result.body ).to.equal( '{"type":"AuthenticationFailureError","message":"authentication error: missing jwt token"}' );

                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });
    });
});
<commit_msg>Added test for validation failure to ensure statusCode of 400 was being set<commit_after>'use strict';

/*jshint expr: true*/

const expect = require( 'chai' ).expect;

const MODULE_PATH = 'lib/event_types/api/index';

const vandium = require( '../../../../' );

const apiHandler = require( '../../../../' + MODULE_PATH );

describe( MODULE_PATH, function() {

    describe( 'handler', function() {

        it( 'normal operation', function( done ) {

            let handler = apiHandler();

            handler.GET( {}, function() { return 'get called'; });
            handler.DELETE( {}, function() { return 'delete called'; });

            handler.PUT( {

                body: {

                    name: vandium.types.string().trim().required()
                }

            }, ( evt ) => {

                expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                return 'put called';
            });

            let event = require( './put-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: {}, body: 'put called', isBase64Encoded: false } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with cookie', function( done ) {

            let handler = apiHandler();

            handler.PUT( {

                body: {

                    name: vandium.types.string().trim().required()
                }

            }, ( evt ) => {

                expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                expect( evt.cookies ).to.eql( {

                    firstcookie: 'chocolate',
                  secondcookie: 'chip',
                  thirdcookie: 'strawberry'
                });

                return 'put called';
            });

            let event = require( './put-with-cookies-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: {}, body: 'put called', isBase64Encoded: false } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with headers and cors', function( done ) {

            let handler = apiHandler();

            handler.PUT( {

                body: {

                    name: vandium.types.string().trim().required()
                }

            }, ( evt ) => {

                expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                return 'put called';
            });

            handler.headers( {

                header1: 'HEADER1',
                header2: 'HEADER2'
            });

            handler.cors( {

                allowOrigin: 'https://whatever.vandium.io',
                allowCredentials: true
            });

            let event = require( './put-event.json'  );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( {

                        statusCode: 200,
                        headers: {
                            header1: 'HEADER1',
                            header2: 'HEADER2',
                            "Access-Control-Allow-Credentials": "true",
                            "Access-Control-Allow-Origin": "https://whatever.vandium.io"
                        },
                        isBase64Encoded: false,
                        body: 'put called'
                    });

                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with base64 encoded binary', function( done ) {

            let handler = apiHandler();
            let sampleBase64Png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==';

            handler.GET( {}, ( evt ) => {
                return {
                    headers: {
                        'Content-Type': 'image/png'
                    },
                    isBase64Encoded: true,
                    body: sampleBase64Png
                }
            });

            let event = require( './get-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: { 'Content-Type': 'image/png'}, body: sampleBase64Png, isBase64Encoded: true } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with result containing a Buffer instance', function( done ) {

            let handler = apiHandler();
            let sampleBase64Png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==';

            handler.GET( () => {
                return {
                    headers: {
                        'Content-Type': 'image/png'
                    },
                    body: Buffer.from( sampleBase64Png, 'base64' )
                }
            });

            let event = require( './get-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: { 'Content-Type': 'image/png'}, body: sampleBase64Png, isBase64Encoded: true } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'normal operation, with result containing a Buffer instance', function( done ) {

            let handler = apiHandler();
            let sampleBase64Png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==';

            handler.header( 'Content-Type', 'image/png' )
                   .GET( () => {

                    return Buffer.from( sampleBase64Png, 'base64' );
                });

            let event = require( './get-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result ).to.eql( { statusCode: 200, headers: { 'Content-Type': 'image/png'}, body: sampleBase64Png, isBase64Encoded: true } );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'handle JWT failure', function( done ) {

            let handler = apiHandler()
                .jwt( {

                    algorithm: 'HS256',
                    key: 'secret'
                })
                .PUT( ( evt ) => {

                    expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                    return 'put called';
                });

            let event = require( './put-event.json'  );

            handler( event, {}, (err,result) => {

                try {

                    expect( result.statusCode ).to.equal( 403 );
                    expect( result.body ).to.equal( '{"type":"AuthenticationFailureError","message":"authentication error: missing jwt token"}' );

                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });

        it( 'validation failure', function( done ) {

            let handler = apiHandler();

            handler.GET( {}, function() { return 'get called'; });
            handler.DELETE( {}, function() { return 'delete called'; });

            handler.PUT( {

                body: {

                    name: vandium.types.string().trim().required(),
                    age: vandium.types.number().required()
                }

            }, ( evt ) => {

                expect( evt.body.name ).to.equal( 'John Doe' );     // event contains padded input

                return 'put called';
            });

            let event = require( './put-event.json' );

            handler( event, {}, (err,result) => {

                try {

                    expect( result.statusCode ).to.equal( 400 );
                    expect( result.body ).to.contain( '"type":"ValidationError"' );
                    expect( result.isBase64Encoded ).to.be.false;
                    expect( result.headers ).to.eql( {} );
                    done();
                }
                catch( e ) {

                    done( e );
                }
            });
        });
    });
});
<|endoftext|>


<commit_before>/**
 * Javie Package
 * ==========================================================
 *
 * @package     Javie
 * @require     underscore, console, jQuery/Zepto
 * @since       0.1.0
 * @author      Mior Muhammad Zaki <https://git.io/crynobone>
 * @license     MIT License
 */(function(){"use strict";var e=this;e.Javie={}}).call(this),function(){"use strict";var e,t,n,r;e=this,t={},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=t),exports.Events=t):("undefined"==typeof e.Javie&&(e.Javie={}),e.Javie.Events=t),n=e._,!n&&"undefined"!=typeof require&&(n=require("underscore"));if(!n)throw new Error("Expected Underscore.js not available");t.make=function(){var t,i;return i=this,!n.isNull(r)&&!n.isUndefined(r)?r:(t={},r={listener:function(r,i){if(!n.isFunction(i))throw new Error("Callback is not a function");if(n.isNull(t[r])||n.isUndefined(t[r]))t[r]=[];return t[r].push(i),{id:r,cb:i}},fire:function(r,i){var s,o;s=this,o=[];if(n.isNull(r))throw new Error("Event ID is not provided: ["+r+"]");return n.isNull(t[r])||n.isNull(t[r])?null:(n.each(t[r],function(t,n){o.push(t.apply(s,i||[]))}),o)},first:function s(e,r){var i,o,s;i=this,o=[];if(n.isNull(e))throw new Error("Event ID is not provided: ["+e+"]");return n.isNull(t[e])||n.isNull(t[e])?null:(s=t[e].slice(0,1),n.each(s,function(t,n){o.push(t.apply(i,r||[]))}),o[0])},until:function(r,i){var s,o;s=this,o=null;if(n.isNull(r))throw new Error("Event ID is not provided: ["+r+"]");return n.isNull(t[r])||n.isNull(t[r])?null:(n.each(t[r],function(t,r){n.isNull(o)&&(o=t.apply(s,i||[]))}),null)},flush:function(r){n.isUndefined(t[r])||(t[r]=null)},forget:function(r){var i,s,o;i=this,s=r.id,o=r.cb;if(!n.isString(s))throw new Error("Event ID is not provided: ["+s+"]");if(!n.isFunction(o))throw new Error("Callback is not a function");if(n.isNull(t[s]))throw new Error("No registered event found for ["+s+"]");n.each(t[s],function(n,r){n===o&&t[s].splice(r,1)})},clone:function(r){return{to:function(i){t[i]=n.clone(t[r])}}}},r)}}.call(this),function(e){"use strict";function s(e){return Array.prototype.slice.call(e)}var t,n,r,i;t=this,n={},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=n),exports.Logger=n):("undefined"==typeof t.Javie&&(t.Javie={}),t.Javie.Logger=n),r=t._,!r&&"undefined"!=typeof require&&(r=require("underscore"));if(!r)throw new Error("Expected Underscore.js not available");n.noConflict=function(){return t.Logger=previous,this},n.enabled=!1,n.ERROR="error",n.WARNING="warning",n.INFO="info",n.DEBUG="debug",n.LOG="log",n.enable=function(){this.enabled=!0},n.disable=function(){this.enabled=!1},n.status=function(){return this.enabled},n.make=function(){var n,o;return!r.isNull(i)&&!r.isUndefined(i)?i:(n=this,o=function(r,i){var o;if(n.enabled===!1)return null;o=s(arguments),r=o.shift(),o.length===1&&(o=o[0]);switch(r){case"info":e.info(o);break;case"debug":e.debug(o);break;case"warning":e.warn(o);break;case"error":e.error(o);break;case"log":e.log(o);break;default:e.log("["+r.toUpperCase()+"]",o)}},i={logs:[],info:function(){var t;return t=s(arguments),t.unshift(n.INFO),this.logs.push(t),o.apply(this,t),this},debug:function(){var t;return t=s(arguments),t.unshift(n.DEBUG),this.logs.push(t),o.apply(this,t),this},warning:function(){var t;return t=s(arguments),t.unshift(n.WARNING),this.logs.push(t),o.apply(this,t),this},error:function(){var t;return t=s(arguments),t.unshift(n.ERROR),this.logs.push(t),o.apply(this,t),this},log:function(){var t;return t=s(arguments),t.unshift(n.LOG),this.logs.push(t),o.apply(this,t),this},post:function u(){var e;return e=s(arguments),this.logs.push(e),u.apply(this,e),this}},i)}}.call(this),function(e){"use strict";function s(){return{id:"",type:"",start:null,end:null,total:null,message:""}}function o(e){var t,n;return t=(new Date).getTime(),n=parseInt(t/1e3,10),e?t/1e3:(t-n*1e3)/1e3+" "+n}var t,n,r,i;t=this,i={},n={},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=n),exports.Profiler=n):("undefined"==typeof t.Javie&&(t.Javie={}),t.Javie.Profiler=n),r=t._,!r&&"undefined"!=typeof require&&(r=require("underscore"));if(!r)throw new Error("Expected Underscore.js not available");n.enabled=!1,n.enable=function(){this.enabled=!0},n.disable=function(){this.enabled=!1},n.status=function(){return this.enabled},n.make=function(n){var u,a,f;if(e===undefined&&this.enabled===!0)throw new Error("console is not available.");if(r.isUndefined(n)||n==="")n="default";return i[n]!==undefined?i[n]:(a=this,f={logs:[],pair:{},startedAt:o(!0),time:function(n,i){var u,f;return r.isNull(n)&&(n=this.logs.length),a.enabled===!1?null:(f=s(),f.id=n,f.type="time",f.message=i.toString(),f.start=o(!0),r.isUndefined(this.pair["time."+n])?(this.logs.push(f),this.pair["time."+n]=this.logs.length-1):(u=this.pair["time."+n],this.logs[u]=f),e.time(n),n)},timeEnd:function(n,i){var f,l,c,h,p;r.isNull(n)&&(n=this.logs.length);if(a.enabled===!1)return;return r.isUndefined(this.pair["time."+n])?(p=s(),p.start=this.startedAt,u.isSet(i)&&(p.message=i),this.logs.push(p),this.pair["time."+n]=this.logs.length-1,p.id=n,p.type="time"):e.timeEnd(n),f=this.pair["time."+n],p=this.logs[f],c=p.end=o(!0),l=p.start,h=c-l,p.total=h,this.logs[f]=p,h},trace:function(){if(a.enabled===!1)return;e.trace()},output:function(n){var r,i,s,o;if(a.enabled===!1){if(n!==!0)return;a.enable()}r=this.logs,s=r.length;for(i=0;i<s;i+=1)o=r[i],"time"===o.type?e.info("%s: %s - %dms",o.id,o.message,Math.floor(o.total*1e3)):e.log(o.id,o.message)}},i[n]=f,i[n])}}.call(this,console);<commit_msg>Update javie.min.js<commit_after>/**
 * Javie Package
 * ==========================================================
 *
 * @package     Javie
 * @require     underscore, console, jQuery/Zepto
 * @since       0.1.0
 * @author      Mior Muhammad Zaki <https://git.io/crynobone>
 * @license     MIT License
 */(function(){"use strict";var e=this;e.Javie={}}).call(this),function(){"use strict";var e,t,n,r;e=this,t={},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=t),exports.Events=t):("undefined"==typeof e.Javie&&(e.Javie={}),e.Javie.Events=t),n=e._,!n&&"undefined"!=typeof require&&(n=require("underscore"));if(!n)throw new Error("Expected Underscore.js not available");t.make=function(){var t,i;return i=this,!n.isNull(r)&&!n.isUndefined(r)?r:(t={},r={listen:function(r,i){if(!n.isFunction(i))throw new Error("Callback is not a function");if(n.isNull(t[r])||n.isUndefined(t[r]))t[r]=[];return t[r].push(i),{id:r,cb:i}},listener:function(t,n){return this.listen(t,n)},fire:function(r,i){var s,o;s=this,o=[];if(n.isNull(r))throw new Error("Event ID is not provided: ["+r+"]");return n.isNull(t[r])||n.isNull(t[r])?null:(n.each(t[r],function(t,n){o.push(t.apply(s,i||[]))}),o)},first:function s(e,r){var i,o,s;i=this,o=[];if(n.isNull(e))throw new Error("Event ID is not provided: ["+e+"]");return n.isNull(t[e])||n.isNull(t[e])?null:(s=t[e].slice(0,1),n.each(s,function(t,n){o.push(t.apply(i,r||[]))}),o[0])},until:function(r,i){var s,o;s=this,o=null;if(n.isNull(r))throw new Error("Event ID is not provided: ["+r+"]");return n.isNull(t[r])||n.isNull(t[r])?null:(n.each(t[r],function(t,r){n.isNull(o)&&(o=t.apply(s,i||[]))}),null)},flush:function(r){n.isUndefined(t[r])||(t[r]=null)},forget:function(r){var i,s,o;i=this,s=r.id,o=r.cb;if(!n.isString(s))throw new Error("Event ID is not provided: ["+s+"]");if(!n.isFunction(o))throw new Error("Callback is not a function");if(n.isNull(t[s]))throw new Error("No registered event found for ["+s+"]");n.each(t[s],function(n,r){n===o&&t[s].splice(r,1)})},clone:function(r){return{to:function(i){t[i]=n.clone(t[r])}}}},r)}}.call(this),function(e){"use strict";function s(e){return Array.prototype.slice.call(e)}var t,n,r,i;t=this,n={},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=n),exports.Logger=n):("undefined"==typeof t.Javie&&(t.Javie={}),t.Javie.Logger=n),r=t._,!r&&"undefined"!=typeof require&&(r=require("underscore"));if(!r)throw new Error("Expected Underscore.js not available");n.noConflict=function(){return t.Logger=previous,this},n.enabled=!1,n.ERROR="error",n.WARNING="warning",n.INFO="info",n.DEBUG="debug",n.LOG="log",n.enable=function(){this.enabled=!0},n.disable=function(){this.enabled=!1},n.status=function(){return this.enabled},n.make=function(){var n,o;return!r.isNull(i)&&!r.isUndefined(i)?i:(n=this,o=function(r,i){var o;if(n.enabled===!1)return null;o=s(arguments),r=o.shift(),o.length===1&&(o=o[0]);switch(r){case"info":e.info(o);break;case"debug":e.debug(o);break;case"warning":e.warn(o);break;case"error":e.error(o);break;case"log":e.log(o);break;default:e.log("["+r.toUpperCase()+"]",o)}},i={logs:[],info:function(){var t;return t=s(arguments),t.unshift(n.INFO),this.logs.push(t),o.apply(this,t),this},debug:function(){var t;return t=s(arguments),t.unshift(n.DEBUG),this.logs.push(t),o.apply(this,t),this},warning:function(){var t;return t=s(arguments),t.unshift(n.WARNING),this.logs.push(t),o.apply(this,t),this},error:function(){var t;return t=s(arguments),t.unshift(n.ERROR),this.logs.push(t),o.apply(this,t),this},log:function(){var t;return t=s(arguments),t.unshift(n.LOG),this.logs.push(t),o.apply(this,t),this},post:function u(){var e;return e=s(arguments),this.logs.push(e),u.apply(this,e),this}},i)}}.call(this),function(e){"use strict";function s(){return{id:"",type:"",start:null,end:null,total:null,message:""}}function o(e){var t,n;return t=(new Date).getTime(),n=parseInt(t/1e3,10),e?t/1e3:(t-n*1e3)/1e3+" "+n}var t,n,r,i;t=this,i={},n={},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=n),exports.Profiler=n):("undefined"==typeof t.Javie&&(t.Javie={}),t.Javie.Profiler=n),r=t._,!r&&"undefined"!=typeof require&&(r=require("underscore"));if(!r)throw new Error("Expected Underscore.js not available");n.enabled=!1,n.enable=function(){this.enabled=!0},n.disable=function(){this.enabled=!1},n.status=function(){return this.enabled},n.make=function(n){var u,a,f;if(e===undefined&&this.enabled===!0)throw new Error("console is not available.");if(r.isUndefined(n)||n==="")n="default";return i[n]!==undefined?i[n]:(a=this,f={logs:[],pair:{},startedAt:o(!0),time:function(n,i){var u,f;return r.isNull(n)&&(n=this.logs.length),a.enabled===!1?null:(f=s(),f.id=n,f.type="time",f.message=i.toString(),f.start=o(!0),r.isUndefined(this.pair["time."+n])?(this.logs.push(f),this.pair["time."+n]=this.logs.length-1):(u=this.pair["time."+n],this.logs[u]=f),e.time(n),n)},timeEnd:function(n,i){var f,l,c,h,p;r.isNull(n)&&(n=this.logs.length);if(a.enabled===!1)return;return r.isUndefined(this.pair["time."+n])?(p=s(),p.start=this.startedAt,u.isSet(i)&&(p.message=i),this.logs.push(p),this.pair["time."+n]=this.logs.length-1,p.id=n,p.type="time"):e.timeEnd(n),f=this.pair["time."+n],p=this.logs[f],c=p.end=o(!0),l=p.start,h=c-l,p.total=h,this.logs[f]=p,h},trace:function(){if(a.enabled===!1)return;e.trace()},output:function(n){var r,i,s,o;if(a.enabled===!1){if(n!==!0)return;a.enable()}r=this.logs,s=r.length;for(i=0;i<s;i+=1)o=r[i],"time"===o.type?e.info("%s: %s - %dms",o.id,o.message,Math.floor(o.total*1e3)):e.log(o.id,o.message)}},i[n]=f,i[n])}}.call(this,console);
<|endoftext|>


<commit_before>// @see https://devcenter.heroku.com/articles/nodejs#write-your-app
var express = require('express')
  , fs      = require('fs') // node
  , gm      = require('gm')
  , http    = require('http') // node
  , https   = require('https') // node
  , mime    = require('mime') // express
  , url     = require('url') // node
  , app = express.createServer(express.logger())
  , mimeTypes = [
    'image/jpeg',
    'image/png',
    'image/gif',
    'image/jpg',
  ];

app.get('/', function (req, res, next) {
  //@todo Allow requests from authorized hosts only.

  var remote = req.param('url')
    , width = req.param('width')
    , height = req.param('height');

  // Require query string parameters.
  if (!remote || !width || !height) {
    return res.send('Expected url, width and height query string parameters', 404);
  }

  // Validate query string parameters.
  var parts = url.parse(remote);
  // @see http://nodejs.org/api/url.html#url_url
  if (['https:', 'http:'].indexOf(parts['protocol']) === -1) {
    return res.send('Expected url to use the HTTP or HTTPS protocol', 404);
  }
  if (!parts['hostname']) {
    return res.send('Expected url to include a hostname', 404);
  }
  if (isNaN(parseFloat(width))) {
    return res.send('Expected width to be an integer', 404);
  }
  if (isNaN(parseFloat(height))) {
    return res.send('Expected height to be an integer', 404);
  }

  var agent = parts['protocol'] === 'http:' ? http : https;

  // @see http://nodejs.org/api/http.html#http_http_get_options_callback
  agent.get(remote, function (res2) {
    // The remote image must return status code 200.
    // @see http://nodejs.org/api/http.html#http_response_statuscode
    if (res2.statusCode !== 200) {
      return res.send('Expected response code 200, got ' + res2.statusCode, 404);
    }

    // The remote image must be a valid content type.
    // @see http://nodejs.org/api/http.html#http_request_headers
    var mimeType = res2.headers['content-type'];
    if (mimeTypes.indexOf(mimeType) === -1) {
      return res.send('Expected content type ' + mimeTypes.join(', ') + ', got ' + mimeType, 404);
    }

    // @see https://github.com/aheckmann/gm#constructor
    gm(res2, 'image.' + mime.extension(mimeType))
    // @see http://www.imagemagick.org/Usage/thumbnails/#cut
    .resize(width, height + '^>')
    .gravity('Center')
    .extent(width, height)
    .stream(function (err, stdout, stderr) {
      if (err) return next(err);
      stderr.pipe(process.stderr);
      res.writeHead(200, {'Content-Type': mimeType});
      stdout.pipe(res);
    });
  }).on('error', next);
});

var port = process.env.PORT || 5000;
app.listen(port, function () {
  console.log('Listening on ' + port);
});
<commit_msg>use imagemagick<commit_after>// @see https://devcenter.heroku.com/articles/nodejs#write-your-app

var express = require('express')
  , fs      = require('fs') // node
  , gm      = require('gm')
  , http    = require('http') // node
  , https   = require('https') // node
  , mime    = require('mime') // express
  , url     = require('url') // node
  // @see http://aaronheckmann.posterous.com/graphicsmagick-on-heroku-with-nodejs
  , imageMagick = gm.subClass({imageMagick: true})
  , app = express.createServer(express.logger())
  , mimeTypes = [
    'image/jpeg',
    'image/png',
    'image/gif',
    'image/jpg',
  ];

app.get('/', function (req, res, next) {
  //@todo Allow requests from authorized hosts only.

  var remote = req.param('url')
    , width = req.param('width')
    , height = req.param('height');

  // Require query string parameters.
  if (!remote || !width || !height) {
    return res.send('Expected url, width and height query string parameters', 404);
  }

  // Validate query string parameters.
  var parts = url.parse(remote);
  // @see http://nodejs.org/api/url.html#url_url
  if (['https:', 'http:'].indexOf(parts['protocol']) === -1) {
    return res.send('Expected url to use the HTTP or HTTPS protocol', 404);
  }
  if (!parts['hostname']) {
    return res.send('Expected url to include a hostname', 404);
  }
  if (isNaN(parseFloat(width))) {
    return res.send('Expected width to be an integer', 404);
  }
  if (isNaN(parseFloat(height))) {
    return res.send('Expected height to be an integer', 404);
  }

  var agent = parts['protocol'] === 'http:' ? http : https;

  // @see http://nodejs.org/api/http.html#http_http_get_options_callback
  agent.get(remote, function (res2) {
    // The remote image must return status code 200.
    // @see http://nodejs.org/api/http.html#http_response_statuscode
    if (res2.statusCode !== 200) {
      return res.send('Expected response code 200, got ' + res2.statusCode, 404);
    }

    // The remote image must be a valid content type.
    // @see http://nodejs.org/api/http.html#http_request_headers
    var mimeType = res2.headers['content-type'];
    if (mimeTypes.indexOf(mimeType) === -1) {
      return res.send('Expected content type ' + mimeTypes.join(', ') + ', got ' + mimeType, 404);
    }

    // @see https://github.com/aheckmann/gm#constructor
    imageMagick(res2, 'image.' + mime.extension(mimeType))
    // @see http://www.imagemagick.org/Usage/thumbnails/#cut
    .resize(width, height + '^>')
    .gravity('Center')
    .extent(width, height)
    .stream(function (err, stdout, stderr) {
      if (err) return next(err);
      stderr.pipe(process.stderr);
      res.writeHead(200, {'Content-Type': mimeType});
      stdout.pipe(res);
    });
  }).on('error', next);
});

var port = process.env.PORT || 5000;
app.listen(port, function () {
  console.log('Listening on ' + port);
});
<|endoftext|>


<commit_before>/** @module api */
import Auth from './auth.js';

/**
 * Fetches a url using a stored access token, signing the user in
 * if no access token exists
 * @param {string} url The url to fetch
 * @return {Promise<Response>} Fetch response object
 */
const authenticatedFetch = async (url) => {
  const accessToken = Auth.getAccessToken();
  if (accessToken) {
    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${accessToken}`,
      },
    });

    if (!response.ok) {
      if (response.status == 401) {
        Auth.signIn();
      } else {
        throw new Error(await response.text());
      }
    }

    return response;
  } else {
    Auth.signIn();
  }
};

// TODO: Add ability to filter by search query, to
//       later implement with navigation views
// https://github.com/GoogleCloudPlatform/healthcare-api-dicom-viewer/issues/6
/**
 * Fetches a list of the user's google cloud project ids recursively
 * @param {string=} pageToken Page token to use for the request
 * @param {Array=} projects Projects fetched from a previous iteration
 * @return {Promise<Array<string>>} List of projects available to the user
 */
const fetchProjects = async (pageToken) => {
  const response = await gapi.client.cloudresourcemanager.projects.list({
    pageToken,
  });
  const data = response.result;
  const projects = data.projects;

  // If next page token is present in the response, fetch again and
  // push result to the current project list
  if (data.nextPageToken) {
    projects.push(...await fetchProjects(data.nextPageToken));

    // Ensure only the first iteration calls .map
    // by checking if pageToken was passed
    if (pageToken) {
      return projects;
    }
    return projects.map((project) => project.projectId);
  }

  if (pageToken) {
    return projects;
  }
  return projects.map((project) => project.projectId);
};

/**
 * Fetches a list of the possible location ids for a given project
 * @param {string} projectId Project id to search locations for
 * @return {Promise<Array<string>>} List of locations available for project
 */
const fetchLocations = async (projectId) => {
  const data = await gapi.client.healthcare.projects.locations.list({
    name: `projects/${projectId}`,
  });

  // Return a list of location Id's
  return data.result.locations.map((location) => location.locationId);
};

/**
 * Fetches a list of the datasets in a project location
 * @param {string} projectId Project id
 * @param {string} location Location
 * @return {Promise<Array<string>>} List of datasets available
 */
const fetchDatasets = async (projectId, location) => {
  // TODO: Handle page tokens
  const data = await gapi.client.healthcare.projects.locations.datasets.list({
    parent: `projects/${projectId}/locations/${location}`,
  });

  // Return a list of datasets by only using content of string after last '/'
  return data.result.datasets
      .map((dataset) => dataset.name.split('/').slice(-1)[0]);
};

/**
 * Fetches a list of the dicomStores in a dataset
 * @param {string} projectId Project ID
 * @param {string} location Location
 * @param {string} dataset Dataset
 * @return {Promise<Array<string>>} List of dicomStores available
 */
const fetchDicomStores = async (projectId, location, dataset) => {
  // TODO: Handle page tokens
  const data = await gapi.client.healthcare.projects.locations.datasets
      .dicomStores.list({
        parent: `projects/${projectId}/locations/${location}/` +
          `datasets/${dataset}`,
      });

  // Return a list of dicomStores by only using content of string after last '/'
  return data.result.dicomStores.map((dicomStore) =>
    dicomStore.name.split('/').slice(-1)[0]);
};

/**
 * Fetches a list of studies in a dicom store
 * @param {string} projectId Project ID
 * @param {string} location Location
 * @param {string} dataset Dataset
 * @param {string} dicomStore Dicom Store
 * @return {Promise<Array<Object>>} List of studies in the dicom store
 */
const fetchStudies =
    async (projectId, location, dataset, dicomStore) => {
  const data = await gapi.client.healthcare.projects.locations.datasets
      .dicomStores.searchForStudies({
        parent: `projects/${projectId}/locations/${location}/` +
    `datasets/${dataset}/dicomStores/${dicomStore}`,
        dicomWebPath: 'studies',
      });

  return data.result;
};

/**
 * Fetches a list of series in a study
 * @param {string} projectId Project ID
 * @param {string} location Location
 * @param {string} dataset Dataset
 * @param {string} dicomStore Dicom Store
 * @param {string} studyId Study UID
 * @return {Promise<Array<Object>>} List of series in the study
 */
const fetchSeries =
    async (projectId, location, dataset, dicomStore, studyId) => {
  const data = await gapi.client.healthcare.projects.locations.datasets
      .dicomStores.studies.searchForSeries({
        parent: `projects/${projectId}/locations/${location}/` +
    `datasets/${dataset}/dicomStores/${dicomStore}`,
        dicomWebPath: `studies/${studyId}/series`,
      });

  return data.result;
};

export {authenticatedFetch, fetchProjects, fetchLocations, fetchDatasets,
  fetchDicomStores, fetchStudies, fetchSeries};
<commit_msg>Removed uneccessary code in fetchProjects<commit_after>/** @module api */
import Auth from './auth.js';

/**
 * Fetches a url using a stored access token, signing the user in
 * if no access token exists
 * @param {string} url The url to fetch
 * @return {Promise<Response>} Fetch response object
 */
const authenticatedFetch = async (url) => {
  const accessToken = Auth.getAccessToken();
  if (accessToken) {
    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${accessToken}`,
      },
    });

    if (!response.ok) {
      if (response.status == 401) {
        Auth.signIn();
      } else {
        throw new Error(await response.text());
      }
    }

    return response;
  } else {
    Auth.signIn();
  }
};

// TODO: Add ability to filter by search query, to
//       later implement with navigation views
// https://github.com/GoogleCloudPlatform/healthcare-api-dicom-viewer/issues/6
/**
 * Fetches a list of the user's google cloud project ids recursively
 * @param {string=} pageToken Page token to use for the request
 * @param {Array=} projects Projects fetched from a previous iteration
 * @return {Promise<Array<string>>} List of projects available to the user
 */
const fetchProjects = async (pageToken) => {
  const response = await gapi.client.cloudresourcemanager.projects.list({
    pageToken,
  });
  const data = response.result;
  const projects = data.projects;

  // If next page token is present in the response, fetch again and
  // push result to the current project list
  if (data.nextPageToken) {
    projects.push(...await fetchProjects(data.nextPageToken));
  }

  // Ensure only the first iteration calls .map
  // by checking if pageToken was passed
  if (pageToken) {
    return projects;
  }
  return projects.map((project) => project.projectId);
};

/**
 * Fetches a list of the possible location ids for a given project
 * @param {string} projectId Project id to search locations for
 * @return {Promise<Array<string>>} List of locations available for project
 */
const fetchLocations = async (projectId) => {
  const data = await gapi.client.healthcare.projects.locations.list({
    name: `projects/${projectId}`,
  });

  // Return a list of location Id's
  return data.result.locations.map((location) => location.locationId);
};

/**
 * Fetches a list of the datasets in a project location
 * @param {string} projectId Project id
 * @param {string} location Location
 * @return {Promise<Array<string>>} List of datasets available
 */
const fetchDatasets = async (projectId, location) => {
  // TODO: Handle page tokens
  const data = await gapi.client.healthcare.projects.locations.datasets.list({
    parent: `projects/${projectId}/locations/${location}`,
  });

  // Return a list of datasets by only using content of string after last '/'
  return data.result.datasets
      .map((dataset) => dataset.name.split('/').slice(-1)[0]);
};

/**
 * Fetches a list of the dicomStores in a dataset
 * @param {string} projectId Project ID
 * @param {string} location Location
 * @param {string} dataset Dataset
 * @return {Promise<Array<string>>} List of dicomStores available
 */
const fetchDicomStores = async (projectId, location, dataset) => {
  // TODO: Handle page tokens
  const data = await gapi.client.healthcare.projects.locations.datasets
      .dicomStores.list({
        parent: `projects/${projectId}/locations/${location}/` +
          `datasets/${dataset}`,
      });

  // Return a list of dicomStores by only using content of string after last '/'
  return data.result.dicomStores.map((dicomStore) =>
    dicomStore.name.split('/').slice(-1)[0]);
};

/**
 * Fetches a list of studies in a dicom store
 * @param {string} projectId Project ID
 * @param {string} location Location
 * @param {string} dataset Dataset
 * @param {string} dicomStore Dicom Store
 * @return {Promise<Array<Object>>} List of studies in the dicom store
 */
const fetchStudies =
    async (projectId, location, dataset, dicomStore) => {
  const data = await gapi.client.healthcare.projects.locations.datasets
      .dicomStores.searchForStudies({
        parent: `projects/${projectId}/locations/${location}/` +
    `datasets/${dataset}/dicomStores/${dicomStore}`,
        dicomWebPath: 'studies',
      });

  return data.result;
};

/**
 * Fetches a list of series in a study
 * @param {string} projectId Project ID
 * @param {string} location Location
 * @param {string} dataset Dataset
 * @param {string} dicomStore Dicom Store
 * @param {string} studyId Study UID
 * @return {Promise<Array<Object>>} List of series in the study
 */
const fetchSeries =
    async (projectId, location, dataset, dicomStore, studyId) => {
  const data = await gapi.client.healthcare.projects.locations.datasets
      .dicomStores.studies.searchForSeries({
        parent: `projects/${projectId}/locations/${location}/` +
    `datasets/${dataset}/dicomStores/${dicomStore}`,
        dicomWebPath: `studies/${studyId}/series`,
      });

  return data.result;
};

export {authenticatedFetch, fetchProjects, fetchLocations, fetchDatasets,
  fetchDicomStores, fetchStudies, fetchSeries};
<|endoftext|>


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

	/**
	 * @typedef {object} luga.data.DetailSet.options
	 *
	 * @property {string}            id       Unique identifier. Required
	 * @property {luga.data.DataSet} dataSet  Master dataSet
	 */

	/**
	 * DetailSet class
	 * Register itself as observer of the passed dataSet and act as the details in a master/details scenario
	 *
	 * @param {luga.data.DetailSet.options} options
	 * @constructor
	 * @extends luga.Notifier
	 * @fires dataChanged
	 * @listens dataChanged
	 * @listens currentRowChanged
	 */
	luga.data.DetailSet = function(options){

		var CONST = {
			ERROR_MESSAGES: {
				INVALID_ID_PARAMETER: "Luga.DetailSet: id parameter is required",
				INVALID_DS_PARAMETER: "Luga.DetailSet: dataSet parameter is required"
			}
		};

		if(options.id === undefined){
			throw(CONST.ERROR_MESSAGES.INVALID_ID_PARAMETER);
		}
		if(options.dataSet === undefined){
			throw(CONST.ERROR_MESSAGES.INVALID_DS_PARAMETER);
		}

		luga.extend(luga.Notifier, this);

		/** @type {luga.data.DetailSet} */
		var self = this;

		this.id = options.id;
		this.dataSet = options.dataSet;
		this.dataSet.addObserver(this);

		/** @type {luga.data.DataSet.row} */
		this.row = null;

		luga.data.setDataSource(this.id, this);

		/**
		 * @returns {luga.data.DataSet.row}
		 */
		this.getContext = function(){
			return this.row;
		};

		this.fetchRow = function(){
			self.row = self.dataSet.getCurrentRow();
			this.notifyObservers(luga.data.CONST.EVENTS.DATA_CHANGED, {dataSource: this});
		};

		/* Events Handlers */

		/**
		 * @param {luga.data.dataSourceChanged} data
		 */
		this.onDataChangedHandler = function(data){
			self.fetchRow();
		};

		/**
		 * @param {luga.data.DataSet.currentRowChanged} data
		 */
		this.onCurrentRowChangedHandler = function(data){
			self.fetchRow();
		};

		/* Constructor */

		self.row = self.dataSet.getCurrentRow();

	};

}());<commit_msg>Data: DetailSet: JSDoc<commit_after>(function(){
	"use strict";

	/**
	 * @typedef {object} luga.data.DetailSet.options
	 *
	 * @property {string}            id       Unique identifier. Required
	 * @property {luga.data.DataSet} dataSet  Master dataSet
	 */

	/**
	 * DetailSet class
	 * Register itself as observer of the passed dataSet and act as the details in a master/details scenario
	 *
	 * @param {luga.data.DetailSet.options} options
	 * @constructor
	 * @extends luga.Notifier
	 * @fires dataChanged
	 * @listens dataChanged
	 * @listens currentRowChanged
	 */
	luga.data.DetailSet = function(options){

		var CONST = {
			ERROR_MESSAGES: {
				INVALID_ID_PARAMETER: "Luga.DetailSet: id parameter is required",
				INVALID_DS_PARAMETER: "Luga.DetailSet: dataSet parameter is required"
			}
		};

		if(options.id === undefined){
			throw(CONST.ERROR_MESSAGES.INVALID_ID_PARAMETER);
		}
		if(options.dataSet === undefined){
			throw(CONST.ERROR_MESSAGES.INVALID_DS_PARAMETER);
		}

		luga.extend(luga.Notifier, this);

		/** @type {luga.data.DetailSet} */
		var self = this;

		this.id = options.id;
		this.dataSet = options.dataSet;
		this.dataSet.addObserver(this);

		/** @type {luga.data.DataSet.row} */
		this.row = null;

		luga.data.setDataSource(this.id, this);

		/**
		 * @returns {luga.data.DataSet.row}
		 */
		this.getContext = function(){
			return this.row;
		};

		this.fetchRow = function(){
			self.row = self.dataSet.getCurrentRow();
			this.notifyObservers(luga.data.CONST.EVENTS.DATA_CHANGED, {dataSource: this});
		};

		/* Events Handlers */

		/**
		 * @param {luga.data.dataSourceChanged} data
		 */
		this.onDataChangedHandler = function(data){
			self.fetchRow();
		};

		/**
		 * @param {luga.data.DataSet.currentRowChanged} data
		 */
		this.onCurrentRowChangedHandler = function(data){
			self.fetchRow();
		};

		/* Fetch row without notifying observers */
		self.row = self.dataSet.getCurrentRow();

	};

}());<|endoftext|>


<commit_before>/**
 * Created by Wayne on 16/3/16.
 */

'use strict';

var tender = require('../controllers/tender'),
  driverFilter = require('../../../libraries/filters/driver'),
  tenderPayment = require('../controllers/tender_payment');

module.exports = function (app) {
  app.route('/tender/driver/getWechatPayToken').post(driverFilter.requireDriver, tenderPayment.getWechatPayToken);
  app.route('/tender/driver/test_notifiy_url').get(tenderPayment.test_notifiy_url);
  app.route('/tender/driver/test_notifiy_url').post(tenderPayment.test_notifiy_url);
};
<commit_msg>Update for test<commit_after>/**
 * Created by Wayne on 16/3/16.
 */

'use strict';

var tender = require('../controllers/tender'),
  driverFilter = require('../../../libraries/filters/driver'),
  tenderPayment = require('../controllers/tender_payment');

module.exports = function (app) {
  app.route('/tender/driver/getWechatPayToken').post(driverFilter.requireDriver, tenderPayment.getWechatPayToken);
  app.route('/tender/driver/test_notifiy_url').get(tenderPayment.test_notifiy_url);
  app.route('/tender/driver/test_notifiy_url').post(tenderPayment.test_notifiy_url);
  app.route('/tender/driver/wechatPayResult').post(driverFilter.requireDriver, tenderPayment.wechatPayResult);

};
<|endoftext|>


<commit_before>/**
 * @fileoverview Check for function args proper indentation.
 * @author uberVU
 * @copyright 2015 uberVU. All rights reserved.
 * See LICENSE file in root directory for full license.
 */
'use strict';

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

var rule = require('../../../lib/rules/indent-function-args'),

    RuleTester = require('eslint').RuleTester;

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

var ruleTester = new RuleTester();
ruleTester.run('indent-function-args', rule, {

  valid: [
    {
      code: 'foo(arg1, arg2);'
    },
    {
      code: 'foobar(arg1,\n' +
            '    arg2);'
    },
    {
      code: 'foo(arg1,\n' +
            '    arg2);'
    },
    {
      code: 'foobar(arg1,\n' +
            '    arg2,\n' +
            '    arg3);'
    },
    {
      code: 'foobar(arg1,\n' +
            '       arg2,\n' +
            '       arg3);'
    },
    {
      code: 'foobar(arg1,\n' +
            '       arg2, arg3,\n' +
            '       arg4,\n' +
            '       arg5);'
    },
    {
      code: 'var foo = bar(arg1, arg2,\n' +
            '    arg3, arg4);'
    },
    {
      code: 'foo({\n' +
            '  a: 2,\n' +
            '  b: 3\n' +
            '}, arg2);'
    }
  ],

  invalid: [
    {
      code: 'foobar(arg1,\n' +
            '    arg2,\n' +
            '       arg3);',
      errors: [{
        message: 'Indent at 4 spaces.'
      }]
    },
    {
      code: 'foobar(arg1,\n' +
            '       arg2,\n' +
            '    arg3);',
      errors: [{
        message: 'Indent at parent parenthesis.'
      }]
    },
    {
      code: 'var foo = bar(arg1, arg2,\n' +
            'arg3, arg4);',
      errors: [{
        message: 'Indent at 4 spaces or paren.'
      }]
    }
  ]
});
<commit_msg>Fix indent-function-args test file sytling #2<commit_after>/**
 * @fileoverview Check for function args proper indentation.
 * @author uberVU
 * @copyright 2015 uberVU. All rights reserved.
 * See LICENSE file in root directory for full license.
 */
'use strict';

var rule = require('../../../lib/rules/indent-function-args'),
    RuleTester = require('eslint').RuleTester;

var ruleTester = new RuleTester();
ruleTester.run('indent-function-args', rule, {
  valid: [{
    code: 'foo(arg1, arg2);'
  }, {
    code: 'foobar(arg1,\n' +
          '    arg2);'
  }, {
    code: 'foo(arg1,\n' +
          '    arg2);'
  }, {
    code: 'foobar(arg1,\n' +
          '    arg2,\n' +
          '    arg3);'
  }, {
    code: 'foobar(arg1,\n' +
          '       arg2,\n' +
          '       arg3);'
  }, {
    code: 'foobar(arg1,\n' +
          '       arg2, arg3,\n' +
          '       arg4,\n' +
          '       arg5);'
  }, {
    code: 'var foo = bar(arg1, arg2,\n' +
          '    arg3, arg4);'
  }, {
    code: 'foo({\n' +
          '  a: 2,\n' +
          '  b: 3\n' +
          '}, arg2);'
  }],
  invalid: [{
    code: 'foobar(arg1,\n' +
          '    arg2,\n' +
          '       arg3);',
    errors: [{
      message: 'Indent at 4 spaces.'
    }]
  }, {
    code: 'foobar(arg1,\n' +
          '       arg2,\n' +
          '    arg3);',
    errors: [{
      message: 'Indent at parent parenthesis.'
    }]
  }, {
    code: 'var foo = bar(arg1, arg2,\n' +
          'arg3, arg4);',
    errors: [{
      message: 'Indent at 4 spaces or paren.'
    }]
  }]
});
<|endoftext|>


<commit_before>// web.js
var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');

var app = express();

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost:27017/';
  // console.log(mongoUri);

app.use(logfmt.requestLogger());
app.use(express.urlencoded());
app.get('/', function(req, res) {
  res.sendfile('./main.html');
});

if (!global.db) {
    mongo.Db.connect(mongoUri, function (err, db) {
        if (!err) {
            global.db = db;
        } else {
            throw new Error(err);
        }
    });
}

app.get(/^\/([\d\w]+)$/, function(req, res) {
    db.collection('urls', function(er, collection) {
        collection.find({"short": req.params[0]}).toArray(function( err, docs) {
            if (docs.length) {
                res.redirect(docs[0].url);
            } else {
                res.send('Sorry not found.');
            }
        });
    });
});

app.get('/addurl/', function(req, res) {

    getSeqColl(getAndIncSeq);

    function getSeqColl(callback) {
        global.db.collection('ref_seq', function(err, collection) {
            if (!err) {
                console.log("didn't error in getSeqColl")
                callback(collection, getURLsColl);
            } else {
                throw new Error(err);
            }
        });
    }

    function getAndIncSeq(collection, callback) {
            collection.findAndModify({ _id: "seq" }, {}, { $inc: { seq: 1 }},
                                 {}, function(err, object) {
                if (!err) {
                    console.log("didn't error in getanincseq")
                    callback(req, res, collection, object, addNewShort);
                } else {
                    throw new Error(err);
                }
        });
	}

    function getURLsColl(object, callback) {
        global.db.collection('urls', function(err, collection) {
            console.log("appears to have gotten urls collection ok")
            callback(req, res, collection, genID(object.seq), sendToShortened);
        });
    }

	function addNewShort(req, res, collection, seq, callback) {
	        var url = req.query.url;
	        collection.insert({"short": seq, "url": url}, function() {
                console.log("succeeded in adding new short")
	            callback(seq);
	        });
	}

	function sendToShortened(link) {
	    res.send(genResponse(link));
	}

});

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});

function genResponse(link) {
    return 'here\'s your link: quiet-scrubland' +
            '-5884.herokuapp.com/'  + link + '
' +
            'github';
}

function genID(decimal, symbols) {
    if (typeof symbols === 'undefined' || !symbols.length) {
        var symbols = ['0','1','2','3','4','5','6','7','8',
                   '9','b','c','d','f','g','h',
                   'j','k','n','p','q',
                   'r','s','t','w','x','y','z'];
    }
    decimal = decimal * 25;

    function pow(power) {
        return Math.pow(symbols.length, power);
    }

    var numstr = '';
    var rem;
    var i = 0;
    while (true) {

        if ( decimal/pow(i+1) < 1) {
            break;
        }
        i++;

    }

    while ( i >= 0 ) {

        var leftMost = symbols[Math.floor(decimal / pow(i))];
        numstr += leftMost;
        decimal = decimal - pow(i) * Math.floor(decimal / pow(i));
        i--;
    }

    return numstr;
}<commit_msg>rewrite db write function<commit_after>// web.js
var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');

var app = express();

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost:27017/';
  // console.log(mongoUri);

app.use(logfmt.requestLogger());
app.use(express.urlencoded());
app.get('/', function(req, res) {
  res.sendfile('./main.html');
});

if (!global.db) {
    mongo.Db.connect(mongoUri, function (err, db) {
        if (!err) {
            global.db = db;
        } else {
            throw new Error(err);
        }
    });
}

app.get(/^\/([\d\w]+)$/, function(req, res) {
    db.collection('urls', function(er, collection) {
        collection.find({"short": req.params[0]}).toArray(function( err, docs) {
            if (docs.length) {
                res.redirect(docs[0].url);
            } else {
                res.send('Sorry not found.');
            }
        });
    });
});

app.get('/addurl/', function(req, res) {

    getSeqColl(getAndIncSeq);

    function getSeqColl(callback) {
        global.db.collection('ref_seq', function(err, collection) {
            if (!err) {
                console.log("didn't error in getSeqColl")
                callback(collection, getURLsColl);
            } else {
                throw new Error(err);
            }
        });
    }

    function getAndIncSeq(collection, callback) {
            collection.findAndModify({ _id: "seq" }, {}, { $inc: { seq: 1 }},
                                 {}, function(err, object) {
                if (!err) {
                    console.log("didn't error in getanincseq")
                    callback(req, res, collection, object, addNewShort);
                } else {
                    throw new Error(err);
                }
        });
	}

    function getURLsColl(object, callback) {
        global.db.collection('urls', function(err, collection) {
            console.log("appears to have gotten urls collection ok")
            callback(req, res, collection, genID(object.seq), sendToShortened);
        });
    }

	function addNewShort(req, res, collection, seq, callback) {
	        var url = req.query.url;
	        var writeObj = collection.insert({"short": seq, "url": url})

            if (writeObj.nInserted === 1) {
                console.log("succeeded in adding new short")
                callback(seq);
            }
	}

	function sendToShortened(link) {
	    res.send(genResponse(link));
	}

});

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});

function genResponse(link) {
    return 'here\'s your link: quiet-scrubland' +
            '-5884.herokuapp.com/'  + link + '
' +
            'github';
}

function genID(decimal, symbols) {
    if (typeof symbols === 'undefined' || !symbols.length) {
        var symbols = ['0','1','2','3','4','5','6','7','8',
                   '9','b','c','d','f','g','h',
                   'j','k','n','p','q',
                   'r','s','t','w','x','y','z'];
    }
    decimal = decimal * 25;

    function pow(power) {
        return Math.pow(symbols.length, power);
    }

    var numstr = '';
    var rem;
    var i = 0;
    while (true) {

        if ( decimal/pow(i+1) < 1) {
            break;
        }
        i++;

    }

    while ( i >= 0 ) {

        var leftMost = symbols[Math.floor(decimal / pow(i))];
        numstr += leftMost;
        decimal = decimal - pow(i) * Math.floor(decimal / pow(i));
        i--;
    }

    return numstr;
}<|endoftext|>


<commit_before>// Google Analyitcs
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-74403254-2', 'auto');
ga('send', 'pageview');

// Dynamicly add link[rel="import"]
function importHref(href, isAsync = false) {
  return new Promise((resolve, reject) => {
    const link = document.createElement('link');
    link.rel = 'import';
    link.href = href;
    if (isAsync) link.setAttribute('async', '');
    link.onload = e => resolve();
    link.onerror = e => reject(new Error(`Error loading import: ${e.target.href}`));
    document.head.appendChild(link);
  });
}

// Do we need this?

// // Cookie reader
// // From http://stackoverflow.com/questions/5639346
// (function(){
//   let cookies;
//   function readCookie(name,c,C,i){
//     if (cookies){ return cookies[name]; }
//     c = document.cookie.split('; ');
//     cookies = {};
//     for(i=c.length-1; i>=0; i--){
//       C = c[i].split('=');
//       cookies[C[0]] = C[1];
//     }
//     return cookies[name];
//   }
//   window.readCookie = readCookie;
// })();

// // Chrome test
// // From http://stackoverflow.com/questions/4565112
// function isChrome() {
//   const isChromium = window.chrome,
//       winNav = window.navigator,
//       vendorName = winNav.vendor,
//       isOpera = winNav.userAgent.indexOf("OPR") > -1,
//       isIEedge = winNav.userAgent.indexOf("Edge") > -1,
//       isIOSChrome = winNav.userAgent.match("CriOS");
//   if (isIOSChrome){
//     return true
//   } else if (isChromium !== null && isChromium !== undefined && vendorName === "Google Inc." && isOpera == false && isIEedge == false) {
//     return true
//   } else {
//     return false
//   }
// }<commit_msg>Added waitMs() function<commit_after>// Google Analyitcs
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-74403254-2', 'auto');
ga('send', 'pageview');

// Dynamicly add link[rel="import"]
function importHref(href, isAsync = false) {
  return new Promise((resolve, reject) => {
    const link = document.createElement('link');
    link.rel = 'import';
    link.href = href;
    if (isAsync) link.setAttribute('async', '');
    link.onload = e => resolve();
    link.onerror = e => reject(new Error(`Error loading import: ${e.target.href}`));
    document.head.appendChild(link);
  });
}

// Well, it's self-describing
function waitMs(time) {
  return new Promise(r => setTimeout(r, time));
}

// Do we need this?

// // Cookie reader
// // From http://stackoverflow.com/questions/5639346
// (function(){
//   let cookies;
//   function readCookie(name,c,C,i){
//     if (cookies){ return cookies[name]; }
//     c = document.cookie.split('; ');
//     cookies = {};
//     for(i=c.length-1; i>=0; i--){
//       C = c[i].split('=');
//       cookies[C[0]] = C[1];
//     }
//     return cookies[name];
//   }
//   window.readCookie = readCookie;
// })();

// // Chrome test
// // From http://stackoverflow.com/questions/4565112
// function isChrome() {
//   const isChromium = window.chrome,
//       winNav = window.navigator,
//       vendorName = winNav.vendor,
//       isOpera = winNav.userAgent.indexOf("OPR") > -1,
//       isIEedge = winNav.userAgent.indexOf("Edge") > -1,
//       isIOSChrome = winNav.userAgent.match("CriOS");
//   if (isIOSChrome){
//     return true
//   } else if (isChromium !== null && isChromium !== undefined && vendorName === "Google Inc." && isOpera == false && isIEedge == false) {
//     return true
//   } else {
//     return false
//   }
// }<|endoftext|>