<commit_before>/**
 * Recursive flatten function with depth.
 *
 * @param  {Array}  array
 * @param  {Array}  result
 * @param  {Number} depth
 * @return {Array}
 */
function flattenDepth (array, result, depth) {
  for (var i = 0; i < array.length; i++) {
    var value = array[i]

    if (depth > 0 && Array.isArray(value)) {
      flattenDepth(value, result, depth - 1)
    } else {
      result.push(value)
    }
  }

  return result
}

/**
 * Recursive flatten function. Omitting depth is slightly faster.
 *
 * @param  {Array} array
 * @param  {Array} result
 * @return {Array}
 */
function flattenForever (array, result) {
  for (var i = 0; i < array.length; i++) {
    var value = array[i]

    if (Array.isArray(value)) {
      flattenForever(value, result)
    } else {
      result.push(value)
    }
  }

  return result
}

/**
 * Flatten an array, with the ability to define a depth.
 *
 * @param  {Array}  array
 * @param  {Number} depth
 * @return {Array}
 */
module.exports = function (array, depth) {
  if (depth == null) {
    return flattenForever(array, [])
  }

  return flattenDepth(array, [], depth)
}
<commit_msg>Use strict mode<commit_after>'use strict'

/**
 * Recursive flatten function with depth.
 *
 * @param  {Array}  array
 * @param  {Array}  result
 * @param  {Number} depth
 * @return {Array}
 */
function flattenDepth (array, result, depth) {
  for (var i = 0; i < array.length; i++) {
    var value = array[i]

    if (depth > 0 && Array.isArray(value)) {
      flattenDepth(value, result, depth - 1)
    } else {
      result.push(value)
    }
  }

  return result
}

/**
 * Recursive flatten function. Omitting depth is slightly faster.
 *
 * @param  {Array} array
 * @param  {Array} result
 * @return {Array}
 */
function flattenForever (array, result) {
  for (var i = 0; i < array.length; i++) {
    var value = array[i]

    if (Array.isArray(value)) {
      flattenForever(value, result)
    } else {
      result.push(value)
    }
  }

  return result
}

/**
 * Flatten an array, with the ability to define a depth.
 *
 * @param  {Array}  array
 * @param  {Number} depth
 * @return {Array}
 */
module.exports = function (array, depth) {
  if (depth == null) {
    return flattenForever(array, [])
  }

  return flattenDepth(array, [], depth)
}
<|endoftext|>


<commit_before>/* jshint maxdepth: 6 */

(function(W, U) {
	'use strict';

	var filters = {
			num: function(seg) {
				return Number(parseInt(seg)) == seg;
			}
		},
		any = [],
		routes,
		segs,
		uri,

		/**
		 * Recursively process routes
		 *
		 * @private
		 * @param {string} route - route to evaluate
		 * @param {int} i - current index in iteration
		 * @param {int} total - total number of routes
		 * @param {string} [event='load'] - lifecycle event
		 */
		_process = function(route, i, total, event) {
			var seg = segs[i],
				keys = Object.keys(route),
				x = 0;
			i++;

			// Match against patterns
			for (; x < keys.length; x++) {
				var key = keys[x],
					child = route[key],
					opts = key.split('||'),
					k = 0,
					y = i,
					match = false,
					ran = false;

				for (; k < opts.length; k++) {
					var opt = opts[k],
						parts = opt.split(':'),
						history = event != U,
						negate = false,
						push = false,
						eq = false;

					// Ensure event type matches route type
					if ((! history && (
							parts.indexOf('unload') > -1 ||
							parts.indexOf('pop') > -1)
						) ||
						(history && (
							! W.$isObject(child) &&
							parts.indexOf(event) < 0
						))) {
						continue;
					}

					// Set option to rule root
					if (parts.length > 1) {
						opt = parts[0];
					}

					// Negate routes prefixed by !
					if (opt[0] == '!') {
						opt = opt.slice(1);
						negate = true;
					}

					// Move the segment pointer back one level
					if (parts.indexOf('eval') > -1) {
						y--;
					}

					if (opt == seg) {
						eq = true;
					} else if (opt[0] == '$') {
						opt = opt.slice(1);

						if (opt == 'any') {
							eq = true;

							if (parts.indexOf('fire') > -1) {
								ran = true;
							} else if (! W.$isObject(child)) {
								push = true;
							}
						} else if (opt == 'root') {
							if (! seg) {
								eq = true;
								ran = true;
							}
						} else if (opt[0] == '/') {
							var split = opt.split('/');

							if (new RegExp(split[1], split[2] || U).test(seg)) {
								eq = true;
							}
						} else {
							var filter = filters[opt];

							if (filter) {
								if (filter(seg, child, y) === true) {
									eq = true;
									push = true;
								}
							} else if (seg && seg.trim() !== '') {
								eq = true;
							}
						}
					}

					// Invert the equality if the route is negated
					if (negate) {
						eq = ! eq;
					}

					if (eq) {
						// If ran is true then execute the route immediately
						if (ran) {
							W.$exec(child, {
								args: seg
							});
						}

						// If push is true then push the route to the any queue
						if (push) {
							ran = true;
							any.push([child, seg]);
						}

						// Remove the route if set to once
						if (parts.indexOf('once') > -1) {
							delete route[key];
						}

						// Set match to true and break on match
						match = true;
						break;
					}
				}

				// If matched then process recursively or execute if applicable
				if (match) {
					if (W.$isObject(child)) {
						_process(child, y, total, event);
					} else if (! ran && y === total) {
						W.$exec(child, {
							args: seg
						});
					}
				}
			}
		};

	W.routes = {
		/**
		 * Get current URI values or set with string or value
		 *
		 * @param {(object|string)} [value]
		 * @param {string} [value.full]
		 * @param {string} [value.hash]
		 * @param {boolean} [value.history]
		 * @param {string} [value.path]
		 * @param {object} [value.query]
		 * @param {Array} [value.segments]
		 * @param {string} [value.url]
		 * @returns {object} data
		 */
		uri: function(value) {
			if (value) {
				if (W.$isObject(value)) {
					uri = W.$extend(this.uri(), value);
					return uri;
				}

				var a = W._doc.createElement('a');
				a.href = value;

				var search = a.search,
					path = a.pathname.replace(/^\/|\/$/g, '');

				uri = {
					full: '/' + path + search + a.hash,
					hash: a.hash.slice(1),
					history: false,
					path: '/' + path,
					query: search ? W.$unserialize(search) : {},
					segments: path.split('/'),
					url: a.href
				};
			} else if (! uri) {
				uri = W.routes.uri(location.href);
			}

			return uri;
		},

		/**
		 * Get all segments or segment at index
		 *
		 * @param {int} [index]
		 * @returns {(Array|string)} segments
		 */
		segments: function(index) {
			var segs = this.uri().segments;

			return index !== U ? (segs[index] || '') : segs;
		},

		/**
		 * Retrieve or add route endpoints
		 *
		 * @param {object} obj - routes
		 * @param {bool} [init=false] - immediately evaluate routes
		 * @returns {object} routes
		 */
		map: function(obj, init) {
			var curr = routes || {};

			if (obj) {
				routes = W.$extend(curr, obj);

				if (init) {
					this.run({
						routes: routes
					});
				}
			}

			return curr;
		},

		/**
		 * Add conditional route filter
		 *
		 * @param {(object|string)} a - name or filter object
		 * @param {function} [b]
		 */
		addFilter: function(a, b) {
			W._extend(filters, a, b);
		},

		/**
		 * Evaluate routes against URI
		 *
		 * @param {object} [conf]
		 * @param {string} [conf.event='load']
		 * @param {string} [conf.path]
		 * @param {object} [conf.rules]
		 */
		run: function(conf) {
			conf = conf || {};
			var rules = conf.routes || routes;

			if (rules) {
				segs = conf.path ?
					conf.path.replace(/^\/|\/$/g, '').split(/#|\?/)[0].split('/') :
					this.segments();

				_process(rules, 0, segs.length, conf.event);

				// Execute queued init functions on last iteration
				if (any.length) {
					for (var i = 0; i < any.length; i++) {
						var rule = any[i];

						W.$exec(rule[0], {
							args: rule[1]
						});
					}

					// Clear array for next iteration
					any = [];
				}
			}
		}
	};
})(Wee, undefined);<commit_msg>Update run method JSDoc to match parameter name<commit_after>/* jshint maxdepth: 6 */

(function(W, U) {
	'use strict';

	var filters = {
			num: function(seg) {
				return Number(parseInt(seg)) == seg;
			}
		},
		any = [],
		routes,
		segs,
		uri,

		/**
		 * Recursively process routes
		 *
		 * @private
		 * @param {string} route - route to evaluate
		 * @param {int} i - current index in iteration
		 * @param {int} total - total number of routes
		 * @param {string} [event='load'] - lifecycle event
		 */
		_process = function(route, i, total, event) {
			var seg = segs[i],
				keys = Object.keys(route),
				x = 0;
			i++;

			// Match against patterns
			for (; x < keys.length; x++) {
				var key = keys[x],
					child = route[key],
					opts = key.split('||'),
					k = 0,
					y = i,
					match = false,
					ran = false;

				for (; k < opts.length; k++) {
					var opt = opts[k],
						parts = opt.split(':'),
						history = event != U,
						negate = false,
						push = false,
						eq = false;

					// Ensure event type matches route type
					if ((! history && (
							parts.indexOf('unload') > -1 ||
							parts.indexOf('pop') > -1)
						) ||
						(history && (
							! W.$isObject(child) &&
							parts.indexOf(event) < 0
						))) {
						continue;
					}

					// Set option to rule root
					if (parts.length > 1) {
						opt = parts[0];
					}

					// Negate routes prefixed by !
					if (opt[0] == '!') {
						opt = opt.slice(1);
						negate = true;
					}

					// Move the segment pointer back one level
					if (parts.indexOf('eval') > -1) {
						y--;
					}

					if (opt == seg) {
						eq = true;
					} else if (opt[0] == '$') {
						opt = opt.slice(1);

						if (opt == 'any') {
							eq = true;

							if (parts.indexOf('fire') > -1) {
								ran = true;
							} else if (! W.$isObject(child)) {
								push = true;
							}
						} else if (opt == 'root') {
							if (! seg) {
								eq = true;
								ran = true;
							}
						} else if (opt[0] == '/') {
							var split = opt.split('/');

							if (new RegExp(split[1], split[2] || U).test(seg)) {
								eq = true;
							}
						} else {
							var filter = filters[opt];

							if (filter) {
								if (filter(seg, child, y) === true) {
									eq = true;
									push = true;
								}
							} else if (seg && seg.trim() !== '') {
								eq = true;
							}
						}
					}

					// Invert the equality if the route is negated
					if (negate) {
						eq = ! eq;
					}

					if (eq) {
						// If ran is true then execute the route immediately
						if (ran) {
							W.$exec(child, {
								args: seg
							});
						}

						// If push is true then push the route to the any queue
						if (push) {
							ran = true;
							any.push([child, seg]);
						}

						// Remove the route if set to once
						if (parts.indexOf('once') > -1) {
							delete route[key];
						}

						// Set match to true and break on match
						match = true;
						break;
					}
				}

				// If matched then process recursively or execute if applicable
				if (match) {
					if (W.$isObject(child)) {
						_process(child, y, total, event);
					} else if (! ran && y === total) {
						W.$exec(child, {
							args: seg
						});
					}
				}
			}
		};

	W.routes = {
		/**
		 * Get current URI values or set with string or value
		 *
		 * @param {(object|string)} [value]
		 * @param {string} [value.full]
		 * @param {string} [value.hash]
		 * @param {boolean} [value.history]
		 * @param {string} [value.path]
		 * @param {object} [value.query]
		 * @param {Array} [value.segments]
		 * @param {string} [value.url]
		 * @returns {object} data
		 */
		uri: function(value) {
			if (value) {
				if (W.$isObject(value)) {
					uri = W.$extend(this.uri(), value);
					return uri;
				}

				var a = W._doc.createElement('a');
				a.href = value;

				var search = a.search,
					path = a.pathname.replace(/^\/|\/$/g, '');

				uri = {
					full: '/' + path + search + a.hash,
					hash: a.hash.slice(1),
					history: false,
					path: '/' + path,
					query: search ? W.$unserialize(search) : {},
					segments: path.split('/'),
					url: a.href
				};
			} else if (! uri) {
				uri = W.routes.uri(location.href);
			}

			return uri;
		},

		/**
		 * Get all segments or segment at index
		 *
		 * @param {int} [index]
		 * @returns {(Array|string)} segments
		 */
		segments: function(index) {
			var segs = this.uri().segments;

			return index !== U ? (segs[index] || '') : segs;
		},

		/**
		 * Retrieve or add route endpoints
		 *
		 * @param {object} obj - routes
		 * @param {bool} [init=false] - immediately evaluate routes
		 * @returns {object} routes
		 */
		map: function(obj, init) {
			var curr = routes || {};

			if (obj) {
				routes = W.$extend(curr, obj);

				if (init) {
					this.run({
						routes: routes
					});
				}
			}

			return curr;
		},

		/**
		 * Add conditional route filter
		 *
		 * @param {(object|string)} a - name or filter object
		 * @param {function} [b]
		 */
		addFilter: function(a, b) {
			W._extend(filters, a, b);
		},

		/**
		 * Evaluate routes against URI
		 *
		 * @param {object} [conf]
		 * @param {string} [conf.event='load']
		 * @param {string} [conf.path]
		 * @param {object} [conf.routes]
		 */
		run: function(conf) {
			conf = conf || {};
			var rules = conf.routes || routes;

			if (rules) {
				segs = conf.path ?
					conf.path.replace(/^\/|\/$/g, '').split(/#|\?/)[0].split('/') :
					this.segments();

				_process(rules, 0, segs.length, conf.event);

				// Execute queued init functions on last iteration
				if (any.length) {
					for (var i = 0; i < any.length; i++) {
						var rule = any[i];

						W.$exec(rule[0], {
							args: rule[1]
						});
					}

					// Clear array for next iteration
					any = [];
				}
			}
		}
	};
})(Wee, undefined);<|endoftext|>


<commit_before>// Made by camilleeyries (http://github.com/camilleeyries) (alias Faewui)

var AgarioClient = require('agario-client');
var amount = 30; //amount of bot
var begginAmount = amount;
var token = "null";
var myaccount = {c_user: "YOURCUSER", datr: "YOURDATR", xs: "YOURXS"};
var botChain = [];
var debugState = 0;
var serversChain = [];
var region = "EU-London";
var tempServ;
var interval;
var candidateFood = {};
var statChain = {averageMass: "NOT DEFINED !"};
var statInterval;
var statUpdateInterval;
var statScreenRefreshInterval = 100;
var statScreenUpdateInterval = 95;
var botMassChain = {};
var tempVar;
var connected = begginAmount;

var account = new AgarioClient.Account();
account.c_user = myaccount.c_user;
account.datr = myaccount.datr;
account.xs = myaccount.xs;

startStatScreen();

function ExampleBot(bot_id) {
    this.bot_id      = bot_id;         //ID of bot for logging
    this.nickname    = 'Facebots :\)'; //default nickname
    this.verbose     = false;           //default logging enabled
    this.interval_id = 0;              //here we will store setInterval's ID

    this.client       = new AgarioClient(this.bot_id); //create new client
    this.client.debug = 0; //lets set debug to 1
	this.server = '';
	this.auth_token = null;
}

ExampleBot.prototype = {
    log: function(text) {
        if(this.verbose) {
            console.log(this.bot_id + ' says: ' + text);
        }
    },

	reconnect: function() {
		anotherTempVar.client.connect(this.server);
	},

    connect: function(server) {
		this.server = server;
		this.client.auth_token = token;
		var randomNumber = (Math.floor((Math.random() * 10) + 1) * 1000);
		var truc = this;
		setTimeout(function () {
			truc.client.connect(truc.server);
		}, randomNumber);
		this.Events();

	},

    Events: function() {
        var bot = this;

        bot.client.on('connected', function() {
            bot.log('Connected, spawning');
            bot.client.spawn(bot.nickname);
        });

        bot.client.on('connectionError', function(e) {
            bot.log('Connection failed with reason: ' + e);
            bot.log('Server address set to: ' + bot.server + ' key ' + bot.server_key);
        });

		bot.client.on('ballAppear', function(id) {
			var ball = bot.client.balls[id];
			var candi;
			//console.log("candidateFood.bot" +bot.client.client_name);
			eval("candi = candidateFood.bot" +bot.client.client_name);
			if (ball.mass == 1 && candi == null) {
				eval("candidateFood.bot" + bot.client.client_name + " = " + id);
				//console.log("new candidate. mass: " + ball.mass);
				bot.client.moveTo(ball.x, ball.y);
			}

		});

		bot.client.on('packetError', function(packet, err, preventCrash) {
		   bot.client.log('Packet error detected for packet: ' + packet.toString());
		   bot.client.log('Crash will be prevented, bot will be disconnected');
		   preventCrash();
	//	   bot.client.disconnect();
		});

		bot.client.on('somebodyAteSomething', function(eater_id, eaten_id) {
			var candi;
			eval("candi = candidateFood.bot"+ bot.client.client_name);
			if (eaten_id = candi) {
				eval("candidateFood.bot" + bot.client.client_name + " = null");
				//console.log("my target was eated.");
			}
			if (bot.client.balls[bot.client.my_balls[0]] != undefined) {
				//console.log("										my size: " + bot.client.balls[bot.client.my_balls[0]].mass);
				updateBotMassChain(bot.client.balls[bot.client.my_balls[0]].mass, bot.client.client_name);
			}

		});

        bot.client.on('lostMyBalls', function() {
            bot.client.log('Lost all my balls, respawning');
            bot.client.spawn(bot.nickname);
        });

        bot.client.on('disconnect', function() {
            bot.client.log('Disconnected from server, bye!');
			connected--;
			console.log("connected bots: " +connected);
			var randomNumber = (Math.floor((Math.random() * 10) + 1) * 1000);
			setTimeout(function () {
				bot.client.connect(bot.server);
				connected++;
				console.log("connected bots: " +connected);
			}, randomNumber);
        });

        bot.client.on('reset', function() { //when client clears everything (connection lost?)
		//	console.log("connection lost !					" + bot.client.client_name);
		/*	var randomNumber = (Math.floor((Math.random() * 10) + 1) * 1000);
			setTimeout(function () {
				bot.client.connect(bot.server);
			}, randomNumber);*/

        });

		bot.client.on('experienceUpdate', function(level, current_exp, need_exp) { //if facebook key used and server sent exp info
		    bot.client.log('Current Level' + level + ' and experience is ' + current_exp + '/' + need_exp);
		});

    }
};

account.requestFBToken(function(obtainedToken, info) {
    //If you have `token` then you can set it to `client.auth_token`
    // and `client.connect()` to agar server
	if (info.error) console.log('error when trying to obtain fb token: ' + info.error);

	token = obtainedToken;
	console.log("\033[44m\033[31mTOKEN : \033[32m" + token);
	console.log("\033[31mexpire in : \033[32m" + account.token_expire);
	console.log(account);
	start();
});

function start() {

		if (token == "null") {
			return console.log('no token.');
		}
		else{
			if (debugState == 0)
				{
					console.log("\033[40m\033[35mcreating and assigning token to bots... \033[31mTOKEN: \033[32m" + token + "\033[37m");
					debugState++;
				}

				ExampleBot.auth_token = token;
			makeServerChain();
		}

}

function makeServerChain() {
	amount = begginAmount;
	if (debugState == 1) {
		console.log("requesting different FFA servers for Bots...");
		debugState++;
	}
	while (amount !=0 ){
		RequestFFAServer();
		amount--;

	}
	if (amount == 0) {
		setTimeout(console.log('successfull ! !' + serversChain), 3000);
		amount = begginAmount;
	}
}

function RequestFFAServer() {
	AgarioClient.servers.getFFAServer({region: region}, function(srv) {
	    if(!srv.server) return console.log('Failed to request server (error=' + srv.error + ', error_source=' + srv.error_source + ')'); // in case of error...
		tmp = "ws://" + srv.server;
		console.log("Server IP: " + tmp);
		serversChain.push(tmp);
		connectABot(tmp);
	});
}

function connectABot(server) {
	var Fbot = new ExampleBot(amount.toString());
	Fbot.connect(server);
	amount--;
}

function startStatScreen() {
//	statInterval = setInterval(printStatScreen, statScreenRefreshInterval);
	//statUpdateInterval = setInterval(recalculateStatScreen, statScreenUpdateInterval);
}

function printStatScreen() {
	console.log("\033[2J\033[;HAverage mass: " + statChain.averageMass);
}

function recalculateStatScreen() {
	//////////////////
	// AVERAGE MASS//
	/////////////////
	var tmpLength = Object.size(botMassChain);
	var i = 0;
	var tempNumber = 0;
	for (data in botMassChain) {
		tempNumber = tempNumber + data;
		statChain.averageMass = (tempNumber / tmpLength);
		console.log(statChain.averageMass + "  			" + tempNumber + "/" + tmpLength);
	}

}

function updateBotMassChain(mass, botName) {
	//console.log(botName);
	eval("botMassChain['bot" + botName + "'] = " + mass);
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
<commit_msg>renaming bots<commit_after>// Made by camilleeyries (http://github.com/camilleeyries) (alias Faewui)

var AgarioClient = require('agario-client');
var amount = 30; //amount of bot
var begginAmount = amount;
var token = "null";
var myaccount = {c_user: "YOURCUSER", datr: "YOURDATR", xs: "YOURXS"};
var botChain = [];
var debugState = 0;
var serversChain = [];
var region = "EU-London";
var tempServ;
var interval;
var candidateFood = {};
var statChain = {averageMass: "NOT DEFINED !"};
var statInterval;
var statUpdateInterval;
var statScreenRefreshInterval = 100;
var statScreenUpdateInterval = 95;
var botMassChain = {};
var tempVar;
var connected = begginAmount;

var account = new AgarioClient.Account();
account.c_user = myaccount.c_user;
account.datr = myaccount.datr;
account.xs = myaccount.xs;

startStatScreen();

function ExampleBot(bot_id) {
    this.bot_id      = bot_id;         //ID of bot for logging
    this.nickname    = 'AGAR-XPBOT'; //default nickname
    this.verbose     = false;           //default logging enabled
    this.interval_id = 0;              //here we will store setInterval's ID

    this.client       = new AgarioClient(this.bot_id); //create new client
    this.client.debug = 0; //lets set debug to 1
	this.server = '';
	this.auth_token = null;
}

ExampleBot.prototype = {
    log: function(text) {
        if(this.verbose) {
            console.log(this.bot_id + ' says: ' + text);
        }
    },

	reconnect: function() {
		anotherTempVar.client.connect(this.server);
	},

    connect: function(server) {
		this.server = server;
		this.client.auth_token = token;
		var randomNumber = (Math.floor((Math.random() * 10) + 1) * 1000);
		var truc = this;
		setTimeout(function () {
			truc.client.connect(truc.server);
		}, randomNumber);
		this.Events();

	},

    Events: function() {
        var bot = this;

        bot.client.on('connected', function() {
            bot.log('Connected, spawning');
            bot.client.spawn(bot.nickname);
        });

        bot.client.on('connectionError', function(e) {
            bot.log('Connection failed with reason: ' + e);
            bot.log('Server address set to: ' + bot.server + ' key ' + bot.server_key);
        });

		bot.client.on('ballAppear', function(id) {
			var ball = bot.client.balls[id];
			var candi;
			//console.log("candidateFood.bot" +bot.client.client_name);
			eval("candi = candidateFood.bot" +bot.client.client_name);
			if (ball.mass == 1 && candi == null) {
				eval("candidateFood.bot" + bot.client.client_name + " = " + id);
				//console.log("new candidate. mass: " + ball.mass);
				bot.client.moveTo(ball.x, ball.y);
			}

		});

		bot.client.on('packetError', function(packet, err, preventCrash) {
		   bot.client.log('Packet error detected for packet: ' + packet.toString());
		   bot.client.log('Crash will be prevented, bot will be disconnected');
		   preventCrash();
	//	   bot.client.disconnect();
		});

		bot.client.on('somebodyAteSomething', function(eater_id, eaten_id) {
			var candi;
			eval("candi = candidateFood.bot"+ bot.client.client_name);
			if (eaten_id = candi) {
				eval("candidateFood.bot" + bot.client.client_name + " = null");
				//console.log("my target was eated.");
			}
			if (bot.client.balls[bot.client.my_balls[0]] != undefined) {
				//console.log("										my size: " + bot.client.balls[bot.client.my_balls[0]].mass);
				updateBotMassChain(bot.client.balls[bot.client.my_balls[0]].mass, bot.client.client_name);
			}

		});

        bot.client.on('lostMyBalls', function() {
            bot.client.log('Lost all my balls, respawning');
            bot.client.spawn(bot.nickname);
        });

        bot.client.on('disconnect', function() {
            bot.client.log('Disconnected from server, bye!');
			connected--;
			console.log("connected bots: " +connected);
			var randomNumber = (Math.floor((Math.random() * 10) + 1) * 1000);
			setTimeout(function () {
				bot.client.connect(bot.server);
				connected++;
				console.log("connected bots: " +connected);
			}, randomNumber);
        });

        bot.client.on('reset', function() { //when client clears everything (connection lost?)
		//	console.log("connection lost !					" + bot.client.client_name);
		/*	var randomNumber = (Math.floor((Math.random() * 10) + 1) * 1000);
			setTimeout(function () {
				bot.client.connect(bot.server);
			}, randomNumber);*/

        });

		bot.client.on('experienceUpdate', function(level, current_exp, need_exp) { //if facebook key used and server sent exp info
		    bot.client.log('Current Level' + level + ' and experience is ' + current_exp + '/' + need_exp);
		});

    }
};

account.requestFBToken(function(obtainedToken, info) {
    //If you have `token` then you can set it to `client.auth_token`
    // and `client.connect()` to agar server
	if (info.error) console.log('error when trying to obtain fb token: ' + info.error);

	token = obtainedToken;
	console.log("\033[44m\033[31mTOKEN : \033[32m" + token);
	console.log("\033[31mexpire in : \033[32m" + account.token_expire);
	console.log(account);
	start();
});

function start() {

		if (token == "null") {
			return console.log('no token.');
		}
		else{
			if (debugState == 0)
				{
					console.log("\033[40m\033[35mcreating and assigning token to bots... \033[31mTOKEN: \033[32m" + token + "\033[37m");
					debugState++;
				}

				ExampleBot.auth_token = token;
			makeServerChain();
		}

}

function makeServerChain() {
	amount = begginAmount;
	if (debugState == 1) {
		console.log("requesting different FFA servers for Bots...");
		debugState++;
	}
	while (amount !=0 ){
		RequestFFAServer();
		amount--;

	}
	if (amount == 0) {
		setTimeout(console.log('successfull ! !' + serversChain), 3000);
		amount = begginAmount;
	}
}

function RequestFFAServer() {
	AgarioClient.servers.getFFAServer({region: region}, function(srv) {
	    if(!srv.server) return console.log('Failed to request server (error=' + srv.error + ', error_source=' + srv.error_source + ')'); // in case of error...
		tmp = "ws://" + srv.server;
		console.log("Server IP: " + tmp);
		serversChain.push(tmp);
		connectABot(tmp);
	});
}

function connectABot(server) {
	var Fbot = new ExampleBot(amount.toString());
	Fbot.connect(server);
	amount--;
}

function startStatScreen() {
//	statInterval = setInterval(printStatScreen, statScreenRefreshInterval);
	//statUpdateInterval = setInterval(recalculateStatScreen, statScreenUpdateInterval);
}

function printStatScreen() {
	console.log("\033[2J\033[;HAverage mass: " + statChain.averageMass);
}

function recalculateStatScreen() {
	//////////////////
	// AVERAGE MASS//
	/////////////////
	var tmpLength = Object.size(botMassChain);
	var i = 0;
	var tempNumber = 0;
	for (data in botMassChain) {
		tempNumber = tempNumber + data;
		statChain.averageMass = (tempNumber / tmpLength);
		console.log(statChain.averageMass + "  			" + tempNumber + "/" + tmpLength);
	}

}

function updateBotMassChain(mass, botName) {
	//console.log(botName);
	eval("botMassChain['bot" + botName + "'] = " + mass);
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp'),
    gutil = require('gulp-util'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    del = require('del'),
    uglifycss = require('gulp-uglifycss'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    scsslint = require('gulp-sass-lint'),
    jshint = require('gulp-jshint'),
    replace = require('gulp-replace'),
    rename = require('gulp-rename'),
    now = new Date().getTime();

var config = {
    sass: {
        includePaths: [
            'node_modules/govuk_frontend_toolkit/stylesheets',
            'node_modules/govuk-elements-sass/public/sass'
        ]
    },
    jsSrc: 'src/AppBundle/Resources/assets/javascripts',
    imgSrc: 'src/AppBundle/Resources/assets/images',
    sassSrc: 'src/AppBundle/Resources/assets/scss',
    viewsSrc: 'src/AppBundle/Resources/views',
    webAssets: 'web/assets/' + now,
    production: true
};

const setDevelopment = (done) => { // Non production
    config.production = false;
    done();
}

const cleanAssets = () => { // Clear web assets folder and formatted report css folder
    return del([
        'web/assets/*',
        config.viewsSrc + '/Css/*'

    ]);
}

const lintSass = () => { // sass quality control
    return gulp.src([
        config.sassSrc + '/**/*.scss',
        config.sassSrc + '/*.scss'])
        .pipe(scsslint());
}

const lintJS = () => { // JS quality control
    return gulp.src([config.jsSrc + '/**/*.js','!'+ config.jsSrc + '/**/details.polyfill.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
}

const CompileFormattedReportSassToCSS = () => {
    return gulp.src(config.sassSrc + '/formatted-report.scss')
        .pipe(!config.production ? sourcemaps.init() : gutil.noop())
        .pipe(sass(config.sass).on('error', sass.logError))
        .pipe(!config.production ? sourcemaps.write('./') : gutil.noop())
        .pipe(config.production ? uglifycss() : gutil.noop())
        .pipe(gulp.dest(config.viewsSrc + '/Css'));
}

const copyFormattedReportCSSToTwigVersion = () => {
    return gulp.src(config.viewsSrc + '/Css/formatted-report.css')
    .pipe(rename(config.viewsSrc + '/Css/formatted-report.css.twig'))
    .pipe(gulp.dest('./'));
}

const deleteFormattedReportCSSVersion = () => {
    return del([config.viewsSrc + '/Css/formatted-report.css']);
}

const buildApplicationCSSFromSass = () => { // Compile sass files, uglify, copy
    return gulp.src([
        config.sassSrc + '/application.scss',
        config.sassSrc + '/application-print.scss'])
        .pipe(!config.production ? sourcemaps.init() : gutil.noop())
        .pipe(sass(config.sass).on('error', sass.logError))
        .pipe(!config.production ? sourcemaps.write('./') : gutil.noop())
        .pipe(config.production ? uglifycss() : gutil.noop())
        .pipe(gulp.dest(config.webAssets + '/stylesheets'));
};

const makeImagePathsAbsoluteInGovUKCSSThenCopy = () => {
    return gulp.src([
            './node_modules/govuk_template_mustache/assets/stylesheets/fonts.css',
            './node_modules/govuk_template_mustache/assets/stylesheets/govuk-template.css',
        ])
        .pipe(replace('images/', '/images/'))
        .pipe(gulp.dest(config.webAssets + '/stylesheets'));
}

const copyGovUKFonts = () => {
    return gulp.src('node_modules/govuk_template_mustache/assets/stylesheets/fonts/*')
        .pipe(gulp.dest(config.webAssets + '/stylesheets/fonts'));
}
const copyAllImages = () => {
    return gulp.src([
            './node_modules/govuk_frontend_toolkit/images/**/*',
            './node_modules/govuk_template_mustache/assets/images/*',
            './node_modules/govuk_template_mustache/assets/stylesheets/images/**/*',
            './node_modules/govuk_template_mustache/assets/stylesheets/images/gov.uk_logotype_crown.png',
            config.imgSrc + '/**/*'
        ])
        .pipe(gulp.dest('./web/images'));
}

const concatJSThenMinifyAndCopy = () => { // Only minify if prod
    return gulp.src([
            './node_modules/govuk_template_mustache/assets/javascripts/govuk-template.js',
            './node_modules/govuk_frontend_toolkit/javascripts/govuk/show-hide-content.js',
            config.jsSrc + '/govuk/polyfill/*.js',
            config.jsSrc + '/modules/*.js',
            config.jsSrc + '/main.js'])
        .pipe(concat('application.js'))
        .pipe(config.production ? uglify() : gutil.noop())
        .pipe(gulp.dest(config.webAssets + '/javascripts'));
}

const copyJQuery = () => {
    return gulp.src([
        './node_modules/jquery/dist/jquery.min.js'])
        .pipe(gulp.dest(config.webAssets + '/javascripts'));
}

// Compile formatted report CSS and copy to twig, then delete the .css version
gulp.task('rebuild-formatted-report-css', gulp.series(CompileFormattedReportSassToCSS, copyFormattedReportCSSToTwigVersion, deleteFormattedReportCSSVersion));

gulp.task('sass', gulp.series(lintSass, buildApplicationCSSFromSass));

gulp.task('app-js', gulp.series(lintJS, concatJSThenMinifyAndCopy));

// Prepare and build all assets.
gulp.task('default', gulp.series(
    cleanAssets,
    lintSass,
    gulp.parallel(
        'sass',
        makeImagePathsAbsoluteInGovUKCSSThenCopy,
        copyAllImages,
        copyGovUKFonts,
        'app-js',
        copyJQuery,
        'rebuild-formatted-report-css'
    )));

// Watch sass, images and js and recompile as Development
gulp.task('watch', gulp.series(setDevelopment, function () {
    gulp.watch([
        config.sassSrc + '/**/*',
        config.sassSrc + '/*',
        config.imgSrc + '/**/*',
        config.jsSrc + '/**/*.js',
        config.jsSrc + '/*.js'],
        { interval: 1000 },
        gulp.series('default'));
}));
<commit_msg>DDPB-2366 Stop lintSass running twice<commit_after>'use strict';

const gulp = require('gulp'),
    gutil = require('gulp-util'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    del = require('del'),
    uglifycss = require('gulp-uglifycss'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    scsslint = require('gulp-sass-lint'),
    jshint = require('gulp-jshint'),
    replace = require('gulp-replace'),
    rename = require('gulp-rename'),
    now = new Date().getTime();

var config = {
    sass: {
        includePaths: [
            'node_modules/govuk_frontend_toolkit/stylesheets',
            'node_modules/govuk-elements-sass/public/sass'
        ]
    },
    jsSrc: 'src/AppBundle/Resources/assets/javascripts',
    imgSrc: 'src/AppBundle/Resources/assets/images',
    sassSrc: 'src/AppBundle/Resources/assets/scss',
    viewsSrc: 'src/AppBundle/Resources/views',
    webAssets: 'web/assets/' + now,
    production: true
};

const setDevelopment = (done) => { // Non production
    config.production = false;
    done();
}

const cleanAssets = () => { // Clear web assets folder and formatted report css folder
    return del([
        'web/assets/*',
        config.viewsSrc + '/Css/*'

    ]);
}

const lintSass = () => { // sass quality control
    return gulp.src([
        config.sassSrc + '/**/*.scss',
        config.sassSrc + '/*.scss'])
        .pipe(scsslint());
}

const lintJS = () => { // JS quality control
    return gulp.src([config.jsSrc + '/**/*.js','!'+ config.jsSrc + '/**/details.polyfill.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
}

const CompileFormattedReportSassToCSS = () => {
    return gulp.src(config.sassSrc + '/formatted-report.scss')
        .pipe(!config.production ? sourcemaps.init() : gutil.noop())
        .pipe(sass(config.sass).on('error', sass.logError))
        .pipe(!config.production ? sourcemaps.write('./') : gutil.noop())
        .pipe(config.production ? uglifycss() : gutil.noop())
        .pipe(gulp.dest(config.viewsSrc + '/Css'));
}

const copyFormattedReportCSSToTwigVersion = () => {
    return gulp.src(config.viewsSrc + '/Css/formatted-report.css')
    .pipe(rename(config.viewsSrc + '/Css/formatted-report.css.twig'))
    .pipe(gulp.dest('./'));
}

const deleteFormattedReportCSSVersion = () => {
    return del([config.viewsSrc + '/Css/formatted-report.css']);
}

const buildApplicationCSSFromSass = () => { // Compile sass files, uglify, copy
    return gulp.src([
        config.sassSrc + '/application.scss',
        config.sassSrc + '/application-print.scss'])
        .pipe(!config.production ? sourcemaps.init() : gutil.noop())
        .pipe(sass(config.sass).on('error', sass.logError))
        .pipe(!config.production ? sourcemaps.write('./') : gutil.noop())
        .pipe(config.production ? uglifycss() : gutil.noop())
        .pipe(gulp.dest(config.webAssets + '/stylesheets'));
};

const makeImagePathsAbsoluteInGovUKCSSThenCopy = () => {
    return gulp.src([
            './node_modules/govuk_template_mustache/assets/stylesheets/fonts.css',
            './node_modules/govuk_template_mustache/assets/stylesheets/govuk-template.css',
        ])
        .pipe(replace('images/', '/images/'))
        .pipe(gulp.dest(config.webAssets + '/stylesheets'));
}

const copyGovUKFonts = () => {
    return gulp.src('node_modules/govuk_template_mustache/assets/stylesheets/fonts/*')
        .pipe(gulp.dest(config.webAssets + '/stylesheets/fonts'));
}
const copyAllImages = () => {
    return gulp.src([
            './node_modules/govuk_frontend_toolkit/images/**/*',
            './node_modules/govuk_template_mustache/assets/images/*',
            './node_modules/govuk_template_mustache/assets/stylesheets/images/**/*',
            './node_modules/govuk_template_mustache/assets/stylesheets/images/gov.uk_logotype_crown.png',
            config.imgSrc + '/**/*'
        ])
        .pipe(gulp.dest('./web/images'));
}

const concatJSThenMinifyAndCopy = () => { // Only minify if prod
    return gulp.src([
            './node_modules/govuk_template_mustache/assets/javascripts/govuk-template.js',
            './node_modules/govuk_frontend_toolkit/javascripts/govuk/show-hide-content.js',
            config.jsSrc + '/govuk/polyfill/*.js',
            config.jsSrc + '/modules/*.js',
            config.jsSrc + '/main.js'])
        .pipe(concat('application.js'))
        .pipe(config.production ? uglify() : gutil.noop())
        .pipe(gulp.dest(config.webAssets + '/javascripts'));
}

const copyJQuery = () => {
    return gulp.src([
        './node_modules/jquery/dist/jquery.min.js'])
        .pipe(gulp.dest(config.webAssets + '/javascripts'));
}

// Compile formatted report CSS and copy to twig, then delete the .css version
gulp.task('rebuild-formatted-report-css', gulp.series(CompileFormattedReportSassToCSS, copyFormattedReportCSSToTwigVersion, deleteFormattedReportCSSVersion));

gulp.task('sass', gulp.series(lintSass, buildApplicationCSSFromSass));

gulp.task('app-js', gulp.series(lintJS, concatJSThenMinifyAndCopy));

// Prepare and build all assets.
gulp.task('default', gulp.series(
    cleanAssets,
    gulp.parallel(
        'sass',
        makeImagePathsAbsoluteInGovUKCSSThenCopy,
        copyAllImages,
        copyGovUKFonts,
        'app-js',
        copyJQuery,
        'rebuild-formatted-report-css'
    )));

// Watch sass, images and js and recompile as Development
gulp.task('watch', gulp.series(setDevelopment, function () {
    gulp.watch([
        config.sassSrc + '/**/*',
        config.sassSrc + '/*',
        config.imgSrc + '/**/*',
        config.jsSrc + '/**/*.js',
        config.jsSrc + '/*.js'],
        { interval: 1000 },
        gulp.series('default'));
}));
<|endoftext|>


<commit_before>import {isArr, isObj, arrEq, objEq, ensure} from './util';
import Promise from 'bluebird';
import reqlTermExamples from './ReqlTermExamples';

const DatumTerm = reqlTermExamples.DATUM.constructor;
const RDBVal = DatumTerm.__super__.constructor;
const TermBase = RDBVal.__super__.constructor;

// Monkey-patch rethinkdb driver AST terms with a validate method. The validate
// method takes a validation function as its only argument and appends it to
// the list of validate functions stored with this AST term. The validate
// method returns the updated AST term so that it can be chained with other
// calls. See astQueryMatches() below for more information.
TermBase.prototype.validate = function(validateFn) {
  this.validateFns = this.validateFns || [];
  this.validateFns.push(validateFn);
  return this;
};

// ReqlPatternTerm is an AST term that represents a pattern matching function
// inside a whitelist query.
//
// When an incoming query is matched against a pattern query, a term in the
// actual query that corresponds to this ReqlPatternTerm in the pattern query
// will cause us to run the supplied function as fn(actualTerm, refs, session),
// and it must return a boolean that determines whether the actual term matches
// the pattern.
class ReqlPatternTerm extends DatumTerm {
  constructor(fn) {
    super();
    ensure(fn instanceof Function, 'RP.check() requires a function argument');
    this.fn = fn;
  }

  build() {
    return this.fn;
  }

  compose() {
    return this.fn.toString();
  }
}

// ReqlPattern (exported to clients as RP) provides methods to construct
// whitelist queries that offer more sophisticated pattern matching than just
// exact match.
const ReqlPattern = {

  // When any term in a pattern query is created from RP.check(fn), it matches
  // the corresponding term in the actual query if and only if  fn(actualTerm,
  // refs, session) returns true. It must return a boolean, not a promise.
  //
  // The actualTerm argument is the JSON protocol encoding of the corresponding
  // term. For primitives (strings, numbers, and booleans), actualTerm will
  // just be that same primitive; but for arrays, objects, and other reql
  // terms, the JSON protocol encoding becomes relevant. The same applies for
  // RP.ref below.
  //
  // The refs argument is an object that can be used to keep track of terms in
  // the query so that the validate functions can refer to them easily. It starts
  // out as {} every time a query is validated. RP.check functions can mutate it.
  //
  // The session argument is used to track any state regarding the current
  // WebSocket client, for example the current user id. See the sessionCreator
  // option in index.js for more information.
  check(fn) {
    return new ReqlPatternTerm(fn);
  },

  // When any term in a pattern query is created from RP.ref(refName), it
  // always matches and then stores the corresponding term from the actual
  // query in refs[refName]. Like RP.check, it stores the JSON protocol
  // encoding of the corresponding term.
  //
  // Use RP.ref() to simplify keeping track of terms for validations. For
  // example, instead of:
  //
  // r.table("turtles")
  //  .filter({"herdId": RP.check((herdId, refs, session) => {
  //    refs.herdId = herdId;
  //    return true;
  //  })})
  //  .validate((refs, session) => session.curHerdId === refs.herdId)
  //
  // Try this instead:
  //
  // r.table("turtles")
  //  .filter({"herdId": RP.ref("herdId")})
  //  .validate((refs, session) => session.curHerdId === refs.herdId)
  ref(refName) {
    return new ReqlPatternTerm((value, refs, session) => {
      refs[refName] = value;
      return true;
    });
  },

};

// Return whether or not the specified object is a rethinkdb driver AST term.
const isReqlAstTerm = obj => obj instanceof TermBase;

// Compare the pattern query to the actual query to see if they match, and
// return a promise that resolves to true (false) if they matched (didn't
// match). Both queries should be in rethinkdb AST term form.
//
// If the actual query matches the pattern query data, then all of validate functions
// set on the pattern query will be called as validateFn(refs, session). Resolve
// to true if they all return true (or promises that resolve to true) or there
// are no validate functions. Resolve to false if the query data doesn't match or
// any validate function doesn't return true.
const astQueryMatches = (patternQuery, actualQuery, session) => {
  const refs = {};
  const deepMatch = (pattern, actual) => {
    return (
      pattern === actual
    ) || (
      pattern instanceof Function && pattern(actual, refs, session)
    ) || (
      isArr(pattern) && isArr(actual) && arrEq(pattern, actual, deepMatch)
    ) || (
      isObj(pattern) && isObj(actual) && objEq(pattern, actual, deepMatch)
    );
  };
  if (deepMatch(patternQuery.build(), actualQuery.build())) {
    const validateFns = patternQuery.validateFns || [];
    const promises = validateFns.map(fn => fn(refs, session));
    return Promise.all(promises).then(results => results.every(x => x));
  } else {
    return Promise.resolve(false);
  }
};

export {
  ReqlPattern,
  isReqlAstTerm,
  astQueryMatches,
};
<commit_msg>Refactor code<commit_after>import {isArr, isObj, arrEq, objEq, ensure} from './util';
import Promise from 'bluebird';
import reqlTermExamples from './ReqlTermExamples';

const DatumTerm = reqlTermExamples.DATUM.constructor;
const RDBVal = DatumTerm.__super__.constructor;
const TermBase = RDBVal.__super__.constructor;

// Monkey-patch rethinkdb driver AST terms with a validate method. The validate
// method takes a validation function as its only argument and appends it to
// the list of validate functions stored with this AST term. The validate
// method returns the updated AST term so that it can be chained with other
// calls. See astQueryMatches() below for more information.
TermBase.prototype.validate = function(validateFn) {
  this.validateFns = this.validateFns || [];
  this.validateFns.push(validateFn);
  return this;
};

// ReqlPatternTerm is an AST term that represents a pattern matching function
// inside a whitelist query.
//
// When an incoming query is matched against a pattern query, a term in the
// actual query that corresponds to this ReqlPatternTerm in the pattern query
// will cause us to run the supplied function as fn(actualTerm, refs, session),
// and it must return a boolean that determines whether the actual term matches
// the pattern.
class ReqlPatternTerm extends DatumTerm {
  constructor(fn) {
    super();
    ensure(fn instanceof Function, 'RP.check() requires a function argument');
    this.fn = fn;
  }

  build() {
    return this.fn;
  }

  compose() {
    return this.fn.toString();
  }
}

// ReqlPattern (exported to clients as RP) provides methods to construct
// whitelist queries that offer more sophisticated pattern matching than just
// exact match.
const ReqlPattern = {

  // When any term in a pattern query is created from RP.check(fn), it matches
  // the corresponding term in the actual query if and only if  fn(actualTerm,
  // refs, session) returns true. It must return a boolean, not a promise.
  //
  // The actualTerm argument is the JSON protocol encoding of the corresponding
  // term. For primitives (strings, numbers, and booleans), actualTerm will
  // just be that same primitive; but for arrays, objects, and other reql
  // terms, the JSON protocol encoding becomes relevant. The same applies for
  // RP.ref below.
  //
  // The refs argument is an object that can be used to keep track of terms in
  // the query so that the validate functions can refer to them easily. It starts
  // out as {} every time a query is validated. RP.check functions can mutate it.
  //
  // The session argument is used to track any state regarding the current
  // WebSocket client, for example the current user id. See the sessionCreator
  // option in index.js for more information.
  check(fn) {
    return new ReqlPatternTerm(fn);
  },

  // When any term in a pattern query is created from RP.ref(refName), it
  // always matches and then stores the corresponding term from the actual
  // query in refs[refName]. Like RP.check, it stores the JSON protocol
  // encoding of the corresponding term.
  //
  // Use RP.ref() to simplify keeping track of terms for validations. For
  // example, instead of:
  //
  // r.table("turtles")
  //  .filter({"herdId": RP.check((herdId, refs, session) => {
  //    refs.herdId = herdId;
  //    return true;
  //  })})
  //  .validate((refs, session) => session.curHerdId === refs.herdId)
  //
  // Try this instead:
  //
  // r.table("turtles")
  //  .filter({"herdId": RP.ref("herdId")})
  //  .validate((refs, session) => session.curHerdId === refs.herdId)
  ref(refName) {
    return new ReqlPatternTerm((value, refs, session) => {
      refs[refName] = value;
      return true;
    });
  },

};

// Return whether or not the specified object is a rethinkdb driver AST term.
const isReqlAstTerm = obj => obj instanceof TermBase;

// Compare the pattern query to the actual query to see if they match, and
// return a promise that resolves to true (false) if they matched (didn't
// match). Both queries should be in rethinkdb AST term form.
//
// If the actual query matches the pattern query data, then all of validate functions
// set on the pattern query will be called as validateFn(refs, session). Resolve
// to true if they all return true (or promises that resolve to true) or there
// are no validate functions. Resolve to false if the query data doesn't match or
// any validate function doesn't return true.
const astQueryMatches = (patternQuery, actualQuery, session) => {
  const refs = {};
  const deepMatch = (pattern, actual) => {
    if (pattern instanceof Function) {
      return pattern(actual, refs, session);
    } else if (isArr(pattern)) {
      return isArr(actual) && arrEq(pattern, actual, deepMatch);
    } else if (isObj(pattern)) {
      return isObj(actual) && objEq(pattern, actual, deepMatch);
    }
    return pattern === actual;
  };
  if (deepMatch(patternQuery.build(), actualQuery.build())) {
    const validateFns = patternQuery.validateFns || [];
    const promises = validateFns.map(fn => fn(refs, session));
    return Promise.all(promises).then(results => results.every(x => x));
  } else {
    return Promise.resolve(false);
  }
};

export {
  ReqlPattern,
  isReqlAstTerm,
  astQueryMatches,
};
<|endoftext|>


<commit_before>'use strict';
const { src, dest, parallel, series, watch } = require('gulp');

const browsersync = require("browser-sync").create();
const cache = require('gulp-cached');
const fs = require('fs');
const handlebars = require('gulp-compile-handlebars');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const htmlmin = require('gulp-htmlmin');
const imagemin = require('gulp-imagemin');
const inlinesource = require('gulp-inline-source');
const jshint = require('gulp-jshint');
const layouts = require('handlebars-layouts');
const helper = require('handlebars-helper-repeat');
const plumber = require('gulp-plumber');
const reload = browserSync.reload;
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const sass = require('gulp-sass');
const scsslint = require('gulp-scss-lint');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const yaml = require('js-yaml');
const rimraf = require('rimraf');
const runSequence = require('run-sequence');
const notify = require('gulp-notify');
const vendor = require('gulp-concat');
const mainBowerFiles = require('main-bower-files');

handlebars.Handlebars.registerHelper(layouts(handlebars.Handlebars));
handlebars.Handlebars.registerHelper('repeat', helper);

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./src/assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

function scss() {
  return src('./src/assets/sass/*.scss')
    .pipe(plumber())
    .pipe(sass({
      outputStyle: 'compressed',
    }))
    .pipe(rename({suffix: '.min'}))
    .pipe(postcss([ autoprefixer(), cssnano() ])) // PostCSS plugins
    .pipe(dest(path.dist + 'css'))
    .pipe(browsersync.stream());
}

function css() {
  return src('./src/assets/css/*.css')
    .pipe(plumber())
    .pipe(dest(path.dist + 'css'))
    .pipe(browsersync.stream());
}

function images() {
  return src(globs.images)
    .pipe(plumber())
    .pipe(imagemin({
      progressive: true,
    }))
    .pipe(dest(path.dist + 'img'))
    .pipe(browsersync.stream());

}

function fonts() {
  return src(globs.fonts)
    .pipe(plumber())
    .pipe(dest(path.dist + 'fonts'))
    .pipe(browsersync.stream());
}

function email() {
  return src('./src/mail/**/**')
    .pipe(plumber())
    .pipe(dest('./dist/mail'))
    .pipe(browsersync.stream());
}

function template() {
  const templateData = yaml.safeLoad(fs.readFileSync('data.yml', 'utf-8'));
  const options = {
    ignorePartials: true, //ignores the unknown footer2 partial in the handlebars template, defaults to false
    batch: ['./src/partials/'],
    helpers: {
      capitals: function(str) {
        return str.toUpperCase();
      },
    },
  };
  return src('./src/templates/**/*.hbs')
    .pipe(plumber())
    .pipe(handlebars(templateData, options))
    .pipe(rename(function(path) {
      path.extname = '.html';
    }))
    .pipe(dest('./dist/'))
    .pipe(browsersync.stream());
}

function scripts() {
  return src('src/assets/js/*.js')
    .pipe(rename({suffix: '.min'}))
    .pipe(plumber())
    .pipe(uglify())
    .pipe(dest(path.dist + 'js'))
    .pipe(browsersync.stream());
}
function plugins() {
  return src(mainBowerFiles('**/*.min.js'))
    .pipe(vendor('scripts.min.js'))
    .pipe(dest(path.dist + 'js'))
    .pipe(browsersync.stream());
}

function clean(cb) {
  return rimraf('./dist/', cb);
}

var cbString = new Date().getTime();
function cacheBustTask(){
    return src(['./src/partials/base.hbs'])
        .pipe(replace(/cb=\d+/, 'cb=' + cbString))
        .pipe(dest('.'));
}

// BrowserSync
function browserSync(done) {
  browsersync.init({

    injectChanges: true,

    ghostMode: {
      clicks: false,
      forms: false,
      scroll: false,
    },
    server: {
      baseDir: "./dist/"
    },
    port: 3000
  });
  done();
}

// BrowserSync Reload
function browserSyncReload(done) {
  browsersync.reload();
  done();
}

// Watch files
function watchFiles() {
  watch("src/assets/css/**/*", series(css, browserSyncReload));
  watch([
    "src/assets/sass/**/*"
  ],
    series(scss, browserSyncReload)
  );
  watch([
    "src/assets/js/**/*",
  ],
    series(plugins, scripts, browserSyncReload)
  );
  watch(
    [
      "src/templates/**/*",
      "src/partials/**/*"
    ],
    series(template, browserSyncReload)
  );
  watch("src/assets/fonts/**/*", series(fonts, browserSyncReload));
  watch("src/assets/img/**/*", series(images, browserSyncReload));
}

// define complex tasks
const js = series(plugins, scripts);
const build = series(clean, parallel(css, scss, images, template, js, fonts, email));
const serve = series(clean, parallel(build, watchFiles, browserSync));

exports.fonts = fonts;
exports.images = images;
exports.css = css;
exports.scss = scss;
exports.email = email;
exports.clean = clean;
exports.js = js;
exports.build = build;
exports.serve = serve;
exports.default = build;<commit_msg>Update Gulp<commit_after>'use strict';
const { src, dest, parallel, series, watch } = require('gulp');

const browsersync = require("browser-sync").create();
const cache = require('gulp-cached');
const fs = require('fs');
const handlebars = require('gulp-compile-handlebars');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const htmlmin = require('gulp-htmlmin');
const imagemin = require('gulp-imagemin');
const inlinesource = require('gulp-inline-source');
const jshint = require('gulp-jshint');
const layouts = require('handlebars-layouts');
const helper = require('handlebars-helper-repeat');
const plumber = require('gulp-plumber');
const reload = browserSync.reload;
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const sass = require('gulp-sass');
const scsslint = require('gulp-scss-lint');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const yaml = require('js-yaml');
const rimraf = require('rimraf');
const runSequence = require('run-sequence');
const notify = require('gulp-notify');
const vendor = require('gulp-concat');
const mainBowerFiles = require('main-bower-files');

handlebars.Handlebars.registerHelper(layouts(handlebars.Handlebars));
handlebars.Handlebars.registerHelper('repeat', helper);

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./src/assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

function scss() {
  return src('./src/assets/sass/*.scss')
    .pipe(plumber())
    .pipe(sass({
      outputStyle: 'compressed',
    }))
    .pipe(rename({suffix: '.min'}))
    .pipe(postcss([ autoprefixer(), cssnano() ])) // PostCSS plugins
    .pipe(dest(path.dist + 'css'))
    .pipe(browsersync.stream());
}

function css() {
  return src('./src/assets/css/*.css')
    .pipe(plumber())
    .pipe(dest(path.dist + 'css'))
    .pipe(browsersync.stream());
}

function images() {
  return src(globs.images)
    .pipe(plumber())
    .pipe(imagemin({
      progressive: true,
    }))
    .pipe(dest(path.dist + 'img'))
    .pipe(browsersync.stream());

}

function fonts() {
  return src(globs.fonts)
    .pipe(plumber())
    .pipe(dest(path.dist + 'fonts'))
    .pipe(browsersync.stream());
}

function email() {
  return src('./src/mail/**/**')
    .pipe(plumber())
    .pipe(dest('./dist/mail'))
    .pipe(browsersync.stream());
}

function template() {
  const templateData = yaml.safeLoad(fs.readFileSync('data.yml', 'utf-8'));
  const options = {
    ignorePartials: true, //ignores the unknown footer2 partial in the handlebars template, defaults to false
    batch: ['./src/partials/'],
    helpers: {
      capitals: function(str) {
        return str.toUpperCase();
      },
    },
  };
  return src('./src/templates/**/*.hbs')
    .pipe(plumber())
    .pipe(handlebars(templateData, options))
    .pipe(rename(function(path) {
      path.extname = '.html';
    }))
    .pipe(dest('./dist/'))
    .pipe(browsersync.stream());
}

function scripts() {
  return src('src/assets/js/*.js')
    .pipe(rename({suffix: '.min'}))
    .pipe(plumber())
    .pipe(uglify())
    .pipe(dest(path.dist + 'js'))
    .pipe(browsersync.stream());
}
function plugins() {
  return src(mainBowerFiles('**/*.js'))
    .pipe(vendor('scripts.min.js'))
    .pipe(plumber())
    .pipe(uglify())
    .pipe(dest(path.dist + 'js'))
    .pipe(browsersync.stream());
}

function clean(cb) {
  return rimraf('./dist/', cb);
}

var cbString = new Date().getTime();
function cacheBustTask(){
    return src(['./src/partials/base.hbs'])
        .pipe(replace(/cb=\d+/, 'cb=' + cbString))
        .pipe(dest('.'));
}

// BrowserSync
function browserSync(done) {
  browsersync.init({

    injectChanges: true,

    ghostMode: {
      clicks: false,
      forms: false,
      scroll: false,
    },
    server: {
      baseDir: "./dist/"
    },
    port: 3000
  });
  done();
}

// BrowserSync Reload
function browserSyncReload(done) {
  browsersync.reload();
  done();
}

// Watch files
function watchFiles() {
  watch("src/assets/css/**/*", series(css, browserSyncReload));
  watch([
    "src/assets/sass/**/*"
  ],
    series(scss, browserSyncReload)
  );
  watch([
    "src/assets/js/**/*",
  ],
    series(plugins, scripts, browserSyncReload)
  );
  watch(
    [
      "src/templates/**/*",
      "src/partials/**/*"
    ],
    series(template, browserSyncReload)
  );
  watch("src/assets/fonts/**/*", series(fonts, browserSyncReload));
  watch("src/assets/img/**/*", series(images, browserSyncReload));
}

// define complex tasks
const js = series(plugins, scripts);
const build = series(clean, parallel(css, scss, images, template, js, fonts, email));
const serve = series(clean, parallel(build, watchFiles, browserSync));

exports.fonts = fonts;
exports.images = images;
exports.css = css;
exports.scss = scss;
exports.email = email;
exports.clean = clean;
exports.js = js;
exports.build = build;
exports.serve = serve;
exports.default = build;<|endoftext|>


<commit_before>/*globals self */
window.addEventListener('click', function(e) {'use strict';

    if (e.button === 2 || (e.button === 0 && e.shiftKey === true)) {
        self.port.emit('copyDirectoryPath');
        e.preventDefault();
    }

}, true);<commit_msg>newline<commit_after>/*globals self */
window.addEventListener('click', function(e) {'use strict';

    if (e.button === 2 || (e.button === 0 && e.shiftKey === true)) {
        self.port.emit('copyDirectoryPath');
        e.preventDefault();
    }

}, true);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var stylish = require('gulp-jscs-stylish');
var concat = require('gulp-concat');
var nodemon = require('gulp-nodemon');
var ngAnnotate = require('gulp-ng-annotate');
var protractor = require('gulp-protractor').protractor;
var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

gulp.task('build-js', ['codestyle'], function () {
  return gulp.src('client/**/!(*.spec).js')
    .pipe(ngAnnotate())
    .pipe(concat('app.js'))
    .pipe(gulp.dest('dist/'))
  ;
});

gulp.task('build-lib', ['build-bootstrap'], function () {
  return gulp.src([
      'node_modules/angular/angular.js',
      'node_modules/angular-ui-router/release/angular-ui-router.js'
    ])
    .pipe(gulp.dest('dist/lib/'))
  ;
});

gulp.task('build-bootstrap', function () {
  return gulp.src('node_modules/bootstrap/dist/**/*')
    .pipe(gulp.dest('dist/lib/bootstrap/'))
  ;
});

gulp.task('build-static', function () {
  return gulp.src('client/**/!(*.js)')
    .pipe(gulp.dest('dist/'))
  ;
});

gulp.task('build-app', ['build-js', 'build-static']);
gulp.task('build', ['build-lib', 'build-app']);
gulp.task('default', ['codestyle', 'build', 'start']);

gulp.task('start', ['build'], function() {
  gulp.watch('client/**/*', ['codestyle', 'build-app']);
  return nodemon({
    script: 'index.js',
    ext: 'js',
  });
});

gulp.task('test', function() {
  return gulp.src(['client/**/*.spec.js', 'tests/**/*.js'], { read: false })
    .pipe(protractor({
      configFile: 'tests/protractor.config.js',
      args: ['--baseUrl', 'http://localhost:9000'],
    }))
  ;
});

gulp.task('webdriverUpdate', webdriverUpdate);
gulp.task('webdriverStandalone', webdriverStandalone);

gulp.task('codestyle', function() {
  return gulp.src(['client/**/*.js'])
    .pipe(jshint())
    .pipe(jscs())
    .pipe(stylish.combineWithHintResults())
    .pipe(jshint.reporter('jshint-stylish'));
});
<commit_msg>fix CS on gulp and remove .spec in e2e tests<commit_after>'use strict';

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var stylish = require('gulp-jscs-stylish');
var concat = require('gulp-concat');
var nodemon = require('gulp-nodemon');
var ngAnnotate = require('gulp-ng-annotate');
var protractor = require('gulp-protractor').protractor;
var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

gulp.task('build-js', ['codestyle'], function () {
  return gulp.src('client/**/!(*.spec).js')
    .pipe(ngAnnotate())
    .pipe(concat('app.js'))
    .pipe(gulp.dest('dist/'))
  ;
});

gulp.task('build-lib', ['build-bootstrap'], function () {
  return gulp.src([
      'node_modules/angular/angular.js',
      'node_modules/angular-ui-router/release/angular-ui-router.js'
    ])
    .pipe(gulp.dest('dist/lib/'))
  ;
});

gulp.task('build-bootstrap', function () {
  return gulp.src('node_modules/bootstrap/dist/**/*')
    .pipe(gulp.dest('dist/lib/bootstrap/'))
  ;
});

gulp.task('build-static', function () {
  return gulp.src('client/**/!(*.js)')
    .pipe(gulp.dest('dist/'))
  ;
});

gulp.task('build-app', ['build-js', 'build-static']);
gulp.task('build', ['build-lib', 'build-app']);
gulp.task('default', ['codestyle', 'build', 'start']);

gulp.task('start', ['build'], function() {
  gulp.watch('client/**/*', ['codestyle', 'build-app']);
  return nodemon({
    script: 'index.js',
    ext: 'js',
  });
});

gulp.task('test', function() {
  return gulp.src(['tests/**/*.js'], { read: false })
    .pipe(protractor({
      configFile: 'tests/protractor.config.js',
      args: ['--baseUrl', 'http://localhost:9000'],
    }))
  ;
});

gulp.task('webdriverUpdate', webdriverUpdate);
gulp.task('webdriverStandalone', webdriverStandalone);

gulp.task('codestyle', function() {
  return gulp.src(['client/**/*.js'])
    .pipe(jshint())
    .pipe(jscs())
    .pipe(stylish.combineWithHintResults())
    .pipe(jshint.reporter('jshint-stylish'))
  ;
});
<|endoftext|>


<commit_before>function checkArgs(args, expArgLength) {

	// number of arguments passed to the given function.
	var arglength = args.length;

	//last argument must always be a callback.
	//error if it is not callback type.
	if (typeof args[arglength - 1] != "function") {
        throw new Error("Callback function must be passed for this async API");
	}

	//for functions requiring fixed number of arguments
	//this check is performed.
	//If function does not have fixed number of arguments
	//this check is skipped.
	if (typeof expArgLength != "undefined") {
		if (arglength != expArgLength) {
			var err = (new Error()).stack.split("\n")[3];
			var error = {};
			error.func = err.split(".")[2].split("(")[0];
			error.file = err.split("(")[1].split(":")[0];
			error.line = err.split(":")[1];
			error.code = 2;
			error.message = "Number of arguments passed - Invalid";
			var callback = args[arglength - 1];
			callback(error, undefined);
			return -1;
		}
	}

	return 0;
}

// Generic function to execute any LDT function.
// Invokes udf execute with the corresponding LDT
// function name, file name as llist - file in which
// all the LDT functions are implemented.
// some function applies an UDF/Filter on values returned by LDT.
// Those values are passed as {module:" ", funcname:" ", args: " "}  object.
// Parse the above object format and populate UDFArgs accordingly.
// Position of the UDF arguments is passed to parse effectively.
var executeLDTFunction = function(ldtFunc, ldtargs, arglength, udfPosition) {
	if (typeof udfPosition == 'undefined') {
		udfPosition = -1;
	}

	if (checkArgs(ldtargs, arglength) !== 0) {
		return -1;
	}
	var udfargs = [this.binName];
	for (var i = 0; i < arglength - 1; i++) {
		if (udfPosition == i) {
			udfargs.push(ldtargs[i].module);
			udfargs.push(ldtargs[i].funcname);
			udfargs.push(ldtargs[i].args);
		} else {
			udfargs.push(ldtargs[i]);
		}
	}
	udfargs.push(this.createModule);
	var udf = {
		module: this.module,
		funcname: ldtFunc,
		args: udfargs
	};
	this.client.execute(this.key, udf, this.writePolicy, ldtargs[arglength - 1]);
};

var LargeList = function(key, binName, writePolicy, createModule) {

	LargeList.client = this;
	LargeList.key = key;
	LargeList.writePolicy = writePolicy;
	LargeList.binName = binName;
	LargeList.module = "llist";
	LargeList.createModule = createModule;
	LargeList.executeLDTFunction = executeLDTFunction;

	// Handle all the variations of add function.
	// 1. val can be a single value
	// 2. val can be an array of values
	LargeList.add = function(val, callback) {
		if (Array.isArray(arguments[0])) {
			this.executeLDTFunction("add_all", arguments, 2);
		} else {
			this.executeLDTFunction("add", arguments, 2);
		}

	};

	// Handle all the variations of update.
	// same as add variations
	LargeList.update = function(val, callback) {
		if (Array.isArray(arguments[0])) {
			this.executeLDTFunction("update_all", arguments, 2);
		} else {
			this.executeLDTFunction("update", arguments, 2);
		}
	};

	// Handle all the variations of remove.
	// Same as add variations and the following
	LargeList.remove = function(val, callback) {

		if (Array.isArray(val)) {
			this.executeLDTFunction("remove_all", arguments, 2);
		} else {
			this.executeLDTFunction("remove", arguments, 2);
		}
	};

	// Can pass a range to remove the values within the range (inclusive).
	LargeList.removeRange = function(valBegin, valEnd, callback) {

		this.executeLDTFunction("remove_range", arguments, 3);
	};

	LargeList.find = function(val, filterArgs, callback) {
		var arglength = arguments.length;

		if (arglength == 2) {
			this.executeLDTFunction("find", arguments, 2);
		} else if (arglength == 3) {
			this.executeLDTFunction("find", arguments, 3, 1);
		} else {
			return;
		}

	};

	// apply filter - pass all elements through a filter and return all that qualify.
	LargeList.filter = function(filterArgs, callback) {
		this.executeLDTFunction("filter", arguments, 1, 0);
	};

	LargeList.findRange = function(valBegin, valEnd, filterArgs, callback) {
		var arglength = arguments.length;

		if (arglength == 3) {
			this.executeLDTFunction("range", arguments, 3);
		} else if (arglength == 4) {
			this.executeLDTFunction("range", arguments, 4, 2);
		} else {
			return;
		}
	};

	LargeList.scan = function(callback) {
		this.executeLDTFunction("scan", arguments, 1);
	};

	LargeList.destroy = function(callback) {
		this.executeLDTFunction("destroy", arguments, 1);
	};

	LargeList.size = function(callback) {
		this.executeLDTFunction("size", arguments, 1);
	};

	LargeList.getConfig = function(callback) {
		this.executeLDTFunction("config", arguments, 1);
	};
	return LargeList;
};

module.exports = LargeList;
<commit_msg>changed LargeList function to return instance<commit_after>function checkArgs(args, expArgLength) {

	// number of arguments passed to the given function.
	var arglength = args.length;

	//last argument must always be a callback.
	//error if it is not callback type.
	if (typeof args[arglength - 1] != "function") {
        throw new Error("Callback function must be passed for this async API");
	}

	//for functions requiring fixed number of arguments
	//this check is performed.
	//If function does not have fixed number of arguments
	//this check is skipped.
	if (typeof expArgLength != "undefined") {
		if (arglength != expArgLength) {
			var err = (new Error()).stack.split("\n")[3];
			var error = {};
			error.func = err.split(".")[2].split("(")[0];
			error.file = err.split("(")[1].split(":")[0];
			error.line = err.split(":")[1];
			error.code = 2;
			error.message = "Number of arguments passed - Invalid";
			var callback = args[arglength - 1];
			callback(error, undefined);
			return -1;
		}
	}

	return 0;
}

// Generic function to execute any LDT function.
// Invokes udf execute with the corresponding LDT
// function name, file name as llist - file in which
// all the LDT functions are implemented.
// some function applies an UDF/Filter on values returned by LDT.
// Those values are passed as {module:" ", funcname:" ", args: " "}  object.
// Parse the above object format and populate UDFArgs accordingly.
// Position of the UDF arguments is passed to parse effectively.
var executeLDTFunction = function(ldtFunc, ldtargs, arglength, udfPosition) {
	if (typeof udfPosition == 'undefined') {
		udfPosition = -1;
	}

	if (checkArgs(ldtargs, arglength) !== 0) {
		return -1;
	}
	var udfargs = [this.binName];
	for (var i = 0; i < arglength - 1; i++) {
		if (udfPosition == i) {
			udfargs.push(ldtargs[i].module);
			udfargs.push(ldtargs[i].funcname);
			udfargs.push(ldtargs[i].args);
		} else {
			udfargs.push(ldtargs[i]);
		}
	}
	udfargs.push(this.createModule);
	var udf = {
		module: this.module,
		funcname: ldtFunc,
		args: udfargs
	};
	this.client.execute(this.key, udf, this.writePolicy, ldtargs[arglength - 1]);
};

var LargeList = function (key, binName, writePolicy, createModule) {
	var instance = {};
	instance.client = this;
	instance.key = key;
	instance.writePolicy = writePolicy;
	instance.binName = binName;
	instance.module = "llist";
	instance.createModule = createModule;
	instance.executeLDTFunction = executeLDTFunction;

	// Handle all the variations of add function.
	// 1. val can be a single value
	// 2. val can be an array of values
	instance.add = function(val, callback) {
		if (Array.isArray(arguments[0])) {
			this.executeLDTFunction("add_all", arguments, 2);
		} else {
			this.executeLDTFunction("add", arguments, 2);
		}

	};

	// Handle all the variations of update.
	// same as add variations
	instance.update = function(val, callback) {
		if (Array.isArray(arguments[0])) {
			this.executeLDTFunction("update_all", arguments, 2);
		} else {
			this.executeLDTFunction("update", arguments, 2);
		}
	};

	// Handle all the variations of remove.
	// Same as add variations and the following
	instance.remove = function(val, callback) {

		if (Array.isArray(val)) {
			this.executeLDTFunction("remove_all", arguments, 2);
		} else {
			this.executeLDTFunction("remove", arguments, 2);
		}
	};

	// Can pass a range to remove the values within the range (inclusive).
	instance.removeRange = function(valBegin, valEnd, callback) {

		this.executeLDTFunction("remove_range", arguments, 3);
	};

	instance.find = function(val, filterArgs, callback) {
		var arglength = arguments.length;

		if (arglength == 2) {
			this.executeLDTFunction("find", arguments, 2);
		} else if (arglength == 3) {
			this.executeLDTFunction("find", arguments, 3, 1);
		} else {
			return;
		}

	};

	// apply filter - pass all elements through a filter and return all that qualify.
	instance.filter = function(filterArgs, callback) {
		this.executeLDTFunction("filter", arguments, 1, 0);
	};

	instance.findRange = function(valBegin, valEnd, filterArgs, callback) {
		var arglength = arguments.length;

		if (arglength == 3) {
			this.executeLDTFunction("range", arguments, 3);
		} else if (arglength == 4) {
			this.executeLDTFunction("range", arguments, 4, 2);
		} else {
			return;
		}
	};

	instance.scan = function(callback) {
		this.executeLDTFunction("scan", arguments, 1);
	};

	instance.destroy = function(callback) {
		this.executeLDTFunction("destroy", arguments, 1);
	};

	instance.size = function(callback) {
		this.executeLDTFunction("size", arguments, 1);
	};

	instance.getConfig = function(callback) {
		this.executeLDTFunction("config", arguments, 1);
	};

	return instance;
};

module.exports = LargeList;
<|endoftext|>


<commit_before>var generateKeyObjects = function (keysFromVim) {
  var keyObjects = [];

  for (var i = 0; i < keysFromVim.length; i++) {

    var keyObject = {};
    keyObject.key = "";
    keyObject.keyCode = [];
    keyObject.isKeyCode = false;
    keyObject.usingObject = {};
    keyObject.usingObject.using = [];

    var splitKeys = keysFromVim[i].split(",");
    if (!isValidKey(splitKeys)) return "";

    if (isKeyCode(splitKeys[0])) {
      keyObject.isKeyCode = true;
      keyObject.keyCode.push(Number(splitKeys[0]));
    } else {
      keyObject.key = splitKeys[0];
    }

    for (var k = 1; k < splitKeys.length; k++) {
      var usingKey = getUsingKey(splitKeys[k]);
      if (usingKey !== "") {
        keyObject.usingObject.using.push(usingKey);
      }
    }

    keyObjects.push(keyObject);
  }

  return keyObjects;
};

var isKeyCode = function (keyCode) {
  var keyCodeRe = /^\d{1,3}$/;
  if (keyCode.match(keyCodeRe)) return true;
  return false;
}

var isValidKey = function (splitKeys) {
  if (splitKeys.length > 5) return false;

  var usingKeyRe = /c|d|a|s/;

  for (var i = 0; i < splitKeys.length; i++) {
    if (i === 0) {
      // とりあえず空以外は許容とする
      if (splitKeys[i] === null || splitKeys[i] === "") {
        console.log("invalid key:" + splitKeys[i]);
        return false;
      }
    } else {
      if (!splitKeys[i].match(usingKeyRe)) {
        console.log("invalid key:" + splitKeys[i]);
        return false;
      }
    }
  }

  return true;
};

var getUsingKey = function (usingKey) {
  if (usingKey === "c") {
    return "control down";
  } else if (usingKey === "s") {
    return "shift down";
  } else if (usingKey === "a") {
    return "option down";
  } else if (usingKey === "d") {
    return "command down";
  }
  return "";
};

var sendKey = function (keyObjects, targetAppName, vimAppName) {
  var targetApp = null;
  var vimApp = null;
  try {
    targetApp = Application(targetAppName);
    vimApp = Application(vimAppName);
  } catch(e) {
    console.log(e);
    return;
  }

  var systemEvent = Application("System Events");
  targetApp.activate();

  var delayTime = 0.3;
//  var keyCount = getKeyCount(keyObjects);
//  if (keyCount > 5) {
//    delayTime = 0.1 * keyCount;
//  }
  delay(delayTime);

  keyObjects.forEach(function(keyObject) {
    if (keyObject.isKeyCode) {
      doKeyCode(systemEvent, keyObject);
    } else {
      doKeystroke(systemEvent, keyObject);
    }
  });

  vimApp.activate();
};

var getKeyCount = function (keyObjects) {
  var count = 0;

  keyObjects.forEach(function (keyObject) {
    if (!keyObject.isKeyCode) {
      count += keyObject.key.length;
    } else {
      count += 1;
    }
  });

  return count;
}

var doKeystroke = function (systemEvent, keyObject) {
  systemEvent.keystroke(keyObject.key, keyObject.usingObject);
};

var doKeyCode = function (systemEvent, keyObject) {
  systemEvent.keyCode(keyObject.keyCode, keyObject.usingObject);
};

// argv[0]はtargetAppName
// argv[1]はvimAppName
// それ移行はkey
function run(argv){
  if (argv.length < 3) {
    console.log("Arguments are necessary more than 3.");
    return;
  }

  var targetAppName = null;
  var vimAppName = null;
  var keysFromVim = [];

  for (var i = 0; i < argv.length; i++) {
    if (i === 0) {
      targetAppName = argv[i];
    } else if (i === 1) {
      vimAppName = argv[i];
    } else {
      keysFromVim.push(argv[i]);
    }
  }

  var keys = generateKeyObjects(keysFromVim);
  if (keys === "") return;

  sendKey(keys, targetAppName, vimAppName);
}

<commit_msg>change function name<commit_after>var generateKeyObjects = function (keysFromVim) {
  var keyObjects = [];

  for (var i = 0; i < keysFromVim.length; i++) {

    var keyObject = {};
    keyObject.key = "";
    keyObject.keyCode = [];
    keyObject.isKeyCode = false;
    keyObject.usingObject = {};
    keyObject.usingObject.using = [];

    var splitKeys = keysFromVim[i].split(",");
    if (!isValidKey(splitKeys)) return "";

    if (isKeyCode(splitKeys[0])) {
      keyObject.isKeyCode = true;
      keyObject.keyCode.push(Number(splitKeys[0]));
    } else {
      keyObject.key = splitKeys[0];
    }

    for (var k = 1; k < splitKeys.length; k++) {
      var usingKey = getUsingKey(splitKeys[k]);
      if (usingKey !== "") {
        keyObject.usingObject.using.push(usingKey);
      }
    }

    keyObjects.push(keyObject);
  }

  return keyObjects;
};

var isKeyCode = function (keyCode) {
  var keyCodeRe = /^\d{1,3}$/;
  if (keyCode.match(keyCodeRe)) return true;
  return false;
}

var isValidKey = function (splitKeys) {
  if (splitKeys.length > 5) return false;

  var usingKeyRe = /c|d|a|s/;

  for (var i = 0; i < splitKeys.length; i++) {
    if (i === 0) {
      // とりあえず空以外は許容とする
      if (splitKeys[i] === null || splitKeys[i] === "") {
        console.log("invalid key:" + splitKeys[i]);
        return false;
      }
    } else {
      if (!splitKeys[i].match(usingKeyRe)) {
        console.log("invalid key:" + splitKeys[i]);
        return false;
      }
    }
  }

  return true;
};

var getUsingKey = function (usingKey) {
  if (usingKey === "c") {
    return "control down";
  } else if (usingKey === "s") {
    return "shift down";
  } else if (usingKey === "a") {
    return "option down";
  } else if (usingKey === "d") {
    return "command down";
  }
  return "";
};

var sendKey2App = function (keyObjects, targetAppName, vimAppName) {
  var targetApp = null;
  var vimApp = null;
  try {
    targetApp = Application(targetAppName);
    vimApp = Application(vimAppName);
  } catch(e) {
    console.log(e);
    return;
  }

  var systemEvent = Application("System Events");
  targetApp.activate();

  var delayTime = 0.3;
//  var keyCount = getKeyCount(keyObjects);
//  if (keyCount > 5) {
//    delayTime = 0.1 * keyCount;
//  }
  delay(delayTime);

  keyObjects.forEach(function(keyObject) {
    if (keyObject.isKeyCode) {
      doKeyCode(systemEvent, keyObject);
    } else {
      doKeystroke(systemEvent, keyObject);
    }
  });

  vimApp.activate();
};

var getKeyCount = function (keyObjects) {
  var count = 0;

  keyObjects.forEach(function (keyObject) {
    if (!keyObject.isKeyCode) {
      count += keyObject.key.length;
    } else {
      count += 1;
    }
  });

  return count;
}

var doKeystroke = function (systemEvent, keyObject) {
  systemEvent.keystroke(keyObject.key, keyObject.usingObject);
};

var doKeyCode = function (systemEvent, keyObject) {
  systemEvent.keyCode(keyObject.keyCode, keyObject.usingObject);
};

// argv[0]はtargetAppName
// argv[1]はvimAppName
// それ移行はkey
function run(argv){
  if (argv.length < 3) {
    console.log("Arguments are necessary more than 3.");
    return;
  }

  var targetAppName = null;
  var vimAppName = null;
  var keysFromVim = [];

  for (var i = 0; i < argv.length; i++) {
    if (i === 0) {
      targetAppName = argv[i];
    } else if (i === 1) {
      vimAppName = argv[i];
    } else {
      keysFromVim.push(argv[i]);
    }
  }

  var keys = generateKeyObjects(keysFromVim);
  if (keys === "") return;

  sendKey2App(keys, targetAppName, vimAppName);
}

<|endoftext|>