<commit_before>'use babel';
'use strict';

import EventEmitter from 'events';
import stringArgv from 'string-argv';
import { stripIndents } from 'common-tags';
import escapeRegex from 'escape-string-regexp';
import FriendlyError from '../errors/friendly';

export default class CommandDispatcher extends EventEmitter {
	constructor(bot) {
		super();
		if(!bot) throw new Error('A bot must be specified.');
		this.bot = bot;
		this._serverCommandPatterns = {};
		this._results = {};
	}

	async handleMessage(message, oldMessage = null) {
		if(message.author.equals(this.bot.client.user)) return;

		// Make sure the bot is allowed to run in the channel, or the user is an admin
		if(message.server && !this.bot.storage.allowedChannels.isEmpty(message.server)
			&& !this.bot.storage.allowedChannels.exists(message.server, message.channel)
			&& !this.bot.permissions.isAdmin(message.server, message.author)) return;

		// Parse the message, and get the old result if it exists
		const [command, args, fromPattern, isCommandMessage] = this.parseMessage(message);
		const oldResult = oldMessage ? this._results[oldMessage.id] : null;

		// Run the command, or make an error message result
		let result;
		if(command) {
			if(!oldMessage || oldResult) result = await this.run(command, args, fromPattern, message);
		} else if(isCommandMessage) {
			result = { reply: [`Unknown command. Use ${this.bot.util.usage('help', message.server)} to view the list of all commands.`], editable: true };
		} else if(this.bot.config.values.nonCommandEdit) {
			result = { editable: true };
		}

		if(result) {
			// Change a plain or reply response into direct if there isn't a server
			if(!message.server) {
				if(!result.direct) result.direct = result.plain || result.reply;
				delete result.plain;
				delete result.reply;
			}

			// Update old messages or send new ones
			if(oldResult && (oldResult.plain || oldResult.reply || oldResult.direct)) {
				await this.updateMessagesForResult(message, result, oldResult);
			} else {
				await this.sendMessagesForResult(message, result);
			}

			// Cache the result
			if(this.bot.config.values.commandEditable > 0) {
				if(result.editable) {
					result.timeout = oldResult && oldResult.timeout ? oldResult.timeout : setTimeout(() => { delete this._results[message.id]; }, this.bot.config.values.commandEditable * 1000);
					this._results[message.id] = result;
				} else {
					delete this._results[message.id];
				}
			}
		}
	}

	async run(command, args, fromPattern, message) {
		const logInfo = {
			args: String(args),
			user: `${message.author.username}#${message.author.discriminator}`,
			userID: message.author.id,
			server: message.server ? message.server.name : null,
			serverID: message.server ? message.server.id : null
		};

		// Make sure the command is usable
		if(command.serverOnly && !message.server) {
			this.bot.logger.info(`Not running ${command.group}:${command.groupName}; server only.`, logInfo);
			return { reply: `The \`${command.name}\` command must be used in a server channel.`, editable: true };
		}
		if(command.isRunnable && !command.isRunnable(message)) {
			this.bot.logger.info(`Not running ${command.group}:${command.groupName}; not runnable.`, logInfo);
			return { reply: `You do not have permission to use the \`${command.name}\` command.`, editable: true };
		}

		// Run the command
		this.bot.logger.info(`Running ${command.group}:${command.groupName}.`, logInfo);
		try {
			const result = this.constructor.makeResultObject(await command.run(message, args, fromPattern));
			this.emit('commandRun', command, result, message, args, fromPattern);
			return result;
		} catch(err) {
			if(err instanceof FriendlyError) {
				return { reply: err.message, editable: true };
			} else {
				this.bot.logger.error(err);
				const owner = this.bot.config.values.owner ? message.client.users.get('id', this.bot.config.values.owner) : null;
				return {
					reply: stripIndents`
						An error occurred while running the command: \`${err.name}: ${err.message}\`
						${owner ? `Please contact ${owner.name}#${owner.discriminator}${this.bot.config.values.invite ? ` in this server: ${this.bot.config.values.invite}` : '.'}` : ''}
					`,
					editable: true
				};
			}
		}
	}

	async sendMessagesForResult(message, result) {
		const messages = await Promise.all([
			result.plain ? this.sendMessages(message, result.plain, 'plain') : null,
			result.reply ? this.sendMessages(message, result.reply, 'reply') : null,
			result.direct ? this.sendMessages(message, result.direct, 'direct') : null
		]);
		if(result.plain) result.normalMessages = messages[0];
		else if(result.reply) result.normalMessages = messages[1];
		if(result.direct) result.directMessages = messages[2];
	}

	async sendMessages(message, contents, type) {
		const sentMessages = [];
		for(const content of contents) {
			if(type === 'plain') sentMessages.push(await message.client.sendMessage(message, content));
			else if(type === 'reply') sentMessages.push(await message.reply(content));
			else if(type === 'direct') sentMessages.push(await message.client.sendMessage(message.author, content));
		}
		return sentMessages;
	}

	async updateMessagesForResult(message, result, oldResult) {
		// Update the messages
		const messages = await Promise.all([
			result.plain || result.reply ? this.updateMessages(message, oldResult.normalMessages, result.plain ? result.plain : result.reply, result.plain ? 'plain' : 'reply') : null,
			result.direct ? oldResult.direct ? this.updateMessages(message, oldResult.directMessages, result.direct, 'direct') : this.sendMessages(message, result.direct, 'direct') : null
		]);
		if(result.plain || result.reply) result.normalMessages = messages[0];
		if(result.direct) result.directMessages = messages[1];

		// Delete old messages if we're not using them
		if(!result.plain && !result.reply && (oldResult.plain || oldResult.reply)) for(const msg of oldResult.normalMessages) msg.delete();
		if(!result.direct && oldResult.direct) for(const msg of oldResult.directMessages) msg.delete();
	}

	async updateMessages(message, oldMessages, contents, type) {
		const updatedMessages = [];

		// Update/send messages
		for(let i = 0; i < contents.length; i++) {
			if(i < oldMessages.length) updatedMessages.push(await oldMessages[i].update(type === 'reply' ? `${message.author}, ${contents[i]}` : contents[i]));
			else updatedMessages.push((await this.sendMessages(message, [contents[i]], type))[0]);
		}

		// Delete extra old messages
		if(oldMessages.length > contents.length) {
			for(let i = oldMessages.length - 1; i >= contents.length; i--) oldMessages[i].delete();
		}

		return updatedMessages;
	}

	parseMessage(message) {
		// Find the command to run by patterns
		for(const command of this.bot.registry.commands) {
			if(!command.patterns) continue;
			for(const pattern of command.patterns) {
				const matches = pattern.exec(message.content);
				if(matches) return [command, matches, true, true];
			}
		}

		// Find the command to run with default command handling
		const patternIndex = message.server ? message.server.id : '-';
		if(!this._serverCommandPatterns[patternIndex]) this._serverCommandPatterns[patternIndex] = this._buildCommandPattern(message.server, message.client.user);
		let [command, args, isCommandMessage] = this.matchDefault(message, this._serverCommandPatterns[patternIndex], 2);
		if(!command && !message.server) [command, args, isCommandMessage] = this.matchDefault(message, unprefixedCommandPattern);
		if(command) return [command, args, false, true];

		return [null, null, false, isCommandMessage];
	}

	matchDefault(message, pattern, commandNameIndex = 1) {
		const matches = pattern.exec(message.content);
		if(!matches) return [null, null, false];

		const commandName = matches[commandNameIndex].toLowerCase();
		const command = this.bot.registry.commands.find(cmd => cmd.name === commandName || (cmd.aliases && cmd.aliases.some(alias => alias === commandName)));
		if(!command || command.disableDefault) return [null, null, true];

		const argString = message.content.substring(matches[1].length + (matches[2] ? matches[2].length : 0));
		let args;
		if(!('argsType' in command) || command.argsType === 'single') {
			args = [argString.trim()];
		} else if(command.argsType === 'multiple') {
			if(command.argsCount) {
				if(command.argsCount < 2) throw new RangeError(`Command ${command.group}:${command.groupName} argsCount must be at least 2.`);
				args = [];
				const newlinesReplaced = argString.trim().replace(newlinesPattern, newlinesReplacement);
				const argv = stringArgv(newlinesReplaced);
				if(argv.length > 0) {
					for(let i = 0; i < command.argsCount - 1; i++) args.push(argv.shift());
					if(argv.length > 0) args.push(argv.join(' ').replace(newlinesReplacementPattern, '\n').replace(extraNewlinesPattern, '\n\n'));
				}
			} else {
				args = stringArgv(argString);
			}
		} else {
			throw new Error(`Command ${command.group}:${command.groupName} argsType is not one of 'single' or 'multiple'.`);
		}

		return [command, args, true];
	}

	static makeResultObject(result) {
		if(typeof result !== 'object' || Array.isArray(result)) result = { reply: result };
		if(result.plain && result.reply) throw new Error('The command result may contain either "plain" or "reply", not both.');
		if(result.plain && !Array.isArray(result.plain)) result.plain = [result.plain];
		if(result.reply && !Array.isArray(result.reply)) result.reply = [result.reply];
		if(result.direct && !Array.isArray(result.direct)) result.direct = [result.direct];
		if(!('editable' in result)) result.editable = true;
		return result;
	}

	/**
	 * Creates a regular expression to match the command prefix and name in a message
	 * @param {?Server} server - A Discord.js Server instance of the server that the message is from
	 * @param {User} user - The Discord.js User instance of the bot
	 * @return {RegExp} Regular expression that matches a command prefix and name
	 */
	_buildCommandPattern(server, user) {
		let prefix = server ? this.bot.storage.settings.getValue(server, 'command-prefix', this.bot.config.values.commandPrefix) : this.bot.config.values.commandPrefix;
		if(prefix === 'none') prefix = '';
		const escapedPrefix = escapeRegex(prefix);
		const prefixPatternPiece = prefix ? `${escapedPrefix}\\s*|` : '';
		const pattern = new RegExp(`^(${prefixPatternPiece}<@!?${user.id}>\\s+(?:${escapedPrefix})?)([^\\s]+)`, 'i');
		this.bot.logger.info(`Server command pattern built.`, {
			server: server ? server.name : null,
			serverID: server ? server.id : null,
			prefix: prefix, pattern: pattern.source
		});
		return pattern;
	}
}

const unprefixedCommandPattern = /^([^\s]+)/i;
const newlinesPattern = /\n/g;
const newlinesReplacement = '{!~NL~!}';
const newlinesReplacementPattern = new RegExp(newlinesReplacement, 'g');
const extraNewlinesPattern = /\n{3,}/g;
<commit_msg>Fixed newlines in multiple args that aren't last<commit_after>'use babel';
'use strict';

import EventEmitter from 'events';
import stringArgv from 'string-argv';
import { stripIndents } from 'common-tags';
import escapeRegex from 'escape-string-regexp';
import FriendlyError from '../errors/friendly';

export default class CommandDispatcher extends EventEmitter {
	constructor(bot) {
		super();
		if(!bot) throw new Error('A bot must be specified.');
		this.bot = bot;
		this._serverCommandPatterns = {};
		this._results = {};
	}

	async handleMessage(message, oldMessage = null) {
		if(message.author.equals(this.bot.client.user)) return;

		// Make sure the bot is allowed to run in the channel, or the user is an admin
		if(message.server && !this.bot.storage.allowedChannels.isEmpty(message.server)
			&& !this.bot.storage.allowedChannels.exists(message.server, message.channel)
			&& !this.bot.permissions.isAdmin(message.server, message.author)) return;

		// Parse the message, and get the old result if it exists
		const [command, args, fromPattern, isCommandMessage] = this.parseMessage(message);
		const oldResult = oldMessage ? this._results[oldMessage.id] : null;

		// Run the command, or make an error message result
		let result;
		if(command) {
			if(!oldMessage || oldResult) result = await this.run(command, args, fromPattern, message);
		} else if(isCommandMessage) {
			result = { reply: [`Unknown command. Use ${this.bot.util.usage('help', message.server)} to view the list of all commands.`], editable: true };
		} else if(this.bot.config.values.nonCommandEdit) {
			result = { editable: true };
		}

		if(result) {
			// Change a plain or reply response into direct if there isn't a server
			if(!message.server) {
				if(!result.direct) result.direct = result.plain || result.reply;
				delete result.plain;
				delete result.reply;
			}

			// Update old messages or send new ones
			if(oldResult && (oldResult.plain || oldResult.reply || oldResult.direct)) {
				await this.updateMessagesForResult(message, result, oldResult);
			} else {
				await this.sendMessagesForResult(message, result);
			}

			// Cache the result
			if(this.bot.config.values.commandEditable > 0) {
				if(result.editable) {
					result.timeout = oldResult && oldResult.timeout ? oldResult.timeout : setTimeout(() => { delete this._results[message.id]; }, this.bot.config.values.commandEditable * 1000);
					this._results[message.id] = result;
				} else {
					delete this._results[message.id];
				}
			}
		}
	}

	async run(command, args, fromPattern, message) {
		const logInfo = {
			args: String(args),
			user: `${message.author.username}#${message.author.discriminator}`,
			userID: message.author.id,
			server: message.server ? message.server.name : null,
			serverID: message.server ? message.server.id : null
		};

		// Make sure the command is usable
		if(command.serverOnly && !message.server) {
			this.bot.logger.info(`Not running ${command.group}:${command.groupName}; server only.`, logInfo);
			return { reply: `The \`${command.name}\` command must be used in a server channel.`, editable: true };
		}
		if(command.isRunnable && !command.isRunnable(message)) {
			this.bot.logger.info(`Not running ${command.group}:${command.groupName}; not runnable.`, logInfo);
			return { reply: `You do not have permission to use the \`${command.name}\` command.`, editable: true };
		}

		// Run the command
		this.bot.logger.info(`Running ${command.group}:${command.groupName}.`, logInfo);
		try {
			const result = this.constructor.makeResultObject(await command.run(message, args, fromPattern));
			this.emit('commandRun', command, result, message, args, fromPattern);
			return result;
		} catch(err) {
			if(err instanceof FriendlyError) {
				return { reply: err.message, editable: true };
			} else {
				this.bot.logger.error(err);
				const owner = this.bot.config.values.owner ? message.client.users.get('id', this.bot.config.values.owner) : null;
				return {
					reply: stripIndents`
						An error occurred while running the command: \`${err.name}: ${err.message}\`
						${owner ? `Please contact ${owner.name}#${owner.discriminator}${this.bot.config.values.invite ? ` in this server: ${this.bot.config.values.invite}` : '.'}` : ''}
					`,
					editable: true
				};
			}
		}
	}

	async sendMessagesForResult(message, result) {
		const messages = await Promise.all([
			result.plain ? this.sendMessages(message, result.plain, 'plain') : null,
			result.reply ? this.sendMessages(message, result.reply, 'reply') : null,
			result.direct ? this.sendMessages(message, result.direct, 'direct') : null
		]);
		if(result.plain) result.normalMessages = messages[0];
		else if(result.reply) result.normalMessages = messages[1];
		if(result.direct) result.directMessages = messages[2];
	}

	async sendMessages(message, contents, type) {
		const sentMessages = [];
		for(const content of contents) {
			if(type === 'plain') sentMessages.push(await message.client.sendMessage(message, content));
			else if(type === 'reply') sentMessages.push(await message.reply(content));
			else if(type === 'direct') sentMessages.push(await message.client.sendMessage(message.author, content));
		}
		return sentMessages;
	}

	async updateMessagesForResult(message, result, oldResult) {
		// Update the messages
		const messages = await Promise.all([
			result.plain || result.reply ? this.updateMessages(message, oldResult.normalMessages, result.plain ? result.plain : result.reply, result.plain ? 'plain' : 'reply') : null,
			result.direct ? oldResult.direct ? this.updateMessages(message, oldResult.directMessages, result.direct, 'direct') : this.sendMessages(message, result.direct, 'direct') : null
		]);
		if(result.plain || result.reply) result.normalMessages = messages[0];
		if(result.direct) result.directMessages = messages[1];

		// Delete old messages if we're not using them
		if(!result.plain && !result.reply && (oldResult.plain || oldResult.reply)) for(const msg of oldResult.normalMessages) msg.delete();
		if(!result.direct && oldResult.direct) for(const msg of oldResult.directMessages) msg.delete();
	}

	async updateMessages(message, oldMessages, contents, type) {
		const updatedMessages = [];

		// Update/send messages
		for(let i = 0; i < contents.length; i++) {
			if(i < oldMessages.length) updatedMessages.push(await oldMessages[i].update(type === 'reply' ? `${message.author}, ${contents[i]}` : contents[i]));
			else updatedMessages.push((await this.sendMessages(message, [contents[i]], type))[0]);
		}

		// Delete extra old messages
		if(oldMessages.length > contents.length) {
			for(let i = oldMessages.length - 1; i >= contents.length; i--) oldMessages[i].delete();
		}

		return updatedMessages;
	}

	parseMessage(message) {
		// Find the command to run by patterns
		for(const command of this.bot.registry.commands) {
			if(!command.patterns) continue;
			for(const pattern of command.patterns) {
				const matches = pattern.exec(message.content);
				if(matches) return [command, matches, true, true];
			}
		}

		// Find the command to run with default command handling
		const patternIndex = message.server ? message.server.id : '-';
		if(!this._serverCommandPatterns[patternIndex]) this._serverCommandPatterns[patternIndex] = this._buildCommandPattern(message.server, message.client.user);
		let [command, args, isCommandMessage] = this.matchDefault(message, this._serverCommandPatterns[patternIndex], 2);
		if(!command && !message.server) [command, args, isCommandMessage] = this.matchDefault(message, /^([^\s]+)/i);
		if(command) return [command, args, false, true];

		return [null, null, false, isCommandMessage];
	}

	matchDefault(message, pattern, commandNameIndex = 1) {
		const matches = pattern.exec(message.content);
		if(!matches) return [null, null, false];

		const commandName = matches[commandNameIndex].toLowerCase();
		const command = this.bot.registry.commands.find(cmd => cmd.name === commandName || (cmd.aliases && cmd.aliases.some(alias => alias === commandName)));
		if(!command || command.disableDefault) return [null, null, true];

		const argString = message.content.substring(matches[1].length + (matches[2] ? matches[2].length : 0));
		let args;
		if(!('argsType' in command) || command.argsType === 'single') {
			args = [argString.trim()];
		} else if(command.argsType === 'multiple') {
			if(command.argsCount) {
				if(command.argsCount < 2) throw new RangeError(`Command ${command.group}:${command.groupName} argsCount must be at least 2.`);
				args = [];
				const argv = stringArgv(argString.trim().replace(/\n/g, '{!~NL~!}'));
				if(argv.length === 0) return [command, args, true];
				for(let i = 0; i < command.argsCount - 1; i++) {
					if(!argv[i].includes('{!~NL~!}')) continue;
					const fixed = argv[i].replace(/(?:{!~NL~!}){2,}/g, '{!~NL~!}').split('{!~NL~!}');
					argv.shift();
					argv.unshift(...fixed);
				}
				for(let i = 0; i < command.argsCount - 1; i++) args.push(argv.shift());
				if(argv.length > 0) args.push(argv.join(' ').replace(/{!~NL~!}/g, '\n').replace(/\n{3,}/g, '\n\n'));
			} else {
				args = stringArgv(argString);
			}
		} else {
			throw new Error(`Command ${command.group}:${command.groupName} argsType is not one of 'single' or 'multiple'.`);
		}

		return [command, args, true];
	}

	static makeResultObject(result) {
		if(typeof result !== 'object' || Array.isArray(result)) result = { reply: result };
		if(result.plain && result.reply) throw new Error('The command result may contain either "plain" or "reply", not both.');
		if(result.plain && !Array.isArray(result.plain)) result.plain = [result.plain];
		if(result.reply && !Array.isArray(result.reply)) result.reply = [result.reply];
		if(result.direct && !Array.isArray(result.direct)) result.direct = [result.direct];
		if(!('editable' in result)) result.editable = true;
		return result;
	}

	/**
	 * Creates a regular expression to match the command prefix and name in a message
	 * @param {?Server} server - A Discord.js Server instance of the server that the message is from
	 * @param {User} user - The Discord.js User instance of the bot
	 * @return {RegExp} Regular expression that matches a command prefix and name
	 */
	_buildCommandPattern(server, user) {
		let prefix = server ? this.bot.storage.settings.getValue(server, 'command-prefix', this.bot.config.values.commandPrefix) : this.bot.config.values.commandPrefix;
		if(prefix === 'none') prefix = '';
		const escapedPrefix = escapeRegex(prefix);
		const prefixPatternPiece = prefix ? `${escapedPrefix}\\s*|` : '';
		const pattern = new RegExp(`^(${prefixPatternPiece}<@!?${user.id}>\\s+(?:${escapedPrefix})?)([^\\s]+)`, 'i');
		this.bot.logger.info(`Server command pattern built.`, {
			server: server ? server.name : null,
			serverID: server ? server.id : null,
			prefix: prefix, pattern: pattern.source
		});
		return pattern;
	}
}
<|endoftext|>


<commit_before>var Epoll = require('../build/Release/epoll').Epoll,
  fs = require('fs'),
  valuefd = fs.openSync('/sys/class/gpio/gpio18/value', 'r'),
  buffer = new Buffer(1),
  count = 0,
  poller;

poller = new Epoll(function (err, fd, events) {
  if (err) throw err;

  fs.readSync(fd, buffer, 0, 1, 0);
  console.log('button pressed, value is ' + buffer.toString());

  count++;
  if (count === 20) {
    poller.remove(fd).close();
  }
});

fs.readSync(valuefd, buffer, 0, 1, 0);
poller.add(valuefd, Epoll.EPOLLPRI);

<commit_msg>improved example<commit_after>var Epoll = require('../build/Release/epoll').Epoll,
  fs = require('fs'),
  valuefd = fs.openSync('/sys/class/gpio/gpio18/value', 'r'),
  buffer = new Buffer(1);

var poller = new Epoll(function (err, fd, events) {
  fs.readSync(fd, buffer, 0, 1, 0);
  console.log(buffer.toString() === '1' ? 'pressed' : 'released');
});

fs.readSync(valuefd, buffer, 0, 1, 0);
poller.add(valuefd, Epoll.EPOLLPRI);

setTimeout(function () {
  poller.remove(valuefd).close;
}, 30000);

<|endoftext|>


<commit_before>/*
Copyright 2012 Adobe Systems Inc.;
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var file = function (path) {
    if (path.split('/').length > 1) {
        sep = '/';
    } else if (path.split('\\').length > 1) {
        sep = '\\';
    } else {
        throw new Error('ERROR: the separator in test result file path is neither "/" nor "\\".');
    }
    return path.split(sep).pop().split('.')[0];
};

var submitData = function (stdout, path, args, destination) {
	var querystring = require('querystring');
	var http        = require('http');
	var fs          = require('fs');
	var parse       = require('./csvToJSON');
	var postOptions = require('./settings');

	var post_data = {};

	parse(path, function (j) {
		post_data = {
			resultName : j
		};

		var version = stdout.split(' ');

		post_data.commit = version[0];
		post_data.date   = version[1];
		post_data.test   = args.test || file(path);
		post_data.device = args.device || 'device?';

		post_data = querystring.stringify({data : JSON.stringify(post_data)});

		post_options = postOptions(post_data.length);
		if (destination.host && destination.port) {
			var location = destination.host.split('/');

			post_options.host = location.shift();
			post_options.path = '/' + location.join('/');
			post_options.port = destination.port;
		}

		// Set up the request
		var post_req = http.request(post_options, function(res) {
			res.setEncoding('utf8');
			res.on('data', function(chunk) {
				console.log(chunk);
			});
		});

		// post the data
		post_req.write(post_data);
		post_req.end();

	});

};

module.exports = submitData;<commit_msg>updated submit tool for utc time<commit_after>/*
Copyright 2012 Adobe Systems Inc.;
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var file = function (path) {
    if (path.split('/').length > 1) {
        sep = '/';
    } else if (path.split('\\').length > 1) {
        sep = '\\';
    } else {
        throw new Error('ERROR: the separator in test result file path is neither "/" nor "\\".');
    }
    return path.split(sep).pop().split('.')[0];
};

var submitData = function (stdout, path, args, destination) {
	var querystring = require('querystring');
	var http        = require('http');
	var fs          = require('fs');
	var parse       = require('./csvToJSON');
	var postOptions = require('./settings');

	var post_data = {};

	parse(path, function (j) {
		post_data = {
			resultName : j
		};

		var version = stdout.split(' ');

		post_data.commit = version.shift();
		post_data.date   = version.join(' ');
		post_data.test   = args.test || file(path);
		post_data.device = args.device || 'device?';

		post_data = querystring.stringify({data : JSON.stringify(post_data)});

		post_options = postOptions(post_data.length);
		if (destination.host && destination.port) {
			var location = destination.host.split('/');

			post_options.host = location.shift();
			post_options.path = '/' + location.join('/');
			post_options.port = destination.port;
		}

		// Set up the request
		var post_req = http.request(post_options, function(res) {
			res.setEncoding('utf8');
			res.on('data', function(chunk) {
				console.log(chunk);
			});
		});

		// post the data
		post_req.write(post_data);
		post_req.end();

	});

};

module.exports = submitData;<|endoftext|>


<commit_before>
// Show Page

function showInitialPage() {
	window.pageController.reset();
    var page = buildPage();
    createInitialPage(page);
}

function showLastPage() {
    removeFirstPage();

    var page = buildPage();

    if (activePage().is(':visible')) {
        createLastPage(page);
    }
    else {
        createInitialPage(page);
    }
}

function showFirstPage() {
    removeLastPage();

    var page = buildPage();

    if (activePage().is(':visible')) {
        createFirstPage(page);
    }
    else {
        createInitialPage(page);
    }
}

// Create Pages

function createInitialPage(data) {
    var p = $(data);
    p.appendTo($.mobile.pageContainer);
    $.mobile.pageContainer.pagecontainer('change', p, {
        transition: 'none'
    });
}

function createFirstPage(data) {
    if (!canDoPrev()) {
        activePage().before(data);
    } else {
        getFirst().before(data);
    }
    $.mobile.pageContainer.pagecontainer('change', getFirst().last(), {
	    transition: 'slide'
    });
}

function createLastPage(data) {
    if (!canDoNext()) {
        activePage().after(data);
    } else {
        getLast().after(data);
    }
    $.mobile.pageContainer.pagecontainer('change', getLast().last(), {
        transition: 'slide',
        reverse: true
    });
}

// Remove Pages

function removeFirstPage() {
    if (window.pageController.max <= $('[data-role=page]').length) {
        var page = getFirst();
        if(page.length === 0) {
            page = activePage();
            var active_page = page.next('[data-role=page]');
	        $.mobile.pageContainer.pagecontainer('change', active_page, {
		        transition: 'none'
	        });

        }
        page.remove();
    }
}

function removeLastPage() {
    if (window.pageController.max <= $('[data-role=page]').length) {
        var page = getLast();
        if(page.length === 0) {
            page = activePage();
            var active_page = page.prev('[data-role=page]');
	        $.mobile.pageContainer.pagecontainer('change', active_page, {
		        transition: 'none'
	        });

        }
        page.remove();
    }
}

// Page Controller

window.pageController = {
    first : 0,
	current : 0,
	max : 5,
    reset: function () {
        this.first = 0;
        this.current = 0;
		this.max = 5;
    },
    isLastPage: function () {
        console.log('isLastPage: ' + (window.pageController.current <= 0));
        return (window.pageController.current <= 0);
    },
    isFirstPage: function () {
        console.log('isFirstPage: ' + (window.lj_conf.number != window.lj_conf.count));
        return (window.lj_conf.number != window.lj_conf.count);
    }
};

// Create page

function createPageId() {
	return '"page_' + window.pageController.current + '"';
}

function createPageTitle() {
	return '"Page ' + window.pageController.current + ' - ' + getJournalPageTitle() + '"';
}

function getJournalPageTitle() {
    var date = window.lj_conf.getPageDate(window.pageController.current);
    var d = new Date(date);
    var title =  window.lj_conf.journal + ' ' + $.format.date(d, 'dd-MMM-yyyy hh:mm p');
    return title;
}

function createPageNumber() {
	return '"' + window.pageController.current + '"';
}

function buildPage() {
	var s = '';
	s += '
';
	s += '
';
	s += '

';
	s += '
';
	s += '
';
	return s;
}
<commit_msg>Correct page title<commit_after>
// Show Page

function showInitialPage() {
	window.pageController.reset();
    var page = buildPage();
    createInitialPage(page);
}

function showLastPage() {
    removeFirstPage();

    var page = buildPage();

    if (activePage().is(':visible')) {
        createLastPage(page);
    }
    else {
        createInitialPage(page);
    }
}

function showFirstPage() {
    removeLastPage();

    var page = buildPage();

    if (activePage().is(':visible')) {
        createFirstPage(page);
    }
    else {
        createInitialPage(page);
    }
}

// Create Pages

function createInitialPage(data) {
    var p = $(data);
    p.appendTo($.mobile.pageContainer);
    $.mobile.pageContainer.pagecontainer('change', p, {
        transition: 'none'
    });
}

function createFirstPage(data) {
    if (!canDoPrev()) {
        activePage().before(data);
    } else {
        getFirst().before(data);
    }
    $.mobile.pageContainer.pagecontainer('change', getFirst().last(), {
	    transition: 'slide'
    });
}

function createLastPage(data) {
    if (!canDoNext()) {
        activePage().after(data);
    } else {
        getLast().after(data);
    }
    $.mobile.pageContainer.pagecontainer('change', getLast().last(), {
        transition: 'slide',
        reverse: true
    });
}

// Remove Pages

function removeFirstPage() {
    if (window.pageController.max <= $('[data-role=page]').length) {
        var page = getFirst();
        if(page.length === 0) {
            page = activePage();
            var active_page = page.next('[data-role=page]');
	        $.mobile.pageContainer.pagecontainer('change', active_page, {
		        transition: 'none'
	        });

        }
        page.remove();
    }
}

function removeLastPage() {
    if (window.pageController.max <= $('[data-role=page]').length) {
        var page = getLast();
        if(page.length === 0) {
            page = activePage();
            var active_page = page.prev('[data-role=page]');
	        $.mobile.pageContainer.pagecontainer('change', active_page, {
		        transition: 'none'
	        });

        }
        page.remove();
    }
}

// Page Controller

window.pageController = {
    first : 0,
	current : 0,
	max : 5,
    reset: function () {
        this.first = 0;
        this.current = 0;
		this.max = 5;
    },
    isLastPage: function () {
        console.log('isLastPage: ' + (window.pageController.current <= 0));
        return (window.pageController.current <= 0);
    },
    isFirstPage: function () {
        console.log('isFirstPage: ' + (window.lj_conf.number != window.lj_conf.count));
        return (window.lj_conf.number != window.lj_conf.count);
    }
};

// Create page

function createPageId() {
	return '"page_' + window.pageController.current + '"';
}

function createPageTitle() {
	var s = '';
    s += '"';
    s += getJournalPageTitle();
    s += ' (';
    s += (window.pageController.current + 1);
    s += ')"';
	return s;
}

function getJournalPageTitle() {
    var date = window.lj_conf.getPageDate(window.pageController.current);
    var d = new Date(date);
    var title =  window.lj_conf.journal + ' ' + $.format.date(d, 'dd/MM/yy');
    return title;
}

function createPageNumber() {
	return '"' + window.pageController.current + '"';
}

function buildPage() {
	var s = '';
	s += '
';
	s += '
';
	s += '

';
	s += '
';
	s += '
';
	return s;
}
<|endoftext|>


<commit_before>exports.commands = [
    "nyaa"
];
const azusa = require('random-cat');
exports.nyaa = {
    desc: "Nyaaa!",
    longDesc: "Ny- Nyaaaaaaaaaaaaaaaaaaaaaaaaaa~",
    main: function(bot, ctx) {
        var url = azusa.get();
        ctx.msg.channel.sendMessage(url + ` Nyaaaaaaaaaaaaaaaaaaaaaaaaaa~!`);
    }
}<commit_msg>don't ask why I rewrote this<commit_after>exports.commands = [
    "nyaa"
];
const azusa = require('random-cat');
exports.nyaa = {
    desc: "Nyaaa!",
    longDesc: "Ny- Nyaaaaaaaaaaaaaaaaaaaaaaaaaa~",
    main: function(bot, ctx) {
        var url = azusa.get();
        ctx.msg.channel.sendMessage(url);
    }
}<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * a Scenery Node representing the beaker heater in the view
 *
 * @author John Blanco
 * @author Andrew Adare
 * @author Chris Klusendorf (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var BeakerHeater = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/BeakerHeater' );
  var BeakerView = require( 'ENERGY_FORMS_AND_CHANGES/common/view/BeakerView' );
  var MoveFadeModelElementNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/MoveFadeModelElementNode' );
  var EnergyChunkLayer = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkLayer' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
  var TemperatureAndColorSensorNode = require( 'ENERGY_FORMS_AND_CHANGES/common/view/TemperatureAndColorSensorNode' );
  var Vector2 = require( 'DOT/Vector2' );

  // images
  var elementBaseBackImage = require( 'image!ENERGY_FORMS_AND_CHANGES/element_base_back.png' );
  var elementBaseFrontImage = require( 'image!ENERGY_FORMS_AND_CHANGES/element_base_front.png' );
  var heaterElementOnImage = require( 'image!ENERGY_FORMS_AND_CHANGES/heater_element.png' );
  var heaterElementOffImage = require( 'image!ENERGY_FORMS_AND_CHANGES/heater_element_dark.png' );
  var wireCurveImage = require( 'image!ENERGY_FORMS_AND_CHANGES/wire_black_right.png' );
  var wireFlatImage = require( 'image!ENERGY_FORMS_AND_CHANGES/wire_black_62.png' );

  /**
   * @param {BeakerHeater} beakerHeater
   * @param {Property.<boolean>} energyChunksVisibleProperty
   * @param {ModelViewTransform2} modelViewTransform
   * @constructor
   */
  function BeakerHeaterNode( beakerHeater, energyChunksVisibleProperty, modelViewTransform ) {

    MoveFadeModelElementNode.call( this, beakerHeater, modelViewTransform );

    var wireFlatNode = new Image( wireFlatImage, { left: -112, top: 77 } );
    var wireCurveNode = new Image( wireCurveImage, { left: wireFlatNode.right - 1, bottom: wireFlatNode.bottom + 1 } );
    var elementBaseBackNode = new Image( elementBaseBackImage, {
      right: wireCurveNode.right + 24,
      top: wireCurveNode.top - 2
    } );
    var elementBaseFrontNode = new Image( elementBaseFrontImage, {
      centerX: elementBaseBackNode.centerX,
      top: wireCurveNode.top - 3
    } );
    var energizedCoilNode = new Image( heaterElementOnImage, {
      maxHeight: modelViewTransform.modelToViewDeltaX( BeakerHeater.HEATER_ELEMENT_2D_HEIGHT ),
      centerX: elementBaseFrontNode.centerX - 4,
      bottom: elementBaseFrontNode.top + 15
    } );
    var nonEnergizedCoilNode = new Image( heaterElementOffImage, {
      maxHeight: modelViewTransform.modelToViewDeltaX( BeakerHeater.HEATER_ELEMENT_2D_HEIGHT ),
      centerX: elementBaseFrontNode.centerX - 4,
      bottom: elementBaseFrontNode.top + 15
    } );

    // add the images that are used to depict this element along with the layer that will contain the energy chunks
    this.addChild( wireFlatNode );
    this.addChild( wireCurveNode );
    this.addChild( elementBaseBackNode );
    this.addChild( nonEnergizedCoilNode );
    this.addChild( energizedCoilNode );
    this.addChild( new EnergyChunkLayer( beakerHeater.energyChunkList, beakerHeater.positionProperty, modelViewTransform ) );
    this.addChild( elementBaseFrontNode );

    // create a scale-only MVT, since several sub-elements are relatively positioned
    var scaleAndTranslateMVT = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
      new Vector2( beakerHeater.beaker.positionProperty.value.x, 0 ),
      Vector2.ZERO,
      modelViewTransform.getMatrix().getScaleVector().x
    );

    // @public (read-only) {BeakerView}
    this.beakerView = new BeakerView( beakerHeater.beaker, energyChunksVisibleProperty, scaleAndTranslateMVT );

    this.addChild( this.beakerView.backNode );
    this.addChild( new EnergyChunkLayer(
      beakerHeater.radiatedEnergyChunkList,
      beakerHeater.beaker.positionProperty,
      modelViewTransform
    ) );
    this.addChild( this.beakerView.frontNode );

    // create a scale-only MVT, since several sub-elements are relatively positioned
    var scaleOnlyMVT = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
      Vector2.ZERO,
      Vector2.ZERO,
      modelViewTransform.getMatrix().getScaleVector().x
    );

    // Add the thermometer that will indicate the beaker water temperature.  Since the position of the thermometer is
    // relative to the beaker heater, the model view transform must be compensated
    var temperatureAndColorSensorNode = new TemperatureAndColorSensorNode( beakerHeater.temperatureAndColorSensor, {
      modelViewTransform: scaleOnlyMVT
    } );
    this.addChild( temperatureAndColorSensorNode );

    // update the transparency of the hot element to make the dark element appear to heat up
    beakerHeater.heatProportionProperty.link( function( litProportion ) {
      energizedCoilNode.opacity = litProportion;
    } );
  }

  energyFormsAndChanges.register( 'BeakerHeaterNode', BeakerHeaterNode );

  return inherit( MoveFadeModelElementNode, BeakerHeaterNode, {

    /**
     * step this view element, called by the framework
     * @param dt - time step, in seconds
     * @public
     */
    step: function( dt ) {
      this.beakerView.step( dt );
    }
  } );
} );
<commit_msg>Integrate beaker heater wires, see https://github.com/phetsims/energy-forms-and-changes/issues/91<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * a Scenery Node representing the beaker heater in the view
 *
 * @author John Blanco
 * @author Andrew Adare
 * @author Chris Klusendorf (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var BeakerHeater = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/BeakerHeater' );
  var BeakerView = require( 'ENERGY_FORMS_AND_CHANGES/common/view/BeakerView' );
  var MoveFadeModelElementNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/MoveFadeModelElementNode' );
  var EnergyChunkLayer = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkLayer' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
  var TemperatureAndColorSensorNode = require( 'ENERGY_FORMS_AND_CHANGES/common/view/TemperatureAndColorSensorNode' );
  var Vector2 = require( 'DOT/Vector2' );

  // images
  var elementBaseBackImage = require( 'image!ENERGY_FORMS_AND_CHANGES/element_base_back.png' );
  var elementBaseFrontImage = require( 'image!ENERGY_FORMS_AND_CHANGES/element_base_front.png' );
  var heaterElementOnImage = require( 'image!ENERGY_FORMS_AND_CHANGES/heater_element.png' );
  var heaterElementOffImage = require( 'image!ENERGY_FORMS_AND_CHANGES/heater_element_dark.png' );
  var wireBottomRightImage = require( 'image!ENERGY_FORMS_AND_CHANGES/wire_bottom_right.png' );
  var wireStraightImage = require( 'image!ENERGY_FORMS_AND_CHANGES/wire_straight.png' );

  /**
   * @param {BeakerHeater} beakerHeater
   * @param {Property.<boolean>} energyChunksVisibleProperty
   * @param {ModelViewTransform2} modelViewTransform
   * @constructor
   */
  function BeakerHeaterNode( beakerHeater, energyChunksVisibleProperty, modelViewTransform ) {

    MoveFadeModelElementNode.call( this, beakerHeater, modelViewTransform );

    var wireStraightNode = new Image( wireStraightImage, { left: -112, top: 78 } );
    var wireBottomRightNode = new Image( wireBottomRightImage, {
      left: wireStraightNode.right - 4,
      bottom: wireStraightNode.bottom + 2.5
    } );
    var elementBaseBackNode = new Image( elementBaseBackImage, {
      right: wireBottomRightNode.right + 21,
      top: wireBottomRightNode.top - 2.5
    } );
    var elementBaseFrontNode = new Image( elementBaseFrontImage, {
      centerX: elementBaseBackNode.centerX,
      top: wireBottomRightNode.top - 3
    } );
    var energizedCoilNode = new Image( heaterElementOnImage, {
      maxHeight: modelViewTransform.modelToViewDeltaX( BeakerHeater.HEATER_ELEMENT_2D_HEIGHT ),
      centerX: elementBaseFrontNode.centerX - 4,
      bottom: elementBaseFrontNode.top + 15
    } );
    var nonEnergizedCoilNode = new Image( heaterElementOffImage, {
      maxHeight: modelViewTransform.modelToViewDeltaX( BeakerHeater.HEATER_ELEMENT_2D_HEIGHT ),
      centerX: elementBaseFrontNode.centerX - 4,
      bottom: elementBaseFrontNode.top + 15
    } );

    // add the images that are used to depict this element along with the layer that will contain the energy chunks
    this.addChild( wireStraightNode );
    this.addChild( wireBottomRightNode );
    this.addChild( elementBaseBackNode );
    this.addChild( nonEnergizedCoilNode );
    this.addChild( energizedCoilNode );
    this.addChild( new EnergyChunkLayer( beakerHeater.energyChunkList, beakerHeater.positionProperty, modelViewTransform ) );
    this.addChild( elementBaseFrontNode );

    // create a scale-only MVT, since several sub-elements are relatively positioned
    var scaleAndTranslateMVT = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
      new Vector2( beakerHeater.beaker.positionProperty.value.x, 0 ),
      Vector2.ZERO,
      modelViewTransform.getMatrix().getScaleVector().x
    );

    // @public (read-only) {BeakerView}
    this.beakerView = new BeakerView( beakerHeater.beaker, energyChunksVisibleProperty, scaleAndTranslateMVT );

    this.addChild( this.beakerView.backNode );
    this.addChild( new EnergyChunkLayer(
      beakerHeater.radiatedEnergyChunkList,
      beakerHeater.beaker.positionProperty,
      modelViewTransform
    ) );
    this.addChild( this.beakerView.frontNode );

    // create a scale-only MVT, since several sub-elements are relatively positioned
    var scaleOnlyMVT = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
      Vector2.ZERO,
      Vector2.ZERO,
      modelViewTransform.getMatrix().getScaleVector().x
    );

    // Add the thermometer that will indicate the beaker water temperature.  Since the position of the thermometer is
    // relative to the beaker heater, the model view transform must be compensated
    var temperatureAndColorSensorNode = new TemperatureAndColorSensorNode( beakerHeater.temperatureAndColorSensor, {
      modelViewTransform: scaleOnlyMVT
    } );
    this.addChild( temperatureAndColorSensorNode );

    // update the transparency of the hot element to make the dark element appear to heat up
    beakerHeater.heatProportionProperty.link( function( litProportion ) {
      energizedCoilNode.opacity = litProportion;
    } );
  }

  energyFormsAndChanges.register( 'BeakerHeaterNode', BeakerHeaterNode );

  return inherit( MoveFadeModelElementNode, BeakerHeaterNode, {

    /**
     * step this view element, called by the framework
     * @param dt - time step, in seconds
     * @public
     */
    step: function( dt ) {
      this.beakerView.step( dt );
    }
  } );
} );
<|endoftext|>


<commit_before>// DEMO scripting
(function(w){
	var doc = w.document,
		o = overthrow;
	// Enhance this page a bit

// add a link to toggle overthrow on/off on the content
if( o.support === "native" || o.support === "polyfilled" ){
	var oToggleLink = doc.createElement( "a" ),
		toggleContain = doc.getElementById( "toggleContain" );

	if( toggleContain ){
		oToggleLink.href = "#";
		oToggleLink.className = "toggle";
		oToggleLink.innerText = "Disable Overthrow";
		oToggleLink.onclick = function(){
			if( doc.documentElement.className.indexOf( "overthrow" ) > -1 ){
				o.forget();
				oToggleLink.innerText = "Enable Overthrow";
			}
			else{
				o.set();
				oToggleLink.innerText = "Disable Overthrow";
			}
		};

		doc.getElementById( "toggleContain" ).appendChild( oToggleLink );
	}
}

})(this);<commit_msg>better compat in demo<commit_after>// DEMO scripting
(function(w){
	var doc = w.document,
		o = overthrow;
	// Enhance this page a bit

// add a link to toggle overthrow on/off on the content
if( o.support === "native" || o.support === "polyfilled" ){
	var oToggleLink = doc.createElement( "a" ),
		toggleContain = doc.getElementById( "toggleContain" );

	if( toggleContain ){
		oToggleLink.href = "#";
		oToggleLink.className = "toggle";
		oToggleLink.innerHTML = "Disable Overthrow";
		oToggleLink.onclick = function(){
			if( doc.documentElement.className.indexOf( "overthrow" ) > -1 ){
				o.forget();
				oToggleLink.innerText = "Enable Overthrow";
			}
			else{
				o.set();
				oToggleLink.innerText = "Disable Overthrow";
			}
		};

		doc.getElementById( "toggleContain" ).appendChild( oToggleLink );
	}
}

})(this);<|endoftext|>


<commit_before>define([
    "zepto",
    "modules/hashTable",
    "modules/channels/channel",
    "modules/channels/tokens",
    "modules/channels/channelExtensions",
    "modules/channels/tlkeChannel",
    "modules/channels/remoteChannel",
    "modules/channels/genericChannel",
    "modules/data-types/hex",
    "tools/urandom"
], function ($, HashTable, Channel, tokens, extensions, TlkeChannel, RemoteChannel, GenericChannel, Hex, urandom) {
    "use strict";

    function ContactChannelGroup() {

        // new RemoteChannel() will call this._notifyDirty but the dirtyNotifier is not yet set
        // just don't forget to set the dirtyNotifier after calling new ContactChannelGroup()
        this.setDirtyNotifier({notify: function () { }});

        this.channels = new HashTable();
        this.remoteChannels = new HashTable();
        this.tlkeChannel = null;
        // alice generates offer, bob accepts
        this.iAmAlice = null;

        // mirror of the contact's ContactChannelGroup to send tokens
        this.remoteChannelGroup = new RemoteChannel();
        this._addRemoteChannel(this.remoteChannelGroup, 0);
        this.channels.setItem(this, {ref: 0});

        this._setTokenHandler(tokens.ContactChannelGroup.GenerateTlkeToken, this.onTokenGenerateTlke);
        this._setTokenHandler(tokens.ContactChannelGroup.OfferToken, this.onTokenOffer);
        this._setTokenHandler(tokens.ContactChannelGroup.AuthToken, this.onTokenAuth);
        this._setTokenHandler(tokens.ContactChannelGroup.GenerateOverTlkeToken, this.requestCreateExtraGenericChannel);
    }

    ContactChannelGroup.prototype = new Channel();

    $.extend(ContactChannelGroup.prototype, {
        setMsgProcessor: function (iMsgProcessor) { this.msgProcessor = iMsgProcessor; },

        ////////////////////
        //  User comms    //
        ////////////////////
        // user calls enterToken with ContactChannelGroup.GenerateTlkeToken argument
        onTokenGenerateTlke: function (token, context) {
            this.iAmAlice = true;
            this.tlkeChannel = new TlkeChannel();
            this._addChannel(this.tlkeChannel);
            this.tlkeChannel.enterToken(new tokens.TlkeChannel.GenerateToken());
        },
        // user calls enterToken with ContactChannelGroup.OfferToken argument
        onTokenOffer: function (token, context) {
            this.iAmAlice = false;
            this.tlkeChannel = new TlkeChannel();
            this._addChannel(this.tlkeChannel);
            this.tlkeChannel.enterToken(new tokens.TlkeChannel.OfferToken(token.offer));
        },
        // user calls enterToken with ContactChannelGroup.AuthToken argument
        onTokenAuth: function (token, context) {
            if (!this.tlkeChannel) {
                throw new Error("Tlke channel is not ready");
            }
            this.tlkeChannel.enterToken(new tokens.TlkeChannel.AuthToken(token.auth));
        },
        // transport calls processPacket. Careful to the structure: { receiver: "BEEF", data: "1FAA..." }
        processPacket: function (packet) {
            var receiverTuple = this.channels.first(function (value) {
                return value.inId && value.inId.as(Hex).isEqualTo(packet.receiver);
            });
            if (receiverTuple) {
                receiverTuple.key.processPacket(packet.data);
            } else {
                throw new Error("Could not find the receiver for packet ", packet, " Check packet.receiver property");
            }
        },

        // handled by extensions, configured by this._setTokenHandler()
        enterToken: function (token, context) {
            this._enterToken(token, context);
        },

        // simply send the user message to the contact. data should be plain object
        sendMessage: function (data) {
            this._sendMessage(new ChannelGroupMessage(ChannelGroupMessage.MSG_TYPE_USER, data));
        },

        //////////////////////////////
        //  Regular channels comms.
        //  (regular channels communicate via packetSender that uses onChannelSendPacket())
        //////////////////////////////
        // a message received from generic channel
        onChannelMessage: function (channel, data) {
            var message = ChannelGroupMessage.deserialize(data);
            if (message.type === ChannelGroupMessage.MSG_TYPE_USER) {
                this._emitUserMessage(message.data);
            } else if (message.type === ChannelGroupMessage.MSG_TYPE_WRAPPER) {
                this.onPacketForRemoteChannel(message.data, message.ref);
            } else {
                console.warn("Received a strange message: ", message);
            }
        },
        // one of regular channels has issued a token
        onChannelToken: function (isOverChannel, channel, token, context) {

            if (token instanceof tokens.TlkeChannel.TlkeChannelGeneratedToken) {
                // learn new ids
                this.onChannelNewIds(channel, token);
            } else if (token instanceof tokens.TlkeChannel.ChangeStateToken) {
                // just mirror tlke change state token
                if (isOverChannel) {
                    this._emitPrompt(new tokens.ContactChannelGroup.OverChannelChangeStateToken(token.state));
                } else {
                    this._emitPrompt(new tokens.ContactChannelGroup.ChangeStateToken(token.state));
                }
            } else if (token instanceof tokens.TlkeChannel.GenericChannelGeneratedToken) {
                // create new generic channel
                this.onNewGenericChannelKeysReady(token);
            } else if (channel === this.tlkeChannel && token instanceof tokens.TlkeChannel.OfferToken) {
                // just mirror tlke offer token
                this._emitPrompt(new tokens.ContactChannelGroup.OfferToken(token.offer));
            } else if (channel === this.tlkeChannel && token instanceof tokens.TlkeChannel.AuthToken) {
                // just mirror tlke auth token
                this._emitPrompt(new tokens.ContactChannelGroup.AuthToken(token.auth));
            }

            // handle additional overChannel tokens
            if (isOverChannel) {
                this.onOverChannelToken(channel, token, context);
            }
        },

        // new channel ids learned, add to routing
        onChannelNewIds: function (channel, token) {
            var info = this.channels.getItem(channel);
            info.inId = token.inId;
            info.outId = token.outId;
            this.channels.setItem(channel, info);
            // notify the owner that it should listen more channelIds
            this._emitPrompt(new tokens.ContactChannelGroup.ChannelAddedToken(token.inId));
            this._notifyDirty();
        },
        // tlke channel has generated new keys for generic channel
        onNewGenericChannelKeysReady: function (token) {
            var newGeneric = new GenericChannel();
            this._addChannel(newGeneric);
            this.onChannelNewIds(newGeneric, token);
            newGeneric.enterToken(token);
        },
        // channel sends a packet. Careful to the structure of the resulting packet: { receiver: "BEEF", data: "1FAA..." }
        onChannelSendPacket: function (channel, data) {
            var sender = this.channels.getItem(channel);
            if (!sender.outId) {
                throw new Error("The channel did not provide it's channel ids yet");
            }
            var packet = {
                receiver: sender.outId,
                data: data
            };
            this._sendPacket(packet);
        },
        // channel notifies it has changed it's state
        onChannelNotifyDirty: function (channel) {
            this._notifyDirty();
        },

        //////////////////////////////
        //  Remote channels comms   //
        //////////////////////////////
        // RemoteChannel wants to send the token
        onRemoteChannelSendPacket: function (channel, packet) {
            var sender = this.remoteChannels.getItem(channel);
            this._sendMessage(new ChannelGroupMessage(ChannelGroupMessage.MSG_TYPE_WRAPPER, packet, sender.ref));
        },
        // the remote channel has issued the token
        onRemoteChannelToken: function (channel, token, context) {
            var remoteChannelInfo = this.remoteChannels.getItem(channel);
            var ref = remoteChannelInfo.ref;
            var overChannelItem = this.channels.first(function (value) {
                return value.ref === remoteChannelInfo.ref;
            });
            var refChannel = overChannelItem ? overChannelItem.key : null;

            if ((token instanceof tokens.ContactChannelGroup.OfferToken) && ref === 0) {
                // remote ContactChannelGroup has provided an offer to accept
                this.onRemoteTokenOffer(token, refChannel);
            } else if (token instanceof tokens.ContactChannelGroup.AuthToken) {
                // remote ContactChannelGroup has provided an offer to accept
                refChannel.enterToken(new tokens.TlkeChannel.AuthToken(token.auth));
            }
        },
        // the packet received in a wrapper message from generic channel
        onPacketForRemoteChannel: function (packet, ref) {
            var remoteChannelTuple = this.remoteChannels.first(function (value) {
                return value.ref === ref;
            });
            if (remoteChannelTuple) {
                remoteChannelTuple.key.processPacket(packet);
            } else {
                console.warn("Remote channel with ref " + ref + " not found");
            }
        },

        // received the remote token to create new remote channel and accept offer
        onRemoteTokenOffer: function (token) {
            var overTlke = new TlkeChannel();
            this._addChannel(overTlke, token.ref);
            var remoteTlke = new RemoteChannel();
            this._addRemoteChannel(remoteTlke, token.ref);
            overTlke.enterToken(new tokens.TlkeChannel.OfferToken(token.offer));
        },

        //////////////////////////////
        //  OverChannels (channels that communicate via remote channels)
        //////////////////////////////
        // create additional generic channel
        requestCreateExtraGenericChannel: function () {
            var overTlkeChannel = new TlkeChannel();
            var ref = urandom.int(1, 0xffffff);
            var remoteTlke = new RemoteChannel();
            this._addChannel(overTlkeChannel, ref);
            this._addRemoteChannel(remoteTlke, ref);
            console.info((this.iAmAlice ? "Alice" : "Bob") + " created remote tlke");
            overTlkeChannel.enterToken(new tokens.TlkeChannel.GenerateToken());
        },

        // token from overChannel
        onOverChannelToken: function (channel, token, context) {
            var info = this.channels.getItem(channel);
            var ref = info.ref;
            if (token instanceof tokens.TlkeChannel.OfferToken && token.offer) {
                // overTlkeChannel has generated an offer
                // ask remote contact to create channel and accept the offer
                this.remoteChannelGroup.enterToken(new tokens.ContactChannelGroup.OfferToken(token.offer, ref));
            } else if (token instanceof tokens.TlkeChannel.AuthToken && token.auth) {
                // overTlkeChannel has generated an auth
                // ask remote channel to accept it
                var remoteChannelInfo = this.remoteChannels.first(function (value) { return value.ref === ref; });
                if (!remoteChannelInfo) {
                    throw new Error("Cannot route the token over remote channel");
                }
                remoteChannelInfo.key.enterToken(new tokens.ContactChannelGroup.OfferToken(token.offer));
            }
        },

        //////////////////////////////
        //  Internal
        //////////////////////////////
        // add remote channel and bind handlers
        _addRemoteChannel: function (channel, reference) {
            this._setPacketSender(channel, this.onRemoteChannelSendPacket);
            this._setTokenPrompter(channel, this.onRemoteChannelToken);

            this.remoteChannels.setItem(channel, {ref: reference});
            this._notifyDirty();
        },

        // add regular channel and bind handlers
        _addChannel: function (channel, reference) {
            var isAux = !!reference;
            this._setPacketSender(channel, this.onChannelSendPacket);
            this._setTokenPrompter(channel, this.onChannelToken.bind(this, isAux));
            this._setDirtyNotifier(channel, this.onChannelNotifyDirty);
            if (channel instanceof GenericChannel) {
                this._setMsgProcessor(channel, this.onChannelMessage);
            }
            channel.setRng(this.random);
            this.channels.setItem(channel, {
                inId: null,
                outId: null,
                ref: reference
            });
            this._notifyDirty();
        },

        _sendMessage: function (message, channel) {
            if (!channel) {
                this.channels.each(function (key, value) {
                    // channel.isActive later
                    if (key instanceof GenericChannel) {
                        channel = key;
                    }
                });
            }
            if (!channel) { throw new Error("Didn't found channel to send a message"); }
            if (!(message instanceof ChannelGroupMessage)) {
                throw new Error("Argument exception");
            }
            channel.sendMessage(message.serialize());
        },

        _emitUserMessage: function (message) {
            this._check("msgProcessor");
            this.msgProcessor.processMessage(this, message);
        }

    }, extensions);

    // the message type to communicate between ChannelGroups via GenericChannels
    // it can wrap a user message or the RemoteChannelList packet
    function ChannelGroupMessage(type, data, ref) {
        if (!$.isPlainObject(data)) {
            var msg = "Could not create ChannelGroupMessage message from " + JSON.stringify(data) + ". ";
            msg += "Only plain-object data is supported now";
            throw new Error(msg);
        }
        this.type = type;
        this.data = data;
        if (ref === 0 || ref) {
            this.ref = parseInt(ref, 10);
        }
    }
    ChannelGroupMessage.prototype.serialize = function () {
        var dto = {
            t: this.type,
            d: this.data
        };
        if (this.ref === 0 || this.ref) {
            dto.r = this.ref;
        }
        return dto;
    };
    ChannelGroupMessage.deserialize = function (dto) {
        return new ChannelGroupMessage(dto.t, dto.d, dto.r);
    };

    ChannelGroupMessage.MSG_TYPE_USER = "u";
    ChannelGroupMessage.MSG_TYPE_WRAPPER = "w";

    return ContactChannelGroup;
});<commit_msg>fixed token type<commit_after>define([
    "zepto",
    "modules/hashTable",
    "modules/channels/channel",
    "modules/channels/tokens",
    "modules/channels/channelExtensions",
    "modules/channels/tlkeChannel",
    "modules/channels/remoteChannel",
    "modules/channels/genericChannel",
    "modules/data-types/hex",
    "tools/urandom"
], function ($, HashTable, Channel, tokens, extensions, TlkeChannel, RemoteChannel, GenericChannel, Hex, urandom) {
    "use strict";

    function ContactChannelGroup() {

        // new RemoteChannel() will call this._notifyDirty but the dirtyNotifier is not yet set
        // just don't forget to set the dirtyNotifier after calling new ContactChannelGroup()
        this.setDirtyNotifier({notify: function () { }});

        this.channels = new HashTable();
        this.remoteChannels = new HashTable();
        this.tlkeChannel = null;
        // alice generates offer, bob accepts
        this.iAmAlice = null;

        // mirror of the contact's ContactChannelGroup to send tokens
        this.remoteChannelGroup = new RemoteChannel();
        this._addRemoteChannel(this.remoteChannelGroup, 0);
        this.channels.setItem(this, {ref: 0});

        this._setTokenHandler(tokens.ContactChannelGroup.GenerateTlkeToken, this.onTokenGenerateTlke);
        this._setTokenHandler(tokens.ContactChannelGroup.OfferToken, this.onTokenOffer);
        this._setTokenHandler(tokens.ContactChannelGroup.AuthToken, this.onTokenAuth);
        this._setTokenHandler(tokens.ContactChannelGroup.GenerateOverTlkeToken, this.requestCreateExtraGenericChannel);
    }

    ContactChannelGroup.prototype = new Channel();

    $.extend(ContactChannelGroup.prototype, {
        setMsgProcessor: function (iMsgProcessor) { this.msgProcessor = iMsgProcessor; },

        ////////////////////
        //  User comms    //
        ////////////////////
        // user calls enterToken with ContactChannelGroup.GenerateTlkeToken argument
        onTokenGenerateTlke: function (token, context) {
            this.iAmAlice = true;
            this.tlkeChannel = new TlkeChannel();
            this._addChannel(this.tlkeChannel);
            this.tlkeChannel.enterToken(new tokens.TlkeChannel.GenerateToken());
        },
        // user calls enterToken with ContactChannelGroup.OfferToken argument
        onTokenOffer: function (token, context) {
            this.iAmAlice = false;
            this.tlkeChannel = new TlkeChannel();
            this._addChannel(this.tlkeChannel);
            this.tlkeChannel.enterToken(new tokens.TlkeChannel.OfferToken(token.offer));
        },
        // user calls enterToken with ContactChannelGroup.AuthToken argument
        onTokenAuth: function (token, context) {
            if (!this.tlkeChannel) {
                throw new Error("Tlke channel is not ready");
            }
            this.tlkeChannel.enterToken(new tokens.TlkeChannel.AuthToken(token.auth));
        },
        // transport calls processPacket. Careful to the structure: { receiver: "BEEF", data: "1FAA..." }
        processPacket: function (packet) {
            var receiverTuple = this.channels.first(function (value) {
                return value.inId && value.inId.as(Hex).isEqualTo(packet.receiver);
            });
            if (receiverTuple) {
                receiverTuple.key.processPacket(packet.data);
            } else {
                throw new Error("Could not find the receiver for packet ", packet, " Check packet.receiver property");
            }
        },

        // handled by extensions, configured by this._setTokenHandler()
        enterToken: function (token, context) {
            this._enterToken(token, context);
        },

        // simply send the user message to the contact. data should be plain object
        sendMessage: function (data) {
            this._sendMessage(new ChannelGroupMessage(ChannelGroupMessage.MSG_TYPE_USER, data));
        },

        //////////////////////////////
        //  Regular channels comms.
        //  (regular channels communicate via packetSender that uses onChannelSendPacket())
        //////////////////////////////
        // a message received from generic channel
        onChannelMessage: function (channel, data) {
            var message = ChannelGroupMessage.deserialize(data);
            if (message.type === ChannelGroupMessage.MSG_TYPE_USER) {
                this._emitUserMessage(message.data);
            } else if (message.type === ChannelGroupMessage.MSG_TYPE_WRAPPER) {
                this.onPacketForRemoteChannel(message.data, message.ref);
            } else {
                console.warn("Received a strange message: ", message);
            }
        },
        // one of regular channels has issued a token
        onChannelToken: function (isOverChannel, channel, token, context) {

            if (token instanceof tokens.TlkeChannel.TlkeChannelGeneratedToken) {
                // learn new ids
                this.onChannelNewIds(channel, token);
            } else if (token instanceof tokens.TlkeChannel.ChangeStateToken) {
                // just mirror tlke change state token
                if (isOverChannel) {
                    this._emitPrompt(new tokens.ContactChannelGroup.OverChannelChangeStateToken(token.state));
                } else {
                    this._emitPrompt(new tokens.ContactChannelGroup.ChangeStateToken(token.state));
                }
            } else if (token instanceof tokens.TlkeChannel.GenericChannelGeneratedToken) {
                // create new generic channel
                this.onNewGenericChannelKeysReady(token);
            } else if (channel === this.tlkeChannel && token instanceof tokens.TlkeChannel.OfferToken) {
                // just mirror tlke offer token
                this._emitPrompt(new tokens.ContactChannelGroup.OfferToken(token.offer));
            } else if (channel === this.tlkeChannel && token instanceof tokens.TlkeChannel.AuthToken) {
                // just mirror tlke auth token
                this._emitPrompt(new tokens.ContactChannelGroup.AuthToken(token.auth));
            }

            // handle additional overChannel tokens
            if (isOverChannel) {
                this.onOverChannelToken(channel, token, context);
            }
        },

        // new channel ids learned, add to routing
        onChannelNewIds: function (channel, token) {
            var info = this.channels.getItem(channel);
            info.inId = token.inId;
            info.outId = token.outId;
            this.channels.setItem(channel, info);
            // notify the owner that it should listen more channelIds
            this._emitPrompt(new tokens.ContactChannelGroup.ChannelAddedToken(token.inId));
            this._notifyDirty();
        },
        // tlke channel has generated new keys for generic channel
        onNewGenericChannelKeysReady: function (token) {
            var newGeneric = new GenericChannel();
            this._addChannel(newGeneric);
            this.onChannelNewIds(newGeneric, token);
            newGeneric.enterToken(token);
        },
        // channel sends a packet. Careful to the structure of the resulting packet: { receiver: "BEEF", data: "1FAA..." }
        onChannelSendPacket: function (channel, data) {
            var sender = this.channels.getItem(channel);
            if (!sender.outId) {
                throw new Error("The channel did not provide it's channel ids yet");
            }
            var packet = {
                receiver: sender.outId,
                data: data
            };
            this._sendPacket(packet);
        },
        // channel notifies it has changed it's state
        onChannelNotifyDirty: function (channel) {
            this._notifyDirty();
        },

        //////////////////////////////
        //  Remote channels comms   //
        //////////////////////////////
        // RemoteChannel wants to send the token
        onRemoteChannelSendPacket: function (channel, packet) {
            var sender = this.remoteChannels.getItem(channel);
            this._sendMessage(new ChannelGroupMessage(ChannelGroupMessage.MSG_TYPE_WRAPPER, packet, sender.ref));
        },
        // the remote channel has issued the token
        onRemoteChannelToken: function (channel, token, context) {
            var remoteChannelInfo = this.remoteChannels.getItem(channel);
            var ref = remoteChannelInfo.ref;
            var overChannelItem = this.channels.first(function (value) {
                return value.ref === remoteChannelInfo.ref;
            });
            var refChannel = overChannelItem ? overChannelItem.key : null;

            if ((token instanceof tokens.ContactChannelGroup.OfferToken) && ref === 0) {
                // remote ContactChannelGroup has provided an offer to accept
                this.onRemoteTokenOffer(token, refChannel);
            } else if (token instanceof tokens.ContactChannelGroup.AuthToken) {
                // remote ContactChannelGroup has provided an offer to accept
                refChannel.enterToken(new tokens.TlkeChannel.AuthToken(token.auth));
            }
        },
        // the packet received in a wrapper message from generic channel
        onPacketForRemoteChannel: function (packet, ref) {
            var remoteChannelTuple = this.remoteChannels.first(function (value) {
                return value.ref === ref;
            });
            if (remoteChannelTuple) {
                remoteChannelTuple.key.processPacket(packet);
            } else {
                console.warn("Remote channel with ref " + ref + " not found");
            }
        },

        // received the remote token to create new remote channel and accept offer
        onRemoteTokenOffer: function (token) {
            var overTlke = new TlkeChannel();
            this._addChannel(overTlke, token.ref);
            var remoteTlke = new RemoteChannel();
            this._addRemoteChannel(remoteTlke, token.ref);
            overTlke.enterToken(new tokens.TlkeChannel.OfferToken(token.offer));
        },

        //////////////////////////////
        //  OverChannels (channels that communicate via remote channels)
        //////////////////////////////
        // create additional generic channel
        requestCreateExtraGenericChannel: function () {
            var overTlkeChannel = new TlkeChannel();
            var ref = urandom.int(1, 0xffffff);
            var remoteTlke = new RemoteChannel();
            this._addChannel(overTlkeChannel, ref);
            this._addRemoteChannel(remoteTlke, ref);
            console.info((this.iAmAlice ? "Alice" : "Bob") + " created remote tlke");
            overTlkeChannel.enterToken(new tokens.TlkeChannel.GenerateToken());
        },

        // token from overChannel
        onOverChannelToken: function (channel, token, context) {
            var info = this.channels.getItem(channel);
            var ref = info.ref;
            if (token instanceof tokens.TlkeChannel.OfferToken && token.offer) {
                // overTlkeChannel has generated an offer
                // ask remote contact to create channel and accept the offer
                this.remoteChannelGroup.enterToken(new tokens.ContactChannelGroup.OfferToken(token.offer, ref));
            } else if (token instanceof tokens.TlkeChannel.AuthToken && token.auth) {
                // overTlkeChannel has generated an auth
                // ask remote channel to accept it
                var remoteChannelInfo = this.remoteChannels.first(function (value) { return value.ref === ref; });
                if (!remoteChannelInfo) {
                    throw new Error("Cannot route the token over remote channel");
                }
                remoteChannelInfo.key.enterToken(new tokens.ContactChannelGroup.AuthToken(token.auth));
            }
        },

        //////////////////////////////
        //  Internal
        //////////////////////////////
        // add remote channel and bind handlers
        _addRemoteChannel: function (channel, reference) {
            this._setPacketSender(channel, this.onRemoteChannelSendPacket);
            this._setTokenPrompter(channel, this.onRemoteChannelToken);

            this.remoteChannels.setItem(channel, {ref: reference});
            this._notifyDirty();
        },

        // add regular channel and bind handlers
        _addChannel: function (channel, reference) {
            var isAux = !!reference;
            this._setPacketSender(channel, this.onChannelSendPacket);
            this._setTokenPrompter(channel, this.onChannelToken.bind(this, isAux));
            this._setDirtyNotifier(channel, this.onChannelNotifyDirty);
            if (channel instanceof GenericChannel) {
                this._setMsgProcessor(channel, this.onChannelMessage);
            }
            channel.setRng(this.random);
            this.channels.setItem(channel, {
                inId: null,
                outId: null,
                ref: reference
            });
            this._notifyDirty();
        },

        _sendMessage: function (message, channel) {
            if (!channel) {
                this.channels.each(function (key, value) {
                    // channel.isActive later
                    if (key instanceof GenericChannel) {
                        channel = key;
                    }
                });
            }
            if (!channel) { throw new Error("Didn't found channel to send a message"); }
            if (!(message instanceof ChannelGroupMessage)) {
                throw new Error("Argument exception");
            }
            channel.sendMessage(message.serialize());
        },

        _emitUserMessage: function (message) {
            this._check("msgProcessor");
            this.msgProcessor.processMessage(this, message);
        }

    }, extensions);

    // the message type to communicate between ChannelGroups via GenericChannels
    // it can wrap a user message or the RemoteChannelList packet
    function ChannelGroupMessage(type, data, ref) {
        if (!$.isPlainObject(data)) {
            var msg = "Could not create ChannelGroupMessage message from " + JSON.stringify(data) + ". ";
            msg += "Only plain-object data is supported now";
            throw new Error(msg);
        }
        this.type = type;
        this.data = data;
        if (ref === 0 || ref) {
            this.ref = parseInt(ref, 10);
        }
    }
    ChannelGroupMessage.prototype.serialize = function () {
        var dto = {
            t: this.type,
            d: this.data
        };
        if (this.ref === 0 || this.ref) {
            dto.r = this.ref;
        }
        return dto;
    };
    ChannelGroupMessage.deserialize = function (dto) {
        return new ChannelGroupMessage(dto.t, dto.d, dto.r);
    };

    ChannelGroupMessage.MSG_TYPE_USER = "u";
    ChannelGroupMessage.MSG_TYPE_WRAPPER = "w";

    return ContactChannelGroup;
});<|endoftext|>


<commit_before>const authenticationStore = jest.genMockFromModule('../AuthenticationStore');

function getUserId() {
  return '42';
}

authenticationStore.getUserId = getUserId;

module.exports = authenticationStore;
<commit_msg>remove unused mock<commit_after><|endoftext|>


<commit_before>var data = ["35", "33", "40"];

//var barWidth = 40;

//Array size
var arrElementWidth = 50;
var arrElementHeight = 50;

var width = (arrElementWidth + 10) * data.length;
var height = 350;

//Animation
var animationTime = 0.5;
var tl = new TimelineMax();
tl.pause();

//var arrayList = new ArrayList(data);
var theSize = 3;
var capacity = 5;

//PH - Code TODO get code from another source
var codeContent = [
    "",
    "function Arraylist(a) {",
    "    for(var gap = a.length / 2; gap > 0;",
    "        gap = gap === 2 ? 1 : parseInt(gap / 2.2)) {",
    "",
    "        for(var i = gap; i < a.length; i++) {",
    "            var tmp = a[i];",
    "",
    "            for(var j = i; j >= gap && tmp < a[j - gap]; j-= gap) {",
    "                a[j] = a[j - gap];",
    "            }",
    "            a[j] = tmp;",
    "        }",
    "    }",
    "    return a;",
    "}"
];

var code = d3.select("#code-text");
var drawingArea = d3.select(".drawingArea").append("svg:svg");
var theSizeBlock = drawingArea.append("g");

theSizeBlock.append("rect")
    .attr("width", 0)
    .attr("height", (arrElementHeight + 40 + 10))
    .attr("id", "theSizeBlock")
    .attr("fill", "lime");

theSizeBlock.append("text")
    .attr("y", 25)
    .attr("x", 10)
    .attr("id", "theSizeBlockText")
    .style("opacity", "0")
    .text("theSize");

var mainArray = drawingArea.append("g")
    .attr("id", "mainArray");

createArray(5, 0, 0);

var arrayList = new ArrayList(data);

function createArray(length, oldlength, y) {

    width = (arrElementWidth + 10) * length;

    drawingArea.attr("width", width + 150)
        .attr("height", height);

    for(var i = 0; i < length; i++) {
        mainArray.insert("svg:rect", ":first-child")
            .attr("x", i * ((width) / length) + 5 )
            .attr("y", 40)
            .attr("transform", "translate(0," + y + ")")
            .attr("height", arrElementHeight)
            .attr("width", arrElementWidth)
            .attr("fill", "red")
            .style("opacity", "0")
            .attr("class", "rect" + i );
    }

    for(var j = oldlength; j < length; j++) {
        createTextElement(j, length, y, "");
/*        mainArray.append("text")
            .text("")
            .attr("x",j * (width / length) + arrElementWidth / 3 + 5)
            .attr("y", 30+40)
            .attr("transform", "translate(0," + y + ")")
            .attr("width", barWidth)
            .attr("opacity", "0")
            .attr("class", "text" + j);*/
    }

    tl.to($("#mainArray").find("rect"), animationTime, {opacity:1});
}

function createTextElement(elementNr, length, startY, startValue) {
    mainArray.append("text")
        .text(startValue)
        .attr("x",elementNr * (width / length) + arrElementWidth / 2 + 5)
        .attr("y", 30+40)
        .attr("transform", "translate(0," + startY + ")")
        .attr("width", arrElementWidth)
        .attr("text-anchor", "middle")
        .style("opacity", "0")
        .attr("class", "text" + elementNr);
}

function add(index, textContent) {
    console.log("adding " + textContent + ", to index: " + index);
    var textbox = $(".text" + index);
    if(textbox.length == 0) {
        createTextElement(index, arrayList.capacity, 0, "");
        textbox = $(".text" + index);
    }
    tl.to(textbox, animationTime, {text:{value:textContent}, opacity:1, ease:Linear.easeNone});
}

function move(from, capacity, NewTextNeeded) {
    //if(NewTextNeeded) createTextElement(from, arrayList.capacity, 0, "");
    console.log("Move" + from);
    console.log(NewTextNeeded);
    var element = $(".text" + from);
    var oldElement = $(".text" + (from-1));

        tl.to(element, animationTime, {attr:{x:((from-1) * (width / capacity) + arrElementWidth / 2 + 5)}, ease:Linear.easeNone})
        .to(oldElement, animationTime, {opacity:"0", ease:Linear.easeNone}, '-=' + animationTime);

        oldElement.attr('class', "");
        element.attr('class', "text" + (from-1));
}

function set(index, textContent) {
    var textbox = $(".text" + index);
    tl.to(textbox, animationTime, {text:{value:textContent}, ease:Linear.easeNone});
}

function extendCapacity(newCapacity, oldCapacity) {
    var oldArray = $("#mainArray rect");
    createArray(newCapacity, oldCapacity, 100);

    //for(var j = 0; j < oldCapacity; j++) {
    //    createTextElement(j, oldCapacity, 0, arrayList.theItems[j]);
    //}

    //var texts = $("#mainArray").find("text");

    for(var i = 0; i < oldCapacity; i++) {
        //$(".text" + i).css("opacity", "1");
        tl.to($(".text" + i), animationTime, {y:100});
    }

    tl.to(oldArray, animationTime, {opacity:0});

    tl.to($("#mainArray").find("rect, text"), animationTime, {y:0});
}

function updateTheSize(newSize, length) {
    tl.to($("#theSizeBlock"), animationTime, {attr:{width:(newSize * (width / length) + 1.25)}});
    if(newSize >= 1) {
        tl.to($("#theSizeBlockText"), animationTime, {opacity:1});
    } else {
        tl.to($("#theSizeBlockText"), animationTime, {opacity:0});
    }
}

$( document ).ready(function() {
    //initCode();
});
<commit_msg>arraylist with elements at start<commit_after>var data = ["35", "33", "40"];

//var barWidth = 40;

//Array size
var arrElementWidth = 50;
var arrElementHeight = 50;

var width = (arrElementWidth + 10) * data.length;
var height = 350;

//Animation
var animationTime = 0.5;
var tl = new TimelineMax();
tl.pause();

//var arrayList = new ArrayList(data);
var theSize = 3;
var capacity = 5;

//PH - Code TODO get code from another source
var codeContent = [
    "",
    "function Arraylist(a) {",
    "    for(var gap = a.length / 2; gap > 0;",
    "        gap = gap === 2 ? 1 : parseInt(gap / 2.2)) {",
    "",
    "        for(var i = gap; i < a.length; i++) {",
    "            var tmp = a[i];",
    "",
    "            for(var j = i; j >= gap && tmp < a[j - gap]; j-= gap) {",
    "                a[j] = a[j - gap];",
    "            }",
    "            a[j] = tmp;",
    "        }",
    "    }",
    "    return a;",
    "}"
];

var code = d3.select("#code-text");
var drawingArea = d3.select(".drawingArea").append("svg:svg");

var theSizeBlock = drawingArea.append("g");
theSizeBlock.append("rect")
    .attr("width", 0)
    .attr("height", (arrElementHeight + 40 + 10))
    .attr("id", "theSizeBlock")
    .attr("fill", "lime");

theSizeBlock.append("text")
    .attr("y", 25)
    .attr("x", 10)
    .attr("id", "theSizeBlockText")
    .style("opacity", "0")
    .text("theSize");

var mainArray = drawingArea.append("g")
    .attr("id", "mainArray");

var arrayList;
start(data);

function start(newData) {
    $("#mainArray").empty();
    data = newData;
    var capacity = DEFAULT_CAPACITY;
    while(capacity < data.length) capacity = capacity * 2 + 1;
    createArray(capacity, 0, 0, 1);
    for(var i = 0; i < capacity; i++) {
        if(i < data.length) createTextElement(i, capacity, 0, data[i], 1);
        else createTextElement(i, capacity, 0, "", 1);
    }
    theSizeBlock.selectAll("*").attr("width", data.length * (width / capacity) + 1.25)
        .style("opacity", 1);
    arrayList = new ArrayList();
    arrayList.theItems = data;
    arrayList.capacity = capacity;
    arrayList.theSize = data.length;
}

function createArray(length, oldlength, y, opacity) {

    width = (arrElementWidth + 10) * length;

    drawingArea.attr("width", width + 150)
        .attr("height", height);

    for(var i = 0; i < length; i++) {
        mainArray.insert("svg:rect", ":first-child")
            .attr("x", i * ((width) / length) + 5 )
            .attr("y", 40)
            .attr("transform", "translate(0," + y + ")")
            .attr("height", arrElementHeight)
            .attr("width", arrElementWidth)
            .attr("fill", "red")
            .style("opacity", opacity)
            .attr("class", "rect" + i );
    }

    for(var j = oldlength; j < length; j++) {
        createTextElement(j, length, y, "", 0);
/*        mainArray.append("text")
            .text("")
            .attr("x",j * (width / length) + arrElementWidth / 3 + 5)
            .attr("y", 30+40)
            .attr("transform", "translate(0," + y + ")")
            .attr("width", barWidth)
            .attr("opacity", "0")
            .attr("class", "text" + j);*/
    }

    tl.to($("#mainArray").find("rect"), animationTime, {opacity:1});
}

function createTextElement(elementNr, length, startY, startValue, opacity) {
    mainArray.append("text")
        .text(startValue)
        .attr("x",elementNr * (width / length) + arrElementWidth / 2 + 5)
        .attr("y", 30+40)
        .attr("transform", "translate(0," + startY + ")")
        .attr("width", arrElementWidth)
        .attr("text-anchor", "middle")
        .style("opacity", opacity)
        .attr("class", "text" + elementNr);
}

function add(index, textContent) {
    console.log("adding " + textContent + ", to index: " + index);
    var textbox = $(".text" + index);
    if(textbox.length == 0) {
        createTextElement(index, arrayList.capacity, 0, "", 0);
        textbox = $(".text" + index);
    }
    tl.to(textbox, animationTime, {text:{value:textContent}, opacity:1, ease:Linear.easeNone});
}

function move(from, capacity, NewTextNeeded) {
    //if(NewTextNeeded) createTextElement(from, arrayList.capacity, 0, "");
    console.log("Move" + from);
    console.log(NewTextNeeded);
    var element = $(".text" + from);
    var oldElement = $(".text" + (from-1));

        tl.to(element, animationTime, {attr:{x:((from-1) * (width / capacity) + arrElementWidth / 2 + 5)}, ease:Linear.easeNone})
        .to(oldElement, animationTime, {opacity:"0", ease:Linear.easeNone}, '-=' + animationTime);

        oldElement.attr('class', "");
        element.attr('class', "text" + (from-1));
}

function set(index, textContent) {
    var textbox = $(".text" + index);
    tl.to(textbox, animationTime, {text:{value:textContent}, ease:Linear.easeNone});
}

function extendCapacity(newCapacity, oldCapacity) {
    var oldArray = $("#mainArray rect");
    createArray(newCapacity, oldCapacity, 100, 0);

    //for(var j = 0; j < oldCapacity; j++) {
    //    createTextElement(j, oldCapacity, 0, arrayList.theItems[j]);
    //}

    //var texts = $("#mainArray").find("text");

    for(var i = 0; i < oldCapacity; i++) {
        //$(".text" + i).css("opacity", "1");
        tl.to($(".text" + i), animationTime, {y:100});
    }

    tl.to(oldArray, animationTime, {opacity:0});

    tl.to($("#mainArray").find("rect, text"), animationTime, {y:0});
}

function updateTheSize(newSize, length) {
    tl.to($("#theSizeBlock"), animationTime, {attr:{width:(newSize * (width / length) + 1.25)}});
    if(newSize >= 1) {
        tl.to($("#theSizeBlockText"), animationTime, {opacity:1});
    } else {
        tl.to($("#theSizeBlockText"), animationTime, {opacity:0});
    }
}

$( document ).ready(function() {
    //initCode();
});
<|endoftext|>


<commit_before>var _ = require('../util')
var templateParser = require('../parsers/template')

/**
 * Process an element or a DocumentFragment based on a
 * instance option object. This allows us to transclude
 * a template node/fragment before the instance is created,
 * so the processed fragment can then be cloned and reused
 * in v-repeat.
 *
 * @param {Element} el
 * @param {Object} options
 * @return {Element|DocumentFragment}
 */

module.exports = function transclude (el, options) {
  // for template tags, what we want is its content as
  // a documentFragment (for block instances)
  if (el.tagName === 'TEMPLATE') {
    el = templateParser.parse(el)
  }
  if (options && options.template) {
    el = transcludeTemplate(el, options)
  }
  if (el instanceof DocumentFragment) {
    _.prepend(document.createComment('v-start'), el)
    el.appendChild(document.createComment('v-end'))
  }
  return el
}

/**
 * Process the template option.
 * If the replace option is true this will swap the $el.
 *
 * @param {Element} el
 * @param {Object} options
 * @return {Element|DocumentFragment}
 */

function transcludeTemplate (el, options) {
  var template = options.template
  var frag = templateParser.parse(template, true)
  if (!frag) {
    _.warn('Invalid template option: ' + template)
  } else {
    var rawContent = options._content || _.extractContent(el)
    if (options.replace) {
      if (frag.childNodes.length > 1) {
        transcludeContent(frag, rawContent)
        _.copyAttributes(el, frag.firstChild)
        return frag
      } else {
        var replacer = frag.firstChild
        _.copyAttributes(el, replacer)
        transcludeContent(replacer, rawContent)
        return replacer
      }
    } else {
      el.appendChild(frag)
      transcludeContent(el, rawContent)
      return el
    }
  }
}

/**
 * Resolve <content> insertion points mimicking the behavior
 * of the Shadow DOM spec:
 *
 *   http://w3c.github.io/webcomponents/spec/shadow/#insertion-points
 *
 * @param {Element|DocumentFragment} el
 * @param {Element} raw
 */

function transcludeContent (el, raw) {
  var outlets = getOutlets(el)
  var i = outlets.length
  if (!i) return
  var outlet, select, selected, j, main
  // first pass, collect corresponding content
  // for each outlet.
  while (i--) {
    outlet = outlets[i]
    if (raw) {
      select = outlet.getAttribute('select')
      if (select) {  // select content
        selected = raw.querySelectorAll(select)
        if (selected.length) {
          selected = _.toArray(selected).filter(function(node) {
            return node.parentNode === raw
          })
        }
        outlet.content = selected.length
          ? selected
          : _.toArray(outlet.childNodes)
      } else { // default content
        main = outlet
      }
    } else { // fallback content
      outlet.content = _.toArray(outlet.childNodes)
    }
  }
  // second pass, actually insert the contents
  for (i = 0, j = outlets.length; i < j; i++) {
    outlet = outlets[i]
    if (outlet !== main) {
      insertContentAt(outlet, outlet.content)
    }
  }
  // finally insert the main content
  if (main) {
    insertContentAt(main, _.toArray(raw.childNodes))
  }
}

/**
 * Get <content> outlets from the element/list
 *
 * @param {Element|Array} el
 * @return {Array}
 */

var concat = [].concat
function getOutlets (el) {
  return _.isArray(el)
    ? concat.apply([], el.map(getOutlets))
    : el.querySelectorAll
      ? _.toArray(el.querySelectorAll('content'))
      : []
}

/**
 * Insert an array of nodes at outlet,
 * then remove the outlet.
 *
 * @param {Element} outlet
 * @param {Array} contents
 */

function insertContentAt (outlet, contents) {
  // not using util DOM methods here because
  // parentNode can be cached
  var parent = outlet.parentNode
  for (var i = 0, j = contents.length; i < j; i++) {
    parent.insertBefore(contents[i], outlet)
  }
  parent.removeChild(outlet)
}<commit_msg>make jshint pass + minor adjustments for #787<commit_after>var _ = require('../util')
var templateParser = require('../parsers/template')

/**
 * Process an element or a DocumentFragment based on a
 * instance option object. This allows us to transclude
 * a template node/fragment before the instance is created,
 * so the processed fragment can then be cloned and reused
 * in v-repeat.
 *
 * @param {Element} el
 * @param {Object} options
 * @return {Element|DocumentFragment}
 */

module.exports = function transclude (el, options) {
  // for template tags, what we want is its content as
  // a documentFragment (for block instances)
  if (el.tagName === 'TEMPLATE') {
    el = templateParser.parse(el)
  }
  if (options && options.template) {
    el = transcludeTemplate(el, options)
  }
  if (el instanceof DocumentFragment) {
    _.prepend(document.createComment('v-start'), el)
    el.appendChild(document.createComment('v-end'))
  }
  return el
}

/**
 * Process the template option.
 * If the replace option is true this will swap the $el.
 *
 * @param {Element} el
 * @param {Object} options
 * @return {Element|DocumentFragment}
 */

function transcludeTemplate (el, options) {
  var template = options.template
  var frag = templateParser.parse(template, true)
  if (!frag) {
    _.warn('Invalid template option: ' + template)
  } else {
    var rawContent = options._content || _.extractContent(el)
    if (options.replace) {
      if (frag.childNodes.length > 1) {
        transcludeContent(frag, rawContent)
        _.copyAttributes(el, frag.firstChild)
        return frag
      } else {
        var replacer = frag.firstChild
        _.copyAttributes(el, replacer)
        transcludeContent(replacer, rawContent)
        return replacer
      }
    } else {
      el.appendChild(frag)
      transcludeContent(el, rawContent)
      return el
    }
  }
}

/**
 * Resolve <content> insertion points mimicking the behavior
 * of the Shadow DOM spec:
 *
 *   http://w3c.github.io/webcomponents/spec/shadow/#insertion-points
 *
 * @param {Element|DocumentFragment} el
 * @param {Element} raw
 */

function transcludeContent (el, raw) {
  var outlets = getOutlets(el)
  var i = outlets.length
  if (!i) return
  var outlet, select, selected, j, main

  function isDirectChild (node) {
    return node.parentNode === raw
  }

  // first pass, collect corresponding content
  // for each outlet.
  while (i--) {
    outlet = outlets[i]
    if (raw) {
      select = outlet.getAttribute('select')
      if (select) {  // select content
        selected = raw.querySelectorAll(select)
        if (selected.length) {
          // according to Shadow DOM spec, `select` can
          // only select direct children of the host node.
          // enforcing this also fixes #786.
          selected = [].filter.call(selected, isDirectChild)
        }
        outlet.content = selected.length
          ? selected
          : _.toArray(outlet.childNodes)
      } else { // default content
        main = outlet
      }
    } else { // fallback content
      outlet.content = _.toArray(outlet.childNodes)
    }
  }
  // second pass, actually insert the contents
  for (i = 0, j = outlets.length; i < j; i++) {
    outlet = outlets[i]
    if (outlet !== main) {
      insertContentAt(outlet, outlet.content)
    }
  }
  // finally insert the main content
  if (main) {
    insertContentAt(main, _.toArray(raw.childNodes))
  }
}

/**
 * Get <content> outlets from the element/list
 *
 * @param {Element|Array} el
 * @return {Array}
 */

var concat = [].concat
function getOutlets (el) {
  return _.isArray(el)
    ? concat.apply([], el.map(getOutlets))
    : el.querySelectorAll
      ? _.toArray(el.querySelectorAll('content'))
      : []
}

/**
 * Insert an array of nodes at outlet,
 * then remove the outlet.
 *
 * @param {Element} outlet
 * @param {Array} contents
 */

function insertContentAt (outlet, contents) {
  // not using util DOM methods here because
  // parentNode can be cached
  var parent = outlet.parentNode
  for (var i = 0, j = contents.length; i < j; i++) {
    parent.insertBefore(contents[i], outlet)
  }
  parent.removeChild(outlet)
}<|endoftext|>


<commit_before>import { Component } from './component.js';

export default function createComponent(Constructor, props, context) {
  let instance;

  if (Constructor.prototype && Constructor.prototype.render) {
    instance = new Constructor(props, context);
    Component.call(instance, props, context, true);
    instance = instance.render();
  } else {
    instance = Constructor(props);
  }

  return instance;
}
<commit_msg>[FIX #9] Add instance and venode in the return of the createComponent in lifecycle.js<commit_after>import { Component } from './component.js';

export default function createComponent(Constructor, props, context) {
  let instance, vnode;

  if (Constructor.prototype && Constructor.prototype.render) {
    instance = new Constructor(props, context);
    Component.call(instance, props, context, true);
    vnode = instance.render();
  } else {
    instance = vnode = Constructor(props);
  }

  return {instance, vnode};
}
<|endoftext|>