<commit_before>var Discord = require("discord.js");
var mysql = require("mysql");
var log = require(__dirname + "/logger.js");
var config =  require("./config");
var appConfig = config.appConfig;

var connection;
config.connection = connection;
var serverConfig = config.serverConfig;
var getServerConfig = config.getServerConfig;

var commands = {};

commands.help = {
	alias: "help",
	description: "This help message!",
	hidden: false,
	action: (client, message) => {
		var helpStr = "```";
		for(var cmd in commands) {
			if(!commands[cmd].hidden) {
				helpStr = helpStr.concat(getServerConfig(message.server, "cmdprefix"), commands[cmd].alias, ": ", commands[cmd].description, "\n");
			}
		}
		helpStr = helpStr.concat("```");
		client.sendMessage(message.channel, helpStr);
	}
};

commands.load = {
	alias: "load",
	description: "Load a command",
	hidden: true,
	action: (client, message, params) => {
		if(message.author.id == appConfig.ownerid) {
			try {
				commands[params[0]] = require("./commands/" + params[0] + ".js");
				client.sendMessage(message.channel, "Successfully loaded " + params[0]);
				log.info("Loaded " + params[0]);
			}
			catch(err) {
				client.sendMessage(message.channel, "Failed to load " + params[0]);
				log.error(err);
			}
		}
		else {
			client.sendMessage(message.channel, ":no_entry: **Permission Denied** :no_entry:");
		}
	}
};

commands.unload = {
	alias: "unload",
	description: "Unload a command",
	hidden: true,
	action:  (client, message, params) => {
		if(message.author.id == appConfig.ownerid) {
			try {
				delete commands[params[0]];
				delete require.cache[require.resolve("./commands/" + params[0] + ".js")];
				client.sendMessage(message.channel, "Successfully unloaded " + params[0]);
				log.info("Unloaded " + params[0]);
			}
			catch(err) {
				client.sendMessage(message.channel, "Failed to unload " + params[0]);
				log.error(err);
			}
		}
		else {
			client.sendMessage(message.channel, ":no_entry: **Permission Denied** :no_entry:");
		}
	}
};

commands.reload = {
	alias: "reload",
	description: "Reload a command",
	hidden: true,
	action: (client, message, params) => {
		if(message.author.id == appConfig.ownerid) {
			// commands.unload.action(client, message, params);
			// commands.load.action(client, message, params);
			try {
				delete commands[params[0]];
				delete require.cache[require.resolve("./commands/" + params[0] + ".js")];
				commands[params[0]] = require("./commands/" + params[0] + ".js");
				client.sendMessage(message.channel, "Successfully reloaded " + params[0]);
				log.info("Reloaded " + params[0]);
			}
			catch(err) {
				client.sendMessage(message.channel, "Failed to reload " + params[0]);
				log.error(err);
			}

		}
	}
};

function loadCommands() {
	var fs = require("fs");
	var files = fs.readdirSync("./commands");
	var loaded = 0;
	for(let file of files) {
		if(file.endsWith(".js")) {
			commands[file.slice(0, -3)] = require("./commands/" + file);
			loaded++;
		}
	}
	log.info("Loaded  " + loaded + " commands!");
}

function db_connect() {
	connection = mysql.createConnection(appConfig.mysql);
	connection.connect(function(err) {
		if(err) {
			log.error(err);
			setTimeout(db_connect, 2000);
		}
	});
	connection.on("error", function(err) {
		if(err.code === "PROTOCOL_CONNECTION_LOST") {
			db_connect();
		}
		else {
			return log.error(err);
		}
	});
}

function getParams(content) {
	var params = content.split(" ");
	if(content.indexOf(client.user.mention()) > -1) {
		params.shift();
	}
	params.shift();
	return params;
}

var client = new Discord.Client({autoReconnect: true});

client.on("message", function(message) {
	if(message.content.toLowerCase().indexOf("hello") > -1 && message.isMentioned(client.user)) {
		return client.sendMessage(message.channel, "Hello " + message.author);
	}
	else if(message.content.toLowerCase().indexOf("who gta") > -1) {
		return message.reply("oooh oooh me! I'll play!");
	}
	else if(message.content.startsWith(getServerConfig(message.server, "cmdprefix"))) {

		var cmdArray = message.content.substring(getServerConfig(message.server, "cmdprefix").length).split(" ");
		var cmd = commands[cmdArray[0]];

		if(cmd != null) {
			cmd.action(client, message, getParams(message.content), config);
		}
	}
	else if(subreddit = message.content.matches(/\/r\/\w+/)) { //eslint-disable-line
		client.sendMessage(message.channel, "http://www.reddit.com/" + subreddit[0]); //eslint-disable-line no-undef

	}
	else if(message.isMentioned(client.user)) {
		cmdArray = message.content.split(" ");
		cmd = commands[cmdArray[1]];

		if(cmd != null) {
			cmd.action(client, message, getParams(message.content), config);
		}
	}
});

//Called once the bot is logged in and ready to use.
client.on("ready", function() {
	db_connect();
	log.info("Established connection to database.");
	updatePlaying();
	setInterval(updatePlaying, 600000);

	connection.query("SELECT configName, configValue FROM configs ORDER BY configID ASC", function(err, rows) {
		if(err) {
			return log.error(err);
		}
		serverConfig["default"] = {};
		for(var i = 0;i < rows.length; i++) {
			serverConfig["default"][rows[i].configName] = rows[i].configValue;
			log.info("Set default '"+ rows[i].configName + "' to '" + rows[i].configValue + "'.");
		}
	});

	connection.query("SELECT serverConfig.serverId, serverConfig.value, configs.configName FROM serverConfig INNER JOIN configs on serverConfig.configId= configs.configId", function(err, rows) {
		if(err) {
			return log.error(err);
		}
		for(var server of client.servers) {
			serverConfig[server.id] = {};
		}
		for(var i = 0; i < rows.length; i++) {
			serverConfig[rows[i].serverId][rows[i].configName] = rows[i].value;
		}
	});
	loadCommands();
});

function updatePlaying() {
	connection.query("SELECT playingString FROM playing ORDER BY RAND() LIMIT 1", function(err, rows) {
		if(err) {
			return log.error(err);
		}
		client.setPlayingGame(rows[0].playingString);
	});
}

//Handle a CTRL+C to actually shutdown somewhat cleanly
process.on("SIGINT", function() {
	client.logout(function(error) {
		if(error) {
			return log.error(error);
		}
		process.exit(0);
	});
});

client.loginWithToken(appConfig.apikey, function(err){
	if(err) {
		return log.error(err);
	}
});
<commit_msg>Fixed database connection<commit_after>var Discord = require("discord.js");
var mysql = require("mysql");
var log = require(__dirname + "/logger.js");
var config =  require("./config");
var appConfig = config.appConfig;

var connection;
var serverConfig = config.serverConfig;
var getServerConfig = config.getServerConfig;

var commands = {};

commands.help = {
	alias: "help",
	description: "This help message!",
	hidden: false,
	action: (client, message) => {
		var helpStr = "```";
		for(var cmd in commands) {
			if(!commands[cmd].hidden) {
				helpStr = helpStr.concat(getServerConfig(message.server, "cmdprefix"), commands[cmd].alias, ": ", commands[cmd].description, "\n");
			}
		}
		helpStr = helpStr.concat("```");
		client.sendMessage(message.channel, helpStr);
	}
};

commands.load = {
	alias: "load",
	description: "Load a command",
	hidden: true,
	action: (client, message, params) => {
		if(message.author.id == appConfig.ownerid) {
			try {
				commands[params[0]] = require("./commands/" + params[0] + ".js");
				client.sendMessage(message.channel, "Successfully loaded " + params[0]);
				log.info("Loaded " + params[0]);
			}
			catch(err) {
				client.sendMessage(message.channel, "Failed to load " + params[0]);
				log.error(err);
			}
		}
		else {
			client.sendMessage(message.channel, ":no_entry: **Permission Denied** :no_entry:");
		}
	}
};

commands.unload = {
	alias: "unload",
	description: "Unload a command",
	hidden: true,
	action:  (client, message, params) => {
		if(message.author.id == appConfig.ownerid) {
			try {
				delete commands[params[0]];
				delete require.cache[require.resolve("./commands/" + params[0] + ".js")];
				client.sendMessage(message.channel, "Successfully unloaded " + params[0]);
				log.info("Unloaded " + params[0]);
			}
			catch(err) {
				client.sendMessage(message.channel, "Failed to unload " + params[0]);
				log.error(err);
			}
		}
		else {
			client.sendMessage(message.channel, ":no_entry: **Permission Denied** :no_entry:");
		}
	}
};

commands.reload = {
	alias: "reload",
	description: "Reload a command",
	hidden: true,
	action: (client, message, params) => {
		if(message.author.id == appConfig.ownerid) {
			// commands.unload.action(client, message, params);
			// commands.load.action(client, message, params);
			try {
				delete commands[params[0]];
				delete require.cache[require.resolve("./commands/" + params[0] + ".js")];
				commands[params[0]] = require("./commands/" + params[0] + ".js");
				client.sendMessage(message.channel, "Successfully reloaded " + params[0]);
				log.info("Reloaded " + params[0]);
			}
			catch(err) {
				client.sendMessage(message.channel, "Failed to reload " + params[0]);
				log.error(err);
			}

		}
	}
};

function loadCommands() {
	var fs = require("fs");
	var files = fs.readdirSync("./commands");
	var loaded = 0;
	for(let file of files) {
		if(file.endsWith(".js")) {
			commands[file.slice(0, -3)] = require("./commands/" + file);
			loaded++;
		}
	}
	log.info("Loaded  " + loaded + " commands!");
}

function db_connect() {
	connection = mysql.createConnection(appConfig.mysql);
	config.connection = connection;
	connection.connect(function(err) {
		if(err) {
			log.error(err);
			setTimeout(db_connect, 2000);
		}
	});
	connection.on("error", function(err) {
		if(err.code === "PROTOCOL_CONNECTION_LOST") {
			db_connect();
		}
		else {
			return log.error(err);
		}
	});
}

function getParams(content) {
	var params = content.split(" ");
	if(content.indexOf(client.user.mention()) > -1) {
		params.shift();
	}
	params.shift();
	return params;
}

var client = new Discord.Client({autoReconnect: true});

client.on("message", function(message) {
	if(message.content.toLowerCase().indexOf("hello") > -1 && message.isMentioned(client.user)) {
		return client.sendMessage(message.channel, "Hello " + message.author);
	}
	else if(message.content.toLowerCase().indexOf("who gta") > -1) {
		return message.reply("oooh oooh me! I'll play!");
	}
	else if(message.content.startsWith(getServerConfig(message.server, "cmdprefix"))) {

		var cmdArray = message.content.substring(getServerConfig(message.server, "cmdprefix").length).split(" ");
		var cmd = commands[cmdArray[0]];

		if(cmd != null) {
			cmd.action(client, message, getParams(message.content), config);
		}
	}
	else if(subreddit = message.content.matches(/\/r\/\w+/)) { //eslint-disable-line
		client.sendMessage(message.channel, "http://www.reddit.com/" + subreddit[0]); //eslint-disable-line no-undef

	}
	else if(message.isMentioned(client.user)) {
		cmdArray = message.content.split(" ");
		cmd = commands[cmdArray[1]];

		if(cmd != null) {
			cmd.action(client, message, getParams(message.content), config);
		}
	}
});

//Called once the bot is logged in and ready to use.
client.on("ready", function() {
	db_connect();
	log.info("Established connection to database.");
	updatePlaying();
	setInterval(updatePlaying, 600000);

	connection.query("SELECT configName, configValue FROM configs ORDER BY configID ASC", function(err, rows) {
		if(err) {
			return log.error(err);
		}
		serverConfig["default"] = {};
		for(var i = 0;i < rows.length; i++) {
			serverConfig["default"][rows[i].configName] = rows[i].configValue;
			log.info("Set default '"+ rows[i].configName + "' to '" + rows[i].configValue + "'.");
		}
	});

	connection.query("SELECT serverConfig.serverId, serverConfig.value, configs.configName FROM serverConfig INNER JOIN configs on serverConfig.configId= configs.configId", function(err, rows) {
		if(err) {
			return log.error(err);
		}
		for(var server of client.servers) {
			serverConfig[server.id] = {};
		}
		for(var i = 0; i < rows.length; i++) {
			serverConfig[rows[i].serverId][rows[i].configName] = rows[i].value;
		}
	});
	loadCommands();
});

function updatePlaying() {
	connection.query("SELECT playingString FROM playing ORDER BY RAND() LIMIT 1", function(err, rows) {
		if(err) {
			return log.error(err);
		}
		client.setPlayingGame(rows[0].playingString);
	});
}

//Handle a CTRL+C to actually shutdown somewhat cleanly
process.on("SIGINT", function() {
	client.logout(function(error) {
		if(error) {
			return log.error(error);
		}
		process.exit(0);
	});
});

client.loginWithToken(appConfig.apikey, function(err){
	if(err) {
		return log.error(err);
	}
});
<|endoftext|>


<commit_before>var jaguarDb = require('./jaguarDb').jaguarDb;
var db = new jaguarDb();

db.connect('./data3', function(err) {

	if(err) {
		console.log('Could not connect: ' + err);
		return;
	}
	else {
		console.log('Connected!');
	}

	var data = {title: 'hello', content: 'blah blah blah'};
	db.insert(data, function(err, insertedData) {
		if(err) {
			console.log('ERROR: ' + err);
		}
		else {
			console.log('Inserted: %s', JSON.stringify(insertedData));
			updatedData = insertedData;
			updatedData.title = 'hello world';
			updatedData.content = 'blah-blah-blah-blah';
			updatedData.insertedOn = new Date();
			db.update(updatedData, function(err) {
				if(err) {
					console.log('ERROR: ' + err);
				}
				else {
					console.log('Updated: %s', JSON.stringify(updatedData));
				}
			});
		}
	});

});

<commit_msg>minor tweaks<commit_after>var jaguarDb = require('./jaguarDb').jaguarDb;
var db = new jaguarDb();

db.connect('./data', function(err) {

	if(err) {
		console.log('Could not connect: ' + err);
		return;
	}

	console.log('Connected!');

	var data = {title: 'hello', content: 'blah blah blah'};
	db.insert(data, function(err, insertedData) {

		if(err) {
			console.log('ERROR: ' + err);
			return;
		}

		console.log('Inserted');
		console.dir(insertedData);

		updatedData = insertedData;
		updatedData.title = 'hello world';
		updatedData.content = 'blah-blah-blah-blah';
		updatedData.insertedOn = new Date();
		db.update(updatedData, function(err) {

			if(err) {
				console.log('ERROR: ' + err);
				return;
			}

			console.log('Updated');
			console.dir(updatedData);
		});

	});

});

<|endoftext|>


<commit_before>$NetworkMap.Utils = {};
$NetworkMap.Views = {};
$NetworkMap.Debug = {};
$NetworkMap.Json = {};

$NetworkMap.Json = (function() {

  return {
    setStartPositions: function(json, positions) {
      jQuery.each(positions, function(index, val1) {
        jQuery.each(json, function(index, val2) {
          if (val2.id == val1.id) {
            val2.data.pos = { x: Number(val1.x), y: Number(val1.y) };
          }
        });
      });
    }
  };
})();

$NetworkMap.Debug = (function() {

  return {
    GraphicalOutput: function(viz) {
      var _enabled = false;
      var _redraw = true;
      var _container = jQuery(viz.canvas.getElement());
      var _debugBox = jQuery('

');
      var _c = viz.canvas;
      var _frames = 0.0;
      var _fps = 0;
      var _lastTime = new Date();
      var _log = '';

      // redraw debugging information
      _container.bind('redraw', function() {
        _redraw = true;
        output();
      });

      var output = function() {
        var html = '
** Debugging Information **
';
        var table = jQuery('

');
        var str = '';
        var _preventDefault = function(evt) { evt.preventDefault(); };

        if (!_enabled) return;

        // setup styles
        jQuery("")
          .appendTo('head');

        // disable selection on div
        _debugBox.bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);

        // output performance info
        table.append('
Performance
');
        table.append('
Frame Rate:	' + _fps + '
');

        table.append('

');

        // output viz info
        table.append('
State	');
        table.append('
Busy: 	' + viz.busy + '
');
        table.append('
Div id: 	' + viz.config.injectInto + '
');

        table.append('

');

        // output navigational info
        table.append('
Navigation	');
        table.append('
Scale Offset X:	' + _c.scaleOffsetX + '
');
        table.append('
Scale Offset Y:	' + _c.scaleOffsetY + '
');
        table.append('
Translate Offset X:	' + _c.translateOffsetX + '
');
        table.append('
Translate Offset Y:	' + _c.translateOffsetY + '
');

        table.append('

');

        // output depth info
        table.append('
Groups
');
        table.append('
Current Depth:	' + viz.detailLevel(_c.scaleOffsetX, viz.config.groupLvls) + '
');

        _debugBox.html(html).append('
' + _log + '

');
        _debugBox.append(table);

        // draw things onto the canvas
        if (_redraw) {
          // draw node boxes
          viz.graph.eachNode(function(n) {
            var dim = n.getData('dim');
            var pos = n.getPos();
            var canvas = viz.canvas, ctx = canvas.getCtx();

            ctx.save();
            ctx.strokeStyle = 'rgb(255,0,0)';
            ctx.lineWidth = 1 / canvas.scaleOffsetX;
            ctx.strokeRect(pos.x - dim, pos.y - dim, dim * 2, dim * 2);
            ctx.restore();
          });

          _redraw = false;
        }
      };

      var init = function() {
        var o = _container.offset();
        var ms = 10;

        _debugBox.css({
          position: 'relative',
          top: o.top,
          left: o.left,
          color: 'rgb(255,0,0)'
        });

        _container.append(_debugBox);

        _container.bind('redraw', function() {
          var nowTime = new Date();
          var diffTime = Math.ceil((nowTime.getTime() - _lastTime.getTime()));

          if (diffTime >= 1000) {
            _fps = _frames;
            _frames = 0.0;
            _lastTime = nowTime;
            output();
          }

          _frames++;
        });
      };

      init();

      return {
        enable: function() { _enabled = true; output(); },
        disable: function() { _enabled = false; },
        isEnabled: function() { return _enabled; },
        logWrite: function(text) { _log = 'Log: ' + text; output(); }
      };
    }
  };
})();

$NetworkMap.Views = (function() {

  return {
    Overview: function(viz, mapOpts) {
      var _opts = jQuery.extend(true, {
        injectInto: 'overview',
        Node: {
          overridable: true,
          dim: 20,
          lineWidth: 5
        },
        Edge: {
          overridable: true,
          color: '#23A4FF',
          lineWidth: 3,
          type: 'line'
        },
        Label: {
          type: 'SVG'
        }
      }, mapOpts);

      var _over = new $jit.NetworkMap(_opts);
      var _container = jQuery('#' + _opts.injectInto);
      var _mouse = null;
      var _svg;

      // translate a main canvas in sync with overview box
      var _moveBox = function(e) {
        var o = _container.offset(),
            x = e.clientX - o.left, y = e.clientY - o.top,
            canvas = viz.canvas,
            size = canvas.getSize(),
            pt1 = _over.c2p({ x: x, y: y }),
            pt2 = viz.c2p({ x: size.width / 2, y: size.height / 2 });

        canvas.translate(pt2.x - pt1.x, pt2.y - pt1.y);
      };

      // setup overview visualisation
      var init = function() {
        var o = _container.offset(),
            vizSize = viz.canvas.getSize(),
            overSize = { width: _over.canvas.getSize().width, height: 150 },
            json = jQuery.extend(true, [], viz.json),
            rect,
            svgcont = jQuery('

')
              .css({ top: o.top, left: o.left, position: 'absolute' })
              .appendTo(document.body);

        _svg = Raphael(svgcont.get(0), overSize.width, overSize.height);
        rect = _svg.rect(0, 0, 0, 0).attr({ stroke: 'rgb(255,255,0)' });

        // remove position data from nodes
        viz.config.layout != 'Static' && jQuery.each(json, function(index, n) {
          delete n.data.pos;
        });

        _over.loadJSON(json);
        _over.canvas.resize(overSize.width, overSize.height);
        _over.canvas.scale(overSize.width / vizSize.width, overSize.width / vizSize.width);

        jQuery(viz.canvas.getElement()).bind('redraw', function() {
          var size = viz.canvas.getSize(),
              p1 = _over.p2c(viz.c2p({ x: 0, y: 0 })),
              p2 = _over.p2c(viz.c2p({ x: size.width, y: size.height }));

          rect.attr({ x: p1.x, y: p1.y, width: Math.abs(p2.x - p1.x), height: Math.abs(p2.y - p1.y) });
          _over.loadPositions(viz.getPositions());
        });

        // setup mouse events
        svgcont.mousedown(function(e) {
          console.log('h');
          _moveBox(e);
          _mouse = e;
        });
        svgcont.mouseup(function() {
          _mouse = null;
        });
        svgcont.mousemove(function(e) {
          if (_mouse != null) _moveBox(e);
        });

        _over.refresh();
      };

      init();

      return {
        viz: _over
      };
    },
  };
})({});

$NetworkMap.Utils.Links = (function() {
  return {
    link: function(nf, nt, id, m) {
      this.nodeFrom = nf;
      this.nodeTo = nt;
      this.id = id;
      this.metrics = m;
    }
  }
})();

$NetworkMap.Utils.Metrics = (function() {
  return {
    data: function(bandwidth, capacity, loss, latency) {
      this.bandwidth = bandwidth;
      this.capacity = capacity;
      this.loss = loss;
      this.latency = latency;
    },

    initJSON: function(json) {
      // create links in both ways
      jQuery.each(json, function(index, n) {
        if (!n.adjacencies) return;
        jQuery.each(n.adjacencies, function(index, adj) {
          if (!adj.data) adj.data = {};
          adj.data.links = [
            new $NetworkMap.Utils.Links.link(n.id, adj.nodeTo, '1'),
            new $NetworkMap.Utils.Links.link(adj.nodeTo, n.id, '1')
          ];
        });
      });
    },

    updateMetrics: function(viz, callback) {
      //TODO: get real data?
      var that = this;

      // update graph metrics
      viz.graph.eachNode(function(n) {
        n.eachAdjacency(function(adj) {

          jQuery.each(adj.data.links, function(index, link) {
            // callback(adj.fromNode, adj.toNode);
            var metrics = new that.data(),
                opts = [ 500, 1000, 2000 ],
                group = Math.random() * 100,
                band;

            if (!adj.data.metrics) metrics.capacity = opts[Math.round(Math.random() * (opts.length - 1))];
            else metrics.capacity = adj.data.metrics.capacity;

            // green
            if (group <= 80) {
              band = 10 + Math.random() * metrics.capacity * 0.20 - 10;

            // yellow
            } else if (group <= 95) {
              band = 10 + Math.random() * metrics.capacity * 0.75 - 10;

            //red
            } else {
              band = 10 + Math.random() * metrics.capacity - 10;
            }

            metrics.bandwidth = band;

            // fill in metrics
            link.data = { metrics: metrics };
          });
        });
      });
    }
  };

})();
<commit_msg>left over console code<commit_after>$NetworkMap.Utils = {};
$NetworkMap.Views = {};
$NetworkMap.Debug = {};
$NetworkMap.Json = {};

$NetworkMap.Json = (function() {

  return {
    setStartPositions: function(json, positions) {
      jQuery.each(positions, function(index, val1) {
        jQuery.each(json, function(index, val2) {
          if (val2.id == val1.id) {
            val2.data.pos = { x: Number(val1.x), y: Number(val1.y) };
          }
        });
      });
    }
  };
})();

$NetworkMap.Debug = (function() {

  return {
    GraphicalOutput: function(viz) {
      var _enabled = false;
      var _redraw = true;
      var _container = jQuery(viz.canvas.getElement());
      var _debugBox = jQuery('

');
      var _c = viz.canvas;
      var _frames = 0.0;
      var _fps = 0;
      var _lastTime = new Date();
      var _log = '';

      // redraw debugging information
      _container.bind('redraw', function() {
        _redraw = true;
        output();
      });

      var output = function() {
        var html = '
** Debugging Information **
';
        var table = jQuery('

');
        var str = '';
        var _preventDefault = function(evt) { evt.preventDefault(); };

        if (!_enabled) return;

        // setup styles
        jQuery("")
          .appendTo('head');

        // disable selection on div
        _debugBox.bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);

        // output performance info
        table.append('
Performance
');
        table.append('
Frame Rate:	' + _fps + '
');

        table.append('

');

        // output viz info
        table.append('
State	');
        table.append('
Busy: 	' + viz.busy + '
');
        table.append('
Div id: 	' + viz.config.injectInto + '
');

        table.append('

');

        // output navigational info
        table.append('
Navigation	');
        table.append('
Scale Offset X:	' + _c.scaleOffsetX + '
');
        table.append('
Scale Offset Y:	' + _c.scaleOffsetY + '
');
        table.append('
Translate Offset X:	' + _c.translateOffsetX + '
');
        table.append('
Translate Offset Y:	' + _c.translateOffsetY + '
');

        table.append('

');

        // output depth info
        table.append('
Groups
');
        table.append('
Current Depth:	' + viz.detailLevel(_c.scaleOffsetX, viz.config.groupLvls) + '
');

        _debugBox.html(html).append('
' + _log + '

');
        _debugBox.append(table);

        // draw things onto the canvas
        if (_redraw) {
          // draw node boxes
          viz.graph.eachNode(function(n) {
            var dim = n.getData('dim');
            var pos = n.getPos();
            var canvas = viz.canvas, ctx = canvas.getCtx();

            ctx.save();
            ctx.strokeStyle = 'rgb(255,0,0)';
            ctx.lineWidth = 1 / canvas.scaleOffsetX;
            ctx.strokeRect(pos.x - dim, pos.y - dim, dim * 2, dim * 2);
            ctx.restore();
          });

          _redraw = false;
        }
      };

      var init = function() {
        var o = _container.offset();
        var ms = 10;

        _debugBox.css({
          position: 'relative',
          top: o.top,
          left: o.left,
          color: 'rgb(255,0,0)'
        });

        _container.append(_debugBox);

        _container.bind('redraw', function() {
          var nowTime = new Date();
          var diffTime = Math.ceil((nowTime.getTime() - _lastTime.getTime()));

          if (diffTime >= 1000) {
            _fps = _frames;
            _frames = 0.0;
            _lastTime = nowTime;
            output();
          }

          _frames++;
        });
      };

      init();

      return {
        enable: function() { _enabled = true; output(); },
        disable: function() { _enabled = false; },
        isEnabled: function() { return _enabled; },
        logWrite: function(text) { _log = 'Log: ' + text; output(); }
      };
    }
  };
})();

$NetworkMap.Views = (function() {

  return {
    Overview: function(viz, mapOpts) {
      var _opts = jQuery.extend(true, {
        injectInto: 'overview',
        Node: {
          overridable: true,
          dim: 20,
          lineWidth: 5
        },
        Edge: {
          overridable: true,
          color: '#23A4FF',
          lineWidth: 3,
          type: 'line'
        },
        Label: {
          type: 'SVG'
        }
      }, mapOpts);

      var _over = new $jit.NetworkMap(_opts);
      var _container = jQuery('#' + _opts.injectInto);
      var _mouse = null;
      var _svg;

      // translate a main canvas in sync with overview box
      var _moveBox = function(e) {
        var o = _container.offset(),
            x = e.clientX - o.left, y = e.clientY - o.top,
            canvas = viz.canvas,
            size = canvas.getSize(),
            pt1 = _over.c2p({ x: x, y: y }),
            pt2 = viz.c2p({ x: size.width / 2, y: size.height / 2 });

        canvas.translate(pt2.x - pt1.x, pt2.y - pt1.y);
      };

      // setup overview visualisation
      var init = function() {
        var o = _container.offset(),
            vizSize = viz.canvas.getSize(),
            overSize = { width: _over.canvas.getSize().width, height: 150 },
            json = jQuery.extend(true, [], viz.json),
            rect,
            svgcont = jQuery('

')
              .css({ top: o.top, left: o.left, position: 'absolute' })
              .appendTo(document.body);

        _svg = Raphael(svgcont.get(0), overSize.width, overSize.height);
        rect = _svg.rect(0, 0, 0, 0).attr({ stroke: 'rgb(255,255,0)' });

        // remove position data from nodes
        viz.config.layout != 'Static' && jQuery.each(json, function(index, n) {
          delete n.data.pos;
        });

        _over.loadJSON(json);
        _over.canvas.resize(overSize.width, overSize.height);
        _over.canvas.scale(overSize.width / vizSize.width, overSize.width / vizSize.width);

        jQuery(viz.canvas.getElement()).bind('redraw', function() {
          var size = viz.canvas.getSize(),
              p1 = _over.p2c(viz.c2p({ x: 0, y: 0 })),
              p2 = _over.p2c(viz.c2p({ x: size.width, y: size.height }));

          rect.attr({ x: p1.x, y: p1.y, width: Math.abs(p2.x - p1.x), height: Math.abs(p2.y - p1.y) });
          _over.loadPositions(viz.getPositions());
        });

        // setup mouse events
        svgcont.mousedown(function(e) {
          _moveBox(e);
          _mouse = e;
        });
        svgcont.mouseup(function() {
          _mouse = null;
        });
        svgcont.mousemove(function(e) {
          if (_mouse != null) _moveBox(e);
        });

        _over.refresh();
      };

      init();

      return {
        viz: _over
      };
    },
  };
})({});

$NetworkMap.Utils.Links = (function() {
  return {
    link: function(nf, nt, id, m) {
      this.nodeFrom = nf;
      this.nodeTo = nt;
      this.id = id;
      this.metrics = m;
    }
  }
})();

$NetworkMap.Utils.Metrics = (function() {
  return {
    data: function(bandwidth, capacity, loss, latency) {
      this.bandwidth = bandwidth;
      this.capacity = capacity;
      this.loss = loss;
      this.latency = latency;
    },

    initJSON: function(json) {
      // create links in both ways
      jQuery.each(json, function(index, n) {
        if (!n.adjacencies) return;
        jQuery.each(n.adjacencies, function(index, adj) {
          if (!adj.data) adj.data = {};
          adj.data.links = [
            new $NetworkMap.Utils.Links.link(n.id, adj.nodeTo, '1'),
            new $NetworkMap.Utils.Links.link(adj.nodeTo, n.id, '1')
          ];
        });
      });
    },

    updateMetrics: function(viz, callback) {
      //TODO: get real data?
      var that = this;

      // update graph metrics
      viz.graph.eachNode(function(n) {
        n.eachAdjacency(function(adj) {

          jQuery.each(adj.data.links, function(index, link) {
            // callback(adj.fromNode, adj.toNode);
            var metrics = new that.data(),
                opts = [ 500, 1000, 2000 ],
                group = Math.random() * 100,
                band;

            if (!adj.data.metrics) metrics.capacity = opts[Math.round(Math.random() * (opts.length - 1))];
            else metrics.capacity = adj.data.metrics.capacity;

            // green
            if (group <= 80) {
              band = 10 + Math.random() * metrics.capacity * 0.20 - 10;

            // yellow
            } else if (group <= 95) {
              band = 10 + Math.random() * metrics.capacity * 0.75 - 10;

            //red
            } else {
              band = 10 + Math.random() * metrics.capacity - 10;
            }

            metrics.bandwidth = band;

            // fill in metrics
            link.data = { metrics: metrics };
          });
        });
      });
    }
  };

})();
<|endoftext|>


<commit_before>const fs = require('fs')
const { spawn } = require('child_process')

// Internal Modules
const debug = require('./debug')

/**
 * Exits the process with a given status,
 * logging a given message before exiting.
 *
 * @param {number} status - exit status
 * @param {string} messages - message to log
 */
function exit (status, ...messages) {
  if (messages) {
    messages.forEach(message => console.log(message))
  }

  process.exit(status)
}

/**
 * Checks for an active Internet connection by doing a DNS lookup of Microsoft.com.
 *
 * @return {Promise.<boolean>} - True if lookup succeeded (or if we skip the test)
 */
function checkInternetConnection () {
  return new Promise((resolve) => {
    require('dns').lookup('microsoft.com', (err) => {
      if (err && err.code === 'ENOTFOUND') {
        resolve(false)
      } else {
        resolve(true)
      }
    })
  })
}

/**
 * Checks the current Windows PS1 execution policy. The upgrader requires an unrestricted policy.
 *
 * @return {Promise.<boolean>} - True if unrestricted, false if it isn't
 */
function checkExecutionPolicy () {
  return new Promise((resolve, reject) => {
    let output = []
    let child

    try {
      debug('Powershell: Attempting to spawn PowerShell child')
      child = spawn('powershell.exe', ['-NoProfile', '-NoLogo', 'Get-ExecutionPolicy'])
    } catch (error) {
      debug('Powershell: Could not spawn PowerShell child')
      reject(error)
    }

    child.stdout.on('data', (data) => {
      debug('PowerShell: Stdout received: ' + data.toString())
      output.push(data.toString())
    })

    child.stderr.on('data', (data) => {
      debug('PowerShell: Stderr received: ' + data.toString())
      output.push(data.toString())
    })

    child.on('exit', () => {
      const linesHit = output.filter((line) => line.includes('Unrestricted') || line.includes('RemoteSigned') || line.includes('Bypass'))
      const unrestricted = (linesHit.length > 0)

      if (!unrestricted) {
        debug('PowerShell: Resolving restricted (false)')
        resolve(false)
      } else {
        debug('PowerShell: Resolving unrestricted (true)')
        resolve(true)
      }
    })

    child.stdin.end()
  })
}

/**
 * Checks if a path exists
 *
 * @param filePath - file path to check
 * @returns {boolean} - does the file path exist?
 */
function isPathExists (filePath) {
  try {
    fs.accessSync(filePath)
    debug(`Utils: isPathExists(): ${filePath} exists`)
    return true
  } catch (err) {
    debug(`Utils: isPathExists(): ${filePath} does not exist`)
    return false
  }
}

module.exports = {
  checkInternetConnection,
  checkExecutionPolicy,
  exit,
  isPathExists
}
<commit_msg>:wrench: Rename isPathExists to isPathAccessible<commit_after>const fs = require('fs')
const { spawn } = require('child_process')

// Internal Modules
const debug = require('./debug')

/**
 * Exits the process with a given status,
 * logging a given message before exiting.
 *
 * @param {number} status - exit status
 * @param {string} messages - message to log
 */
function exit (status, ...messages) {
  if (messages) {
    messages.forEach(message => console.log(message))
  }

  process.exit(status)
}

/**
 * Checks for an active Internet connection by doing a DNS lookup of Microsoft.com.
 *
 * @return {Promise.<boolean>} - True if lookup succeeded (or if we skip the test)
 */
function checkInternetConnection () {
  return new Promise((resolve) => {
    require('dns').lookup('microsoft.com', (err) => {
      if (err && err.code === 'ENOTFOUND') {
        resolve(false)
      } else {
        resolve(true)
      }
    })
  })
}

/**
 * Checks the current Windows PS1 execution policy. The upgrader requires an unrestricted policy.
 *
 * @return {Promise.<boolean>} - True if unrestricted, false if it isn't
 */
function checkExecutionPolicy () {
  return new Promise((resolve, reject) => {
    let output = []
    let child

    try {
      debug('Powershell: Attempting to spawn PowerShell child')
      child = spawn('powershell.exe', ['-NoProfile', '-NoLogo', 'Get-ExecutionPolicy'])
    } catch (error) {
      debug('Powershell: Could not spawn PowerShell child')
      reject(error)
    }

    child.stdout.on('data', (data) => {
      debug('PowerShell: Stdout received: ' + data.toString())
      output.push(data.toString())
    })

    child.stderr.on('data', (data) => {
      debug('PowerShell: Stderr received: ' + data.toString())
      output.push(data.toString())
    })

    child.on('exit', () => {
      const linesHit = output.filter((line) => line.includes('Unrestricted') || line.includes('RemoteSigned') || line.includes('Bypass'))
      const unrestricted = (linesHit.length > 0)

      if (!unrestricted) {
        debug('PowerShell: Resolving restricted (false)')
        resolve(false)
      } else {
        debug('PowerShell: Resolving unrestricted (true)')
        resolve(true)
      }
    })

    child.stdin.end()
  })
}

/**
 * Checks if a path exists
 *
 * @param filePath - file path to check
 * @returns {boolean} - does the file path exist?
 */
function isPathAccessible (filePath) {
  try {
    fs.accessSync(filePath)
    debug(`Utils: isPathAccessible(): ${filePath} exists`)
    return true
  } catch (err) {
    debug(`Utils: isPathAccessible(): ${filePath} does not exist`)
    return false
  }
}

module.exports = {
  checkInternetConnection,
  checkExecutionPolicy,
  exit,
  isPathAccessible
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Determines if at least one element in the object matches a truth test.
 *
 * @param {function(val, key)} pred Predicate function.
 * @param {object|array} obj
 * @return {boolean}
 */
function some(pred, obj) {
  for (var key in obj) {
    if (pred(obj[key], key) === true) {
      return true;
    }
  }
  return false;
}

/**
 * Creates a compare function with a property to sort on.
 *
 * @param {string} prop Property to sort.
 * @return {function(object, object)} Compare function.
 */
var sortByFunc =
    (prop) =>
      (a, b) => {
        if (b[prop] === null && a[prop] === null) { return 0 }
        if (a[prop] === null) { return -1 }
        if (b[prop] === null) { return 1 }
        return a[prop] < b[prop] ? -1 : a[prop] > b[prop] ? 1 : 0;
      }

/**
 * @param {object} sortBy Object containing `prop` and `order`.
 * @param {array} data Array to sort.
 * @return {array} Sorted array.
 */
function sort(sortBy, data) {
  var sortedData = data.sort(sortByFunc(sortBy.prop));
  if (sortBy.order === 'descending') {
    sortedData.reverse();
  }
  return sortedData;
}

/**
 * @param {!object} filters
 * @param {!array} data
 * @return {function(*, string)} Function to be executed for each entry in data.
 */
function filterPass(filters, data) {
  return function(filterValue, key) {
    var filterDef = filters[key];
    var partial = filterDef.filter.bind(null, filterValue);
    if (!filterDef.prop) {
      // Filter is for all properties
      return some(each => partial(each), data);
    } else {
      // Filter is for one property
      return partial(data[filterDef.prop]);
    }
  };
}

/**
 * Example of filter and filterValues.
 * filters = { globalSearch: { filter: containsIgnoreCase } }
 * filterValues = { globalSearch: 'filter value' }
 *
 * @param {object} filters Definition of the filters.
 * @param {object} filterValues Values of the filters.
 * @param {array} data Array to filter.
 * @return {array} Filtered array.
 */
function filter(filters, filterValues, data) {
  var filterFunc = filterPass.bind(null, filters);
  return data.filter(each => some(filterFunc(each), filterValues));
}

module.exports = { filter, filterPass, sort, sortByFunc, some };
<commit_msg>Extend prior sorting fix to handle undefined columns as well.<commit_after>'use strict';

/**
 * Determines if at least one element in the object matches a truth test.
 *
 * @param {function(val, key)} pred Predicate function.
 * @param {object|array} obj
 * @return {boolean}
 */
function some(pred, obj) {
  for (var key in obj) {
    if (pred(obj[key], key) === true) {
      return true;
    }
  }
  return false;
}

/**
 * Creates a compare function with a property to sort on.
 *
 * @param {string} prop Property to sort.
 * @return {function(object, object)} Compare function.
 */
var isEmpty =
    (val) => { return val === null || val === undefined || val === ""; }

var sortByFunc =
    (prop) =>
      (a, b) => {
        if (isEmpty(b[prop]) && isEmpty(a[prop])) { return 0 }
        if (isEmpty(a[prop])) { return -1 }
        if (isEmpty(b[prop])) { return 1 }
        return a[prop] < b[prop] ? -1 : a[prop] > b[prop] ? 1 : 0;
      }

/**
 * @param {object} sortBy Object containing `prop` and `order`.
 * @param {array} data Array to sort.
 * @return {array} Sorted array.
 */
function sort(sortBy, data) {
  var sortedData = data.sort(sortByFunc(sortBy.prop));
  if (sortBy.order === 'descending') {
    sortedData.reverse();
  }
  return sortedData;
}

/**
 * @param {!object} filters
 * @param {!array} data
 * @return {function(*, string)} Function to be executed for each entry in data.
 */
function filterPass(filters, data) {
  return function(filterValue, key) {
    var filterDef = filters[key];
    var partial = filterDef.filter.bind(null, filterValue);
    if (!filterDef.prop) {
      // Filter is for all properties
      return some(each => partial(each), data);
    } else {
      // Filter is for one property
      return partial(data[filterDef.prop]);
    }
  };
}

/**
 * Example of filter and filterValues.
 * filters = { globalSearch: { filter: containsIgnoreCase } }
 * filterValues = { globalSearch: 'filter value' }
 *
 * @param {object} filters Definition of the filters.
 * @param {object} filterValues Values of the filters.
 * @param {array} data Array to filter.
 * @return {array} Filtered array.
 */
function filter(filters, filterValues, data) {
  var filterFunc = filterPass.bind(null, filters);
  return data.filter(each => some(filterFunc(each), filterValues));
}

module.exports = { filter, filterPass, sort, sortByFunc, some };
<|endoftext|>


<commit_before>import _ from 'lodash'
import queries from './queries'

/**
 * Extends lodash's assignWith by allowing array concatenation
 * and deep merging.
 *
 * @private
 *
 * @param {Object} target Target.
 * @returns {Object} Merged object.
 */
export function mergeConcat(target) {
  let args = Array.prototype.slice.call(arguments, 1)

  args.unshift(target)
  args.push(function customizer(a, b) {
    if (_.isPlainObject(a)) {
      return _.assignWith(a, b, customizer)
    } else if (_.isArray(a)) {
      return a.concat(b)
    } else {
      return b
    }
  })
  return _.assignWith.apply(null, args)
}

/**
 * Merge two filters or queries using their Boolean counterparts.
 *
 * @private
 *
 * @param  {Object} newObj      New filter or query to add.
 * @param  {Object} currentObj  Old filter or query to merge into.
 * @param  {String} boolType    Type of boolean ('and', 'or', 'not').
 * @returns {Object} Combined filter or query.
 */
export function boolMerge(newObj, currentObj, boolType = 'and') {
  let boolCurrent
  let boolNew

  // Only one, no need for bool.
  if (_.isEmpty(currentObj)) {
    // Allow starting with 'or' and 'not' queries.
    if (boolType !== 'and') {
      return queries.bool(boolType, newObj)
    }
    return newObj
  }

  // Make bools out of the new and existing filters.
  boolCurrent = currentObj.bool ? currentObj : queries.bool('must', currentObj)
  boolNew = newObj.bool ? newObj : queries.bool(boolType, newObj)

  return mergeConcat({}, boolCurrent, boolNew)
}

/**
 * Compound sort function into the list of sorts
 *
 * @private
 *
 * @param  {Array} current Array of Elasticsearch sorts.
 * @param  {String} field Field to sort.
 * @param  {String|Object} value A valid direction ('asc', 'desc') or object with sort options
 * @returns {Array} Array of Elasticsearch sorts.
 */
export function sortMerge(current, field, value) {
  let payload

  if (_.isPlainObject(value)) {
      payload = { [field]: Object.assign({}, value) }
  } else {
      payload = { [field]: { order: value } }
  }

  const idx = _.findIndex(current, function (o) {
      return o[field] != undefined
  })

  if (idx == -1) {
      current.push(payload)
  } else {
      _.extend(current[idx], payload)
  }

  return current
}<commit_msg>replacing`Object.assign` with `_.assign`<commit_after>import _ from 'lodash'
import queries from './queries'

/**
 * Extends lodash's assignWith by allowing array concatenation
 * and deep merging.
 *
 * @private
 *
 * @param {Object} target Target.
 * @returns {Object} Merged object.
 */
export function mergeConcat(target) {
  let args = Array.prototype.slice.call(arguments, 1)

  args.unshift(target)
  args.push(function customizer(a, b) {
    if (_.isPlainObject(a)) {
      return _.assignWith(a, b, customizer)
    } else if (_.isArray(a)) {
      return a.concat(b)
    } else {
      return b
    }
  })
  return _.assignWith.apply(null, args)
}

/**
 * Merge two filters or queries using their Boolean counterparts.
 *
 * @private
 *
 * @param  {Object} newObj      New filter or query to add.
 * @param  {Object} currentObj  Old filter or query to merge into.
 * @param  {String} boolType    Type of boolean ('and', 'or', 'not').
 * @returns {Object} Combined filter or query.
 */
export function boolMerge(newObj, currentObj, boolType = 'and') {
  let boolCurrent
  let boolNew

  // Only one, no need for bool.
  if (_.isEmpty(currentObj)) {
    // Allow starting with 'or' and 'not' queries.
    if (boolType !== 'and') {
      return queries.bool(boolType, newObj)
    }
    return newObj
  }

  // Make bools out of the new and existing filters.
  boolCurrent = currentObj.bool ? currentObj : queries.bool('must', currentObj)
  boolNew = newObj.bool ? newObj : queries.bool(boolType, newObj)

  return mergeConcat({}, boolCurrent, boolNew)
}

/**
 * Compound sort function into the list of sorts
 *
 * @private
 *
 * @param  {Array} current Array of Elasticsearch sorts.
 * @param  {String} field Field to sort.
 * @param  {String|Object} value A valid direction ('asc', 'desc') or object with sort options
 * @returns {Array} Array of Elasticsearch sorts.
 */
export function sortMerge(current, field, value) {
  let payload

  if (_.isPlainObject(value)) {
      payload = { [field]: _.assign({}, value) }
  } else {
      payload = { [field]: { order: value } }
  }

  const idx = _.findIndex(current, function (o) {
      return o[field] != undefined
  })

  if (idx == -1) {
      current.push(payload)
  } else {
      _.extend(current[idx], payload)
  }

  return current
}<|endoftext|>


<commit_before>

export function ensureLuxProp( context ) {
	const __lux = context.__lux = ( context.__lux || {} );
	/*eslint-disable */
	const cleanup = __lux.cleanup = ( __lux.cleanup || [] );
	const subscriptions = __lux.subscriptions = ( __lux.subscriptions || {} );
	/*eslint-enable */
	return __lux;
}

export function *entries( obj ) {
	if ( [ "object", "function" ].indexOf( typeof obj ) === -1 ) {
		obj = {};
	}
	for ( const k of Object.keys( obj ) ) {
		yield [ k, obj[ k ] ];
	}
}
<commit_msg>Added print utils back to utils namespace.<commit_after>import { printActions, printStoreDepTree } from "./printUtils";

export function ensureLuxProp( context ) {
	const __lux = context.__lux = ( context.__lux || {} );
	/*eslint-disable */
	const cleanup = __lux.cleanup = ( __lux.cleanup || [] );
	const subscriptions = __lux.subscriptions = ( __lux.subscriptions || {} );
	/*eslint-enable */
	return __lux;
}

export function *entries( obj ) {
	if ( [ "object", "function" ].indexOf( typeof obj ) === -1 ) {
		obj = {};
	}
	for ( const k of Object.keys( obj ) ) {
		yield [ k, obj[ k ] ];
	}
}

export default { printActions, printStoreDepTree };
<|endoftext|>


<commit_before>import oboe from "oboe";

const
  getJSON = url => {
    return new Promise((resolve, reject) => {
      oboe(url)
        .done(resolve)
        .fail(reject);
    });
  },

  getJSONProp = (url, prop) => {
    return new Promise((resolve, reject) => {
      let found = false;

      oboe(url)
        .node(prop, value => {
          found = true;
          resolve(value);

          // Found value; hang up
          this.abort();
        })
        .done(() => {
          if (!found)
            reject(new Error(`Property ${ prop } not found`));
        })
        .fail(reject);
    });
  };

export {
  getJSON,
  getJSONProp
};
<commit_msg>Added version matcher<commit_after>import filter from "lodash/collection/filter";
import oboe from "oboe";
import reduce from "lodash/collection/reduce";
import semver from "semver";
import sort from "lodash/collection/sortBy";

const
  getJSON = url => {
    return new Promise((resolve, reject) => {
      oboe(url)
        .done(resolve)
        .fail(reject);
    });
  },

  getJSONProp = (url, prop) => {
    return new Promise((resolve, reject) => {
      let found = false;

      oboe(url)
        .node(prop, value => {
          found = true;
          resolve(value);

          // Found value; hang up
          this.abort();
        })
        .done(() => {
          if (!found)
            reject(new Error(`Property ${ prop } not found`));
        })
        .fail(reject);
    });
  },

  checkVersion = condition =>
    v => semver.satisfies(v, condition),

  getSatisfactoryVersion = (condition, versions=[]) => {
    let
      candidates = filter(versions, checkVersion(condition)),
      sorted = sort(candidates),
      highestVersion = reduce(sorted, (v1, v2) => semver.gt(v1, v2) ? v1 : v2);

    return highestVersion;
  };

export {
  getJSON,
  getJSONProp,
  getSatisfactoryVersion
};
<|endoftext|>


<commit_before>var graphRegex = /^T\.(gt|gte|eq|neq|lte|lt|decr|incr|notin|in)$|^Contains\.(IN|NOT_IN)$|^g\.|^Vertex(?=\.class\b)|^Edge(?=\.class\b)|^String(?=\.class\b)|^Integer(?=\.class\b)|^Geoshape(?=\.class\b)|^Direction\.(OUT|IN|BOTH)$/;
var closureRegex = /^\{.*\}$/;

var toString = Object.prototype.toString;

function isString(o) {
    return toString.call(o) === '[object String]';
}

module.exports = {
    //obj1 over writes obj2
    merge: function (obj1, obj2) {
        for(var p in obj2) {
            try  {
                if(obj1.hasOwnProperty(p)) {
                    obj1[p] = merge(obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch (e) {
                obj1[p] = obj2[p];
            }
        }

        return obj1;
    },

    isRegexId: function (id) {
        return !!this.OPTS.idRegex && isString(id) && this.OPTS.idRegex.test(id);
    },

    isGraphReference: function (val) {
        return isString(val) && graphRegex.test(val);
    },

    isObject: function (o) {
        return toString.call(o) === '[object Object]';
    },

    isClosure: function (val) {
        return isString(val) && closureRegex.test(val);
    },

    isArray: function (o) {
        return toString.call(o) === '[object Array]';
    }
};
<commit_msg>Update Regex for testing graph references (entrendipity/grex#18)<commit_after>var graphRegex = /^T\.(gt|gte|eq|neq|lte|lt|decr|incr|notin|in)$|^Contains\.(IN|NOT_IN)$|^g\.|^Vertex(\.class)$|^Edge(\.class)$|^String(\.class)$|^Integer(\.class)$|^Geoshape(\.class)$|^Direction\.(OUT|IN|BOTH)$/;
var closureRegex = /^\{.*\}$/;

var toString = Object.prototype.toString;

function isString(o) {
    return toString.call(o) === '[object String]';
}

module.exports = {
    //obj1 over writes obj2
    merge: function (obj1, obj2) {
        for(var p in obj2) {
            try  {
                if(obj1.hasOwnProperty(p)) {
                    obj1[p] = merge(obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch (e) {
                obj1[p] = obj2[p];
            }
        }

        return obj1;
    },

    isRegexId: function (id) {
        return !!this.OPTS.idRegex && isString(id) && this.OPTS.idRegex.test(id);
    },

    isGraphReference: function (val) {
        return isString(val) && graphRegex.test(val);
    },

    isObject: function (o) {
        return toString.call(o) === '[object Object]';
    },

    isClosure: function (val) {
        return isString(val) && closureRegex.test(val);
    },

    isArray: function (o) {
        return toString.call(o) === '[object Array]';
    }
};
<|endoftext|>


<commit_before>const RichEmbed = require('discord.js').RichEmbed;
const got = require('got');

exports.randomSelection = (choices) => {
    return choices[Math.floor(Math.random() * choices.length)];
};

exports.randomColor = () => {
    return [Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256)];
};

exports.formatNumber = (number) => {
    if (isNaN(number)) return NaN;
    let input = `${number}`;
    if (number < 1e4) return input;
    let out = [];
    while (input.length > 3) {
        out.push(input.substr(input.length - 3, input.length));
        input = input.substr(0, input.length - 3);
    }
    return `${input},${out.reverse().join(',')}`;
};

const randomFooter = () => {
    return exports.randomSelection([
        'just add water!',
        'Powered by squirrels!',
        'codeisluvcodeislife',
        'Where did you get that?',
        'WHAT DID YOU BREAK!?',
        'D-D-D-DROP THE BASS',
        'Eat, Sleep, Dubstep',
        '#BlameRayzr522'
    ]);
};

exports.embed = (title, description = '', fields = [], options = {}) => {
    let url = options.url || '';
    let color = options.color || this.randomColor();

    if (options.inline) {
        if (fields.length % 3 === 2) {
            fields.push({ name: '\u200b', value: '\u200b' });
        }
        fields.forEach(obj => {
            obj.inline = true;
        });
    }

    return new RichEmbed({ fields, video: options.video || url })
        .setTitle(title)
        .setColor(color)
        .setDescription(description)
        .setURL(url)
        .setImage(options.image)
        .setTimestamp(options.timestamp ? timestampToDate(options.timestamp) : null)
        .setFooter(options.footer === true ? randomFooter() : (options.footer ? options.footer : ''), options.footer ? global.bot.user.avatarURL : undefined)
        .setAuthor(options.author === undefined ? '' : options.author)
        .setThumbnail(options.thumbnail);
};

function timestampToDate(timestamp) {
    if (timestamp === true) {
        return new Date();
    }
    if (typeof timestamp === 'number') {
        return new Date(timestamp);
    }
    return timestamp;
}

exports.parseArgs = (args, options) => {
    if (!options)
        return args;
    if (typeof options === 'string')
        options = [options];

    let optionValues = {};

    let i;
    for (i = 0; i < args.length; i++) {
        let arg = args[i];
        if (!arg.startsWith('-')) {
            break;
        }

        let label = arg.substr(1);

        if (options.indexOf(label + ':') > -1) {
            let leftover = args.slice(i + 1).join(' ');
            let matches = leftover.match(/^"(.+?)"/);
            if (matches) {
                optionValues[label] = matches[1];
                i += matches[0].split(' ').length;
            } else {
                i++;
                optionValues[label] = args[i];
            }
        } else if (options.indexOf(label) > -1) {
            optionValues[label] = true;
        } else {
            break;
        }
    }

    return {
        options: optionValues,
        leftover: args.slice(i)
    };
};

exports.multiSend = (channel, messages, delay) => {
    delay = delay || 100;
    messages.forEach((m, i) => {
        setTimeout(() => {
            channel.send(m);
        }, delay * i);
    });
};

exports.sendLarge = (channel, largeMessage, options = {}) => {
    let message = largeMessage;
    let messages = [];
    let prefix = options.prefix || '';
    let suffix = options.suffix || '';

    let max = 2000 - prefix.length - suffix.length;

    while (message.length >= max) {
        let part = message.substr(0, max);
        let cutTo = max;
        if (options.cutOn) {
            /*
             Prevent infinite loop where lastIndexOf(cutOn) is the first char in `part`
             Later, we will correct by +1 since we did lastIndexOf on all but the first char in `part`
             We *dont* correct immediately, since if cutOn is not found, cutTo will be -1, and we dont want that
             to become 0
             */
            cutTo = part.slice(1).lastIndexOf(options.cutOn);

            // Prevent infinite loop when cutOn isnt found in message
            if (cutTo === -1) {
                cutTo = max;
            } else {
                // Correction necessary from a few lines above
                cutTo += 1;

                if (options.cutAfter) {
                    cutTo += 1;
                }
                part = part.substr(0, cutTo);
            }
        }
        messages.push(prefix + part + suffix);
        message = message.substr(cutTo);
    }

    if (message.length > 1) {
        messages.push(prefix + message + suffix);
    }

    this.multiSend(channel, messages, options.delay);
};

exports.now = () => {
    let now = process.hrtime();
    return now[0] * 1e3 + now[1] / 1e6;
};

exports.playAnimation = (msg, delay, list) => {
    if (list.length < 1)
        return;

    let next = list.shift();
    let start = this.now();

    msg.edit(next).then(() => {
        let elapsed = this.now() - start;

        setTimeout(() => {
            this.playAnimation(msg, delay, list);
        }, Math.max(50, delay - elapsed));
    });
};

exports.uploadMethods = {
    hastebin: 'hastebin',
    ix: 'ix.io'
};

exports.textUpload = (text, options) => {
    options = options || {};
    let method = (options.method || exports.uploadMethods.hastebin).toLowerCase();

    if (method === exports.uploadMethods.ix) {
        return exports.ixUpload(text);
    } else if (method === exports.uploadMethods.hastebin) {
        return exports.hastebinUpload(text);
    }
};

exports.hastebinUpload = text => {
    return got('https://hastebin.com/documents', { body: { 'contents': text }, form: true })
        .then(res => {
            if (res && res.body && res.body.key) {
                const key = res.body.key;
                return {
                    key: key,
                    success: true,
                    url: `https://hastebin.com/${key}`,
                    rawUrl: `https://hastebin.com/raw/${key}`
                };
            } else {
                return {
                    success: false
                };
            }
        });
};

exports.ixUpload = text => {
    return got('http://ix.io', { body: { 'f:1': text }, form: true })
        .then(res => {
            if (res && res.body) {
                return {
                    success: true,
                    url: res.body,
                    rawUrl: res.body
                };
            } else {
                return {
                    success: false
                };
            }
        });
};

exports.quoteRegex = (input) => `${input}`.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&');

<commit_msg>Cleaned up utils.js<commit_after>const RichEmbed = require('discord.js').RichEmbed;
const got = require('got');

const randomSelection = choices => choices[Math.floor(Math.random() * choices.length)];

const randomColor = () => [
    Math.floor(Math.random() * 256),
    Math.floor(Math.random() * 256),
    Math.floor(Math.random() * 256)
];

const randomFooter = () => {
    return randomSelection([
        'just add water!',
        'Powered by squirrels!',
        'codeisluvcodeislife',
        'Where did you get that?',
        'WHAT DID YOU BREAK!?',
        'D-D-D-DROP THE BASS',
        'Eat, Sleep, Dubstep',
        '#BlameRayzr522'
    ]);
};

const formatNumber = number => isNaN(number) ? NaN : number.toLocaleString();

const quoteRegex = input => `${input}`.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&');

const now = () => {
    let now = process.hrtime();
    return now[0] * 1e3 + now[1] / 1e6;
};

const timestampToDate = timestamp => {
    if (timestamp === true) {
        return new Date();
    }
    if (typeof timestamp === 'number') {
        return new Date(timestamp);
    }
    return timestamp;
};

const parseArgs = (args, options) => {
    if (!options)
        return args;
    if (typeof options === 'string')
        options = [options];

    let optionValues = {};

    let i;
    for (i = 0; i < args.length; i++) {
        let arg = args[i];
        if (!arg.startsWith('-')) {
            break;
        }

        let label = arg.substr(1);

        if (options.indexOf(label + ':') > -1) {
            let leftover = args.slice(i + 1).join(' ');
            let matches = leftover.match(/^"(.+?)"/);
            if (matches) {
                optionValues[label] = matches[1];
                i += matches[0].split(' ').length;
            } else {
                i++;
                optionValues[label] = args[i];
            }
        } else if (options.indexOf(label) > -1) {
            optionValues[label] = true;
        } else {
            break;
        }
    }

    return {
        options: optionValues,
        leftover: args.slice(i)
    };
};

const embed = (title, description = '', fields = [], options = {}) => {
    let url = options.url || '';
    let color = options.color || this.randomColor();

    if (options.inline) {
        if (fields.length % 3 === 2) {
            fields.push({ name: '\u200b', value: '\u200b' });
        }
        fields.forEach(obj => {
            obj.inline = true;
        });
    }

    return new RichEmbed({ fields, video: options.video || url })
        .setTitle(title)
        .setColor(color)
        .setDescription(description)
        .setURL(url)
        .setImage(options.image)
        .setTimestamp(options.timestamp ? timestampToDate(options.timestamp) : null)
        .setFooter(options.footer === true ? randomFooter() : (options.footer ? options.footer : ''), options.footer ? global.bot.user.avatarURL : undefined)
        .setAuthor(options.author === undefined ? '' : options.author)
        .setThumbnail(options.thumbnail);
};

const multiSend = (channel, messages, delay) => {
    delay = delay || 100;
    messages.forEach((m, i) => {
        setTimeout(() => {
            channel.send(m);
        }, delay * i);
    });
};

const sendLarge = (channel, largeMessage, options = {}) => {
    let message = largeMessage;
    let messages = [];
    let prefix = options.prefix || '';
    let suffix = options.suffix || '';

    let max = 2000 - prefix.length - suffix.length;

    while (message.length >= max) {
        let part = message.substr(0, max);
        let cutTo = max;
        if (options.cutOn) {
            /*
             Prevent infinite loop where lastIndexOf(cutOn) is the first char in `part`
             Later, we will correct by +1 since we did lastIndexOf on all but the first char in `part`
             We *dont* correct immediately, since if cutOn is not found, cutTo will be -1, and we dont want that
             to become 0
             */
            cutTo = part.slice(1).lastIndexOf(options.cutOn);

            // Prevent infinite loop when cutOn isnt found in message
            if (cutTo === -1) {
                cutTo = max;
            } else {
                // Correction necessary from a few lines above
                cutTo += 1;

                if (options.cutAfter) {
                    cutTo += 1;
                }
                part = part.substr(0, cutTo);
            }
        }
        messages.push(prefix + part + suffix);
        message = message.substr(cutTo);
    }

    if (message.length > 1) {
        messages.push(prefix + message + suffix);
    }

    multiSend(channel, messages, options.delay);
};

const playAnimation = (msg, delay, list) => {
    if (list.length < 1)
        return;

    let next = list.shift();
    let start = this.now();

    msg.edit(next).then(() => {
        let elapsed = this.now() - start;

        setTimeout(() => {
            playAnimation(msg, delay, list);
        }, Math.max(50, delay - elapsed));
    });
};

const uploadMethods = {
    hastebin: 'hastebin',
    ix: 'ix.io'
};

const textUpload = (text, options) => {
    options = options || {};
    let method = (options.method || uploadMethods.hastebin).toLowerCase();

    if (method === uploadMethods.ix) {
        return ixUpload(text);
    } else if (method === uploadMethods.hastebin) {
        return hastebinUpload(text);
    }
};

const hastebinUpload = text => {
    return got('https://hastebin.com/documents', { body: { 'contents': text }, form: true })
        .then(res => {
            if (res && res.body && res.body.key) {
                const key = res.body.key;
                return {
                    key: key,
                    success: true,
                    url: `https://hastebin.com/${key}`,
                    rawUrl: `https://hastebin.com/raw/${key}`
                };
            } else {
                return {
                    success: false
                };
            }
        });
};

const ixUpload = text => {
    return got('http://ix.io', { body: { 'f:1': text }, form: true })
        .then(res => {
            if (res && res.body) {
                return {
                    success: true,
                    url: res.body,
                    rawUrl: res.body
                };
            } else {
                return {
                    success: false
                };
            }
        });
};

module.exports = {
    // Randomizers
    randomSelection,
    randomColor,
    randomFooter,
    // Formatter
    formatNumber,
    quoteRegex,
    // Times
    now,
    timestampToDate,
    // Message utilities
    parseArgs,
    embed,
    multiSend,
    sendLarge,
    playAnimation,
    // Services
    uploadMethods,
    textUpload,
    hastebinUpload,
    ixUpload
};
<|endoftext|>


<commit_before>module.exports = {
  toElement: function (html) {
    var wrapper = document.createElement('div')
    wrapper.innerHTML = html
    return wrapper.firstChild
  },
  preventDefault: function (e) {
    e.preventDefault()
  },
  hasClass: function (el, klass) {
    new RegExp('\\b' + klass + '\\b').test(el.className)
  },
  removeClass: function (el, klass) {
    el.className = el.className.replace(new RegExp('\\b ?' + klass + '\\b', 'g'), '')
  },
  addClass: function (el, klass) {
    el.className = el.className.replace(new RegExp('\\b' + klass + '\\b|$'), ' ' + klass)
  },
  isFunction: function (fn) {
    return typeof fn === 'function'
  },
  isNumber: function (num) {
    return toString.call(num) === '[object Number]'
  },
  isString: function (str) {
    return toString.call(str) === '[object String]'
  }
}
<commit_msg>Remove util.js<commit_after><|endoftext|>


<commit_before>/**
 * Project: wampy.js
 *
 * https://github.com/KSDaemon/wampy.js
 *
 * A lightweight client-side implementation of
 * WAMP (The WebSocket Application Messaging Protocol)
 * http://wamp.ws
 *
 * Provides asynchronous RPC/PubSub over WebSocket.
 *
 * Copyright 2014 KSDaemon. Licensed under the MIT License.
 * See license text at http://www.opensource.org/licenses/mit-license.php
 *
 */

;(function(window, document, undefined) {

	var wampcli = function () {

	};

	function getServerUrl (url) {
		var scheme, port, path;

		if (!url) {
			scheme = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
			port = window.location.port !== "" ? ':' + window.location.port : '';
			return scheme + window.location.hostname + port + "/ws";
		} else if (/^ws/.test(url)) {   // scheme is specified
			return url;
		} else if (/:\d{1,5}/.test(url)) {  // port is specified
			scheme = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
			return scheme + url;
		} else {    // just path on current server
			scheme = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
			port = window.location.port !== "" ? ':' + window.location.port : '';
			path = url[0] === '/' ? url : '/' + url;
			return scheme + window.location.hostname + port + path;
		}
	};

	function generateId () {
		var keyChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
			keyLen = 16,
			key = "",
			l = keyChars.length;

		while (keyLen--) {
			key += keyChars.charAt(Math.floor(Math.random() * l));
		}
		return key;
	};

})(window, document);
<commit_msg>Added WAMP msg types<commit_after>/**
 * Project: wampy.js
 *
 * https://github.com/KSDaemon/wampy.js
 *
 * A lightweight client-side implementation of
 * WAMP (The WebSocket Application Messaging Protocol)
 * http://wamp.ws
 *
 * Provides asynchronous RPC/PubSub over WebSocket.
 *
 * Copyright 2014 KSDaemon. Licensed under the MIT License.
 * See license text at http://www.opensource.org/licenses/mit-license.php
 *
 */

;(function(window, document, undefined) {

	var WAMP_SPEC = {
		TYPE_ID_WELCOME: 0,
		TYPE_ID_PREFIX: 1,
		TYPE_ID_CALL: 2,
		TYPE_ID_CALLRESULT: 3,
		TYPE_ID_CALLERROR: 4,
		TYPE_ID_SUBSCRIBE: 5,
		TYPE_ID_UNSUBSCRIBE: 6,
		TYPE_ID_PUBLISH: 7,
		TYPE_ID_EVENT: 8
	};

	function getServerUrl (url) {
		var scheme, port, path;

		if (!url) {
			scheme = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
			port = window.location.port !== "" ? ':' + window.location.port : '';
			return scheme + window.location.hostname + port + "/ws";
		} else if (/^ws/.test(url)) {   // scheme is specified
			return url;
		} else if (/:\d{1,5}/.test(url)) {  // port is specified
			scheme = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
			return scheme + url;
		} else {    // just path on current server
			scheme = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
			port = window.location.port !== "" ? ':' + window.location.port : '';
			path = url[0] === '/' ? url : '/' + url;
			return scheme + window.location.hostname + port + path;
		}
	};

	function generateId () {
		var keyChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
			keyLen = 16,
			key = "",
			l = keyChars.length;

		while (keyLen--) {
			key += keyChars.charAt(Math.floor(Math.random() * l));
		}
		return key;
	};

	function getWebSocket (url, protocols) {
		if ("WebSocket" in window) {
		// Chrome, MSIE, newer Firefox
			if (protocols) {
				return new WebSocket(url, protocols);
			} else {
				return new WebSocket(url);
			}
		} else if ("MozWebSocket" in window) {
			// older versions of Firefox
			if (protocols) {
				return new MozWebSocket(url, protocols);
			} else {
				return new MozWebSocket(url);
			}
		} else {
			return null;
		}
	};

	var wampy = function (url, protocols) {

		this._ws = null;

		if(url) {
			this._ws = getWebSocket(url, protocols);
		}

	};

	wampy.prototype.connect = function (url, protocols) {
		this._ws = getWebSocket(url, protocols);
	};

	window.wampy = wampy;

})(window, document);
<|endoftext|>


<commit_before>'use strict'

var Seneca = require('seneca')
var Mesh = require('seneca-mesh')

var envs = process.env
var opts = {
  seneca: {
    tag: envs.BASE_TAG || 'nodezoo-base'
  },
  mesh: {
    base: true
  }
}

Seneca(opts.seneca)
  .use(Mesh, opts.mesh)
<commit_msg>added HOST env<commit_after>'use strict'

var Seneca = require('seneca')
var Mesh = require('seneca-mesh')

var envs = process.env
var opts = {
  seneca: {
    tag: envs.BASE_TAG || 'nodezoo-base'
  },
  mesh: {
    base: true,
    host: envs.BASE_HOST
  }
}

Seneca(opts.seneca)
  .use(Mesh, opts.mesh)
<|endoftext|>


<commit_before>'use strict'

var Seneca = require('seneca')
var Mesh = require('seneca-mesh')
var Npm = require('../lib/npm')
var Entity = requre('seneca-entity')

var envs = process.env
var opts = {
  seneca: {
    tag: envs.NPM_TAG || 'nodezoo-search'
  },
  npm: {
  },
  mesh: {
    auto: true,
    listen: [
      {pin: 'role:npm,cmd:get', model: 'consume'},
      {pin: 'role:info,req:part', model: 'observe'}
    ]
  }
}

Seneca(opts.seneca)
  .use(Entity)
  .use(Npm, opts.npm)
  .use(Mesh, opts.mesh)
<commit_msg>Yeah I can't spell<commit_after>'use strict'

var Seneca = require('seneca')
var Mesh = require('seneca-mesh')
var Npm = require('../lib/npm')
var Entity = require('seneca-entity')

var envs = process.env
var opts = {
  seneca: {
    tag: envs.NPM_TAG || 'nodezoo-search'
  },
  npm: {
  },
  mesh: {
    auto: true,
    listen: [
      {pin: 'role:npm,cmd:get', model: 'consume'},
      {pin: 'role:info,req:part', model: 'observe'}
    ]
  }
}

Seneca(opts.seneca)
  .use(Entity)
  .use(Npm, opts.npm)
  .use(Mesh, opts.mesh)
<|endoftext|>


<commit_before>// -- settings, immutable -- //
var BRIGHTNESS_FACTOR = 10; // Higher = brighter
var STAR_SIZE_PIXELS = 1.5;
var STAR_RANGE_INDICES = 10; // Higher = more random looking, comp expensive
var LEVEL_DEPTH = 5; // Higher = more (faint) stars, comp expensive

// TODO:
// - touchscreen support
// - resize / fullscreen
// - older browsers / polyfill

var MAX_INT = -1 >>> 1;

// -- zoom and pan, altered by listeners -- //
var offsetX = 0; // Top left has this x coordinate in world frame.
var offsetY = 0;
// scale of 1 means 1 world unit = 1 canvas pixel
// scale of 100 means 1 world unit = 100 canvas pixels
var scale = 1;

var canvas = document.getElementById("starfield");
canvas.style['background-color'] = 'black';
var context = canvas.getContext('2d');

var timestamps = [];

var cache = new RRCache(100000);
function cachedMD5(to_hash) {
  var cached = cache.get(to_hash);
  if (cached) return cached; else {
    var digest = SparkMD5.hash(to_hash, true);
    cache.set(to_hash, digest);
    return digest;
  }
}

function render() {
  var worldWidth = canvas.width / scale;
  var worldHeight = canvas.height / scale;

  // The level at which you would expect one star in current viewport.
  var levelForCurrentScale = - Math.log(worldWidth * worldHeight) / 2
  var startLevel = Math.floor(levelForCurrentScale);
  context.clearRect(0, 0, canvas.width, canvas.height);

  for (level = startLevel; level < startLevel + LEVEL_DEPTH; level++) {
    var spacing = Math.exp(-level);
    for (
      xIndex = Math.floor(offsetX / spacing) - STAR_RANGE_INDICES;
      xIndex <= Math.ceil((offsetX + worldWidth) / spacing)
        + STAR_RANGE_INDICES;
      xIndex++
    ) {
      for (
        yIndex = Math.floor(offsetY / spacing) - STAR_RANGE_INDICES;
        yIndex <= Math.ceil((offsetY + worldHeight) / spacing)
          + STAR_RANGE_INDICES;
        yIndex++
      ) {
        var hash = cachedMD5(xIndex + ':' + yIndex + ':' + level);
        var x = xIndex * spacing
          + (hash[0] / MAX_INT) * spacing * STAR_RANGE_INDICES;
        var y = yIndex * spacing
          + (hash[1] / MAX_INT) * spacing * STAR_RANGE_INDICES;
	var z = Math.atan(
          Math.exp(-level + (hash[2] / MAX_INT)) * BRIGHTNESS_FACTOR
            / Math.exp(-levelForCurrentScale)
        ) * 2 / Math.PI;
        context.fillStyle = 'rgba(255, 255, 255, ' + z + ')';
        context.fillRect(
          (x - offsetX) * scale,
          (y - offsetY) * scale,
          STAR_SIZE_PIXELS,
          STAR_SIZE_PIXELS
        );
      }
    }
  }

  timestamps.push(new Date().getTime());
  if (timestamps.length > 10) {
    console.log(
      (9 * 1000 / (timestamps[9] - timestamps[0])).toFixed(2) + ' fps'
    );
    timestamps = [];
  }
  requestAnimationFrame(render);
}

requestAnimationFrame(render);
<commit_msg>quantize and batch calls to fillStyle<commit_after>// -- settings, immutable -- //
var BRIGHTNESS_FACTOR = 10; // Higher = brighter
var STAR_SIZE_PIXELS = 1.5;
var STAR_RANGE_INDICES = 10; // Higher = more random looking, comp expensive
var LEVEL_DEPTH = 5; // Higher = more (faint) stars, comp expensive

// TODO:
// - touchscreen support
// - resize / fullscreen
// - older browsers / polyfill

var MAX_INT = -1 >>> 1;

// -- zoom and pan, altered by listeners -- //
var offsetX = 0; // Top left has this x coordinate in world frame.
var offsetY = 0;
// scale of 1 means 1 world unit = 1 canvas pixel
// scale of 100 means 1 world unit = 100 canvas pixels
var scale = 1;

var canvas = document.getElementById("starfield");
canvas.style['background-color'] = 'black';
var context = canvas.getContext('2d');

var timestamps = [];

var cache = new RRCache(100000);
function cachedMD5(to_hash) {
  var cached = cache.get(to_hash);
  if (cached) return cached; else {
    var digest = SparkMD5.hash(to_hash, true);
    cache.set(to_hash, digest);
    return digest;
  }
}

function render() {
  var worldWidth = canvas.width / scale;
  var worldHeight = canvas.height / scale;

  // The level at which you would expect one star in current viewport.
  var levelForCurrentScale = - Math.log(worldWidth * worldHeight) / 2
  var startLevel = Math.floor(levelForCurrentScale);
  context.clearRect(0, 0, canvas.width, canvas.height);

  // setting fillStyle is expensive, so quantize and batch it.
  var brightnessToWorldPositions = [];
  for (var i = 0; i < 100; i++) brightnessToWorldPositions.push([]);

  for (level = startLevel; level < startLevel + LEVEL_DEPTH; level++) {
    var spacing = Math.exp(-level);
    for (
      xIndex = Math.floor(offsetX / spacing) - STAR_RANGE_INDICES;
      xIndex <= Math.ceil((offsetX + worldWidth) / spacing)
        + STAR_RANGE_INDICES;
      xIndex++
    ) {
      for (
        yIndex = Math.floor(offsetY / spacing) - STAR_RANGE_INDICES;
        yIndex <= Math.ceil((offsetY + worldHeight) / spacing)
          + STAR_RANGE_INDICES;
        yIndex++
      ) {
        var hash = cachedMD5(xIndex + ':' + yIndex + ':' + level);
        brightnessToWorldPositions[
          Math.floor(
	    100 * Math.atan(
              Math.exp(-level + (hash[2] / MAX_INT)) * BRIGHTNESS_FACTOR
                / Math.exp(-levelForCurrentScale)
            ) * 2 / Math.PI
          )
        ].push([
          xIndex * spacing
            + (hash[0] / MAX_INT) * spacing * STAR_RANGE_INDICES,
          yIndex * spacing
            + (hash[1] / MAX_INT) * spacing * STAR_RANGE_INDICES,
        ]);
      }
    }
  }

  for (i = 0; i < 100; i++) {
    context.fillStyle = 'rgba(255, 255, 255, ' + i / 100 + ')';
    var to_paint = brightnessToWorldPositions[i];
    for (var j = 0; j < to_paint.length; j++) {
      context.fillRect(
        (to_paint[j][0] - offsetX) * scale,
        (to_paint[j][1] - offsetY) * scale,
        STAR_SIZE_PIXELS,
        STAR_SIZE_PIXELS
      );
    }
  }

  timestamps.push(new Date().getTime());
  if (timestamps.length > 10) {
    console.log(
      (9 * 1000 / (timestamps[9] - timestamps[0])).toFixed(2) + ' fps'
    );
    timestamps = [];
  }
  requestAnimationFrame(render);
}

requestAnimationFrame(render);
<|endoftext|>


<commit_before>(function(global){
  'use strict';
  var previous = [null];
  var handlers = [];
  var hashRegex = /#.*$/;

  var fireHandlers = function(fragment) {
    for (var i = 0; i<handlers.length; i++) {
      handlers[i](fragment);
    }
  };

  /**
   * Removes the given handler from the registered
   * handlers.
   *
   * @param {Function} handler
   */
  var off = function(handler) {
    var idx = handlers.indexOf(handler);
    if (idx !== -1) {
      handlers.splice(idx, 1);
    }
  };

  /**
   * Clears the array of registered handlers.
   */
  var clear = function() {
    handlers.length = 0;
  };

  /**
   * Mark the state as processed- if the hash is
   * changed to the identical state then no Stateless
   * handlers will be fired. You do not need to prefix
   * the state with a hashtag.
   *
   * @param {String} state
   */
  var skip = function(state) {
    previous[0] = '#' + state;
  };

  /**
   * Pull the current state from the URL, and
   * forcefully runs the handlers regardless
   * of whether the hash has changed.
   */
  var pull = function() {
    var fragment = window.location.hash.substr(1);
    fireHandlers(fragment);
    skip(fragment);
  };

  /**
   * Set the current hash fragment as the given
   * state. Note that it is not necessary to
   * preceed your strings with '#'.
   *
   * @param {String} state
   */
  var push = function(state) {
    window.location.hash = state;
  };

  /**
   * Replaces the current hash with the given state.
   * Does not push another entry into the browser
   * history.
   *
   * @param {String} state
   */
  var replace = function(state) {
    window.location.replace('#' + state);
  };

  /**
   * Register a Stateless handler. Handlers will
   * be passed the hash fragment after the hash
   * character.
   *
   * @param {Function} handler
   */
  var onChange = function(handler) {
    handlers.push(handler);
  };

  window.addEventListener('hashchange', function() {
    // Workaround for Firefox which automatically
    // decodes the hash fragment [bug:483304]
    var match = hashRegex.exec(window.location.href);
    if (match) {
      var hash = match[0];
      if (hash !== previous[0]) {
        var fragment = hash.substring(1);
        fireHandlers(fragment);
        skip(fragment);
      }
    }
  });

  global.Stateless = {
    off: off,
    push: push,
    pull: pull,
    skip: skip,
    replace: replace,
    onChange: onChange,
    clear: clear,
  };
})(this);
<commit_msg>slightly more efficient matching function<commit_after>(function(global){
  'use strict';
  var previous = [null];
  var handlers = [];
  var hashRegex = /#.*$/;

  var fireHandlers = function(fragment) {
    for (var i = 0; i<handlers.length; i++) {
      handlers[i](fragment);
    }
  };

  /**
   * Removes the given handler from the registered
   * handlers.
   *
   * @param {Function} handler
   */
  var off = function(handler) {
    var idx = handlers.indexOf(handler);
    if (idx !== -1) {
      handlers.splice(idx, 1);
    }
  };

  /**
   * Clears the array of registered handlers.
   */
  var clear = function() {
    handlers.length = 0;
  };

  /**
   * Mark the state as processed- if the hash is
   * changed to the identical state then no Stateless
   * handlers will be fired. You do not need to prefix
   * the state with a hashtag.
   *
   * @param {String} state
   */
  var skip = function(state) {
    previous[0] = '#' + state;
  };

  /**
   * Pull the current state from the URL, and
   * forcefully runs the handlers regardless
   * of whether the hash has changed.
   */
  var pull = function() {
    var fragment = window.location.hash.substr(1);
    fireHandlers(fragment);
    skip(fragment);
  };

  /**
   * Set the current hash fragment as the given
   * state. Note that it is not necessary to
   * preceed your strings with '#'.
   *
   * @param {String} state
   */
  var push = function(state) {
    window.location.hash = state;
  };

  /**
   * Replaces the current hash with the given state.
   * Does not push another entry into the browser
   * history.
   *
   * @param {String} state
   */
  var replace = function(state) {
    window.location.replace('#' + state);
  };

  /**
   * Register a Stateless handler. Handlers will
   * be passed the hash fragment after the hash
   * character.
   *
   * @param {Function} handler
   */
  var onChange = function(handler) {
    handlers.push(handler);
  };

  window.addEventListener('hashchange', function() {
    // Workaround for Firefox which automatically
    // decodes the hash fragment [bug:483304]
    var match = hashRegex.exec(window.location.href) || '#';
    var hash = match[0];
    if (hash !== previous[0]) {
      var fragment = hash.substring(1);
      fireHandlers(fragment);
      skip(fragment);
    }
  });

  global.Stateless = {
    off: off,
    push: push,
    pull: pull,
    skip: skip,
    replace: replace,
    onChange: onChange,
    clear: clear,
  };
})(this);
<|endoftext|>


<commit_before>var Stateless = (function(){
  'use strict';
  var skipped = {};
  var handlers = [];
  var hashRegex = /#(.*)$/;

  var fire = function(state) {
    for (var i = 0; i < handlers.length; i++) {
      handlers[i](state);
    }
  };

  var getState = function() {
    // Workaround for Firefox which automatically
    // decodes the hash fragment [bug:483304]
    var hash = hashRegex.exec(window.location.href);
    return hash ? hash[1] : '';
  };

  var off = function(fn) {
    var idx = handlers.indexOf(fn);
    if (idx !== -1)
      handlers.splice(idx, 1);
  };

  window.addEventListener('hashchange', function() {
    var state = getState();
    if (skipped[state])
      delete skipped[state];
    else
      Stateless.pull();
  });

  return {
    // Control
    off: off,
    clear:    function() { handlers = []; },
    skip:     function(s) { skipped[s] = true; },
    onChange: function(fn) { handlers.push(fn); },

    // Firing
    pull:    function() { fire(getState()); },
    push:    function(s) { window.location.hash = '#' + s; },
    replace: function(s) { window.location.replace('#' + s); },
  };
})();
<commit_msg>Reduced code size<commit_after>var Stateless = (function(window){
  'use strict';
  var skipped = {};
  var handlers = [];
  var hashRegex = /#(.*)$/;

  var fire = function(state) {
    for (var i = 0; i < handlers.length; i++) {
      handlers[i](state);
    }
  };

  var getState = function() {
    // Workaround for Firefox which automatically
    // decodes the hash fragment [bug:483304]
    var hash = hashRegex.exec(window.location.href);
    return hash ? hash[1] : '';
  };

  var off = function(fn) {
    var idx = handlers.indexOf(fn);
    if (idx !== -1)
      handlers.splice(idx, 1);
  };

  window.addEventListener('hashchange', function() {
    var state = getState();
    if (skipped[state])
      delete skipped[state];
    else
      Stateless.pull();
  });

  return {
    // Control
    off: off,
    clear:    function() { handlers = []; },
    skip:     function(s) { skipped[s] = true; },
    onChange: function(fn) { handlers.push(fn); },

    // Firing
    pull:    function() { fire(getState()); },
    push:    function(s) { window.location.hash = '#' + s; },
    replace: function(s) { window.location.replace('#' + s); },
  };
})(window);
<|endoftext|>


<commit_before>/**
 * StopFlash
 *
 * https://github.com/JWhile/StopFlash
 *
 * stopflash.js
 */

// class StopFlashPopup
function StopFlashPopup(doc)
{
    this.ui = new StopFlashUI()
            .insert(doc.body);

    var self = this;

    chrome.tabs.query({'highlighted': true, 'currentWindow': true}, function(tabs)
    {
        var port = chrome.runtime.connect({'name': 'stopflashPopup'});

        port.onMessage.addListener(function(rep)
        {
            if(rep['stopflashData'])
            {
                self.ui.setElements(rep['stopflashData']);
            }
        });

        port.postMessage({'stopflashInit': tabs[0].id});
    });
}

// class StopFlashUI extends Builder
function StopFlashUI()
{
    this.super('div');

    this.mainTab = new Builder('div');

    this.content = new StopFlashTabs()
        .className('content')
        .addTab(this.mainTab)
        .addTab(new Builder('div')
            .text('Whitelist tab'))
        .addTab(new Builder('div')
            .text('Options tab'))
        .setTab(0);

    var self = this;

    this.append(new Builder('div')
            .className('head')
            .append(new Builder('p')
                .className('logo')
                .html('STP Flash')))
        .append(new Builder('div')
            .className('menu')
            .append(new Builder('a')
                .text('Home')
                .event('click', function()
                {
                    self.content.setTab(0);
                }))
            .append(new Builder('a')
                .text('Whitelist')
                .event('click', function()
                {
                    self.content.setTab(1);
                }))
            .append(new Builder('a')
                .text('Options')
                .event('click', function()
                {
                    self.content.setTab(2);
                })))
        .append(this.content)
        .append(new Builder('div')
            .className('foot')
            .html('https://github.com/JWhile/StopFlash'));

    this.setElements(null);
}
// function setElements(Array<Object> elements):void
StopFlashUI.prototype.setElements = function(elements)
{
    this.mainTab.clear();

    if(elements != null && elements.length > 0)
    {
        var self = this;

        for(var i = 0, e; i < elements.length; ++i)
        {
            e = elements[i];

            this.mainTab.append(new Builder('div')
                .className('flash-element')
                .append(new Builder('div')
                    .className('flash-menu')
                    .append(new Builder('a')
                        .text(e.blocked? 'Débloquer' : 'Bloquer')
                        .event('click', function()
                        {
                            //
                        }))
                    .append(new Builder('a')
                        .text(e.whitelist? '- Whitelist' : '+ Whitelist')
                        .event('click', function()
                        {
                            //
                        })))
                .append(new Builder('p')
                    .className('flash-url')
                    .text(e.url))
                .append(new Builder('span')
                    .className('flash-type')
                    .text(e.type)));
        }
    }
    else
    {
        this.mainTab.append(new Builder('p').text('Aucun element trouvé sur cette page'));
    }
};
fus.extend(StopFlashUI, Builder);

// class StopFlashTabs extends Builder
function StopFlashTabs()
{
    this.super('div');

    this.tabs = []; // :Array<Builder>
}
// function addTab(Builder builder):@Chainable
StopFlashTabs.prototype.addTab = function(builder)
{
    this.tabs.push(new Builder('div')
        .className('tab')
        .css('left', (this.tabs.length * 300) +'px')
        .append(builder.className('tab-content'))
        .insert(this));

    return this;
};
// function setTab(int index):@Chainable
StopFlashTabs.prototype.setTab = function(index)
{
    for(var i = 0; i < this.tabs.length; ++i)
    {
        if(index === i)
        {
            this.tabs[i].css('position', 'relative')
                    .css('opacity', '1');
        }
        else
        {
            this.tabs[i].css('position', '')
                    .css('opacity', '0.3');
        }
    }

    this.css('left', '-'+ (index * 300) +'px');

    return this;
};
fus.extend(StopFlashTabs, Builder);

// main
var popup = new StopFlashPopup(document);
<commit_msg>Add elements count + Add title attribute to .flash-url + Small fix<commit_after>/**
 * StopFlash
 *
 * https://github.com/JWhile/StopFlash
 *
 * stopflash.js
 */

// class StopFlashPopup
function StopFlashPopup(doc)
{
    this.ui = new StopFlashUI()
            .insert(doc.body);

    var self = this;

    chrome.tabs.query({'highlighted': true, 'currentWindow': true}, function(tabs)
    {
        var port = chrome.runtime.connect({'name': 'stopflashPopup'});

        port.onMessage.addListener(function(rep)
        {
            if(rep['stopflashData'])
            {
                self.ui.setElements(rep['stopflashData']);
            }
        });

        port.postMessage({'stopflashInit': tabs[0].id});
    });
}

// class StopFlashUI extends Builder
function StopFlashUI()
{
    this.super('div');

    this.mainTab = new Builder('div');

    this.content = new StopFlashTabs()
        .className('content')
        .addTab(this.mainTab)
        .addTab(new Builder('div')
            .text('Whitelist tab'))
        .addTab(new Builder('div')
            .text('Options tab'))
        .setTab(0);

    var self = this;

    this.append(new Builder('div')
            .className('head')
            .append(new Builder('p')
                .className('logo')
                .html('STP Flash')))
        .append(new Builder('div')
            .className('menu')
            .append(new Builder('a')
                .text('Home')
                .event('click', function()
                {
                    self.content.setTab(0);
                }))
            .append(new Builder('a')
                .text('Whitelist')
                .event('click', function()
                {
                    self.content.setTab(1);
                }))
            .append(new Builder('a')
                .text('Options')
                .event('click', function()
                {
                    self.content.setTab(2);
                })))
        .append(this.content)
        .append(new Builder('div')
            .className('foot')
            .html('https://github.com/JWhile/StopFlash'));

    this.setElements(null);
}
// function setElements(Array<Object> elements):void
StopFlashUI.prototype.setElements = function(elements)
{
    this.mainTab.clear();

    if(elements != null && elements.length > 0)
    {
        var self = this;

        this.mainTab.append(new Builder('p')
            .text(elements.length + ((elements.length > 1)? ' elements trouvés' : ' element trouvé')))

        for(var i = 0, e; i < elements.length; ++i)
        {
            e = elements[i];

            this.mainTab.append(new Builder('div')
                .className('flash-element')
                .append(new Builder('p')
                    .className('flash-url')
                    .set('title', e.url)
                    .text(e.url))
                .append(new Builder('span')
                    .className('flash-type')
                    .text(e.type))
                .append(new Builder('div')
                    .className('flash-menu')
                    .append(new Builder('a')
                        .text(e.blocked? 'Débloquer' : 'Bloquer')
                        .event('click', function()
                        {
                            //
                        }))
                    .append(new Builder('a')
                        .text(e.whitelist? '- Whitelist' : '+ Whitelist')
                        .event('click', function()
                        {
                            //
                        }))));
        }
    }
    else
    {
        this.mainTab.append(new Builder('p').text('Aucun element trouvé sur cette page'));
    }
};
fus.extend(StopFlashUI, Builder);

// class StopFlashTabs extends Builder
function StopFlashTabs()
{
    this.super('div');

    this.tabs = []; // :Array<Builder>
}
// function addTab(Builder builder):@Chainable
StopFlashTabs.prototype.addTab = function(builder)
{
    this.tabs.push(new Builder('div')
        .className('tab')
        .css('left', (this.tabs.length * 300) +'px')
        .append(builder.className('tab-content'))
        .insert(this));

    return this;
};
// function setTab(int index):@Chainable
StopFlashTabs.prototype.setTab = function(index)
{
    for(var i = 0; i < this.tabs.length; ++i)
    {
        if(index === i)
        {
            this.tabs[i].css('position', 'relative')
                    .css('opacity', '1');
        }
        else
        {
            this.tabs[i].css('position', '')
                    .css('opacity', '0.3');
        }
    }

    this.css('left', '-'+ (index * 300) +'px');

    return this;
};
fus.extend(StopFlashTabs, Builder);

// main
var popup = new StopFlashPopup(document);
<|endoftext|>