<commit_before>// This modules defines the behavior of the client's OT. It handles the
// buffering of operations yet to be committed to the master document and the
// responsibility of transforming those operations if the server sends new
// operations before they have all been committed.
//
// While this code is meant to run on the client, it does not contain any DOM
// manipulation, or browser specific code. All of that is abstracted and
// sandboxed within the `ui` option for the `OTDocument` constructor. One could
// fairly easily use some front end other than the browser with little to no
// changes so long as they provide the functions required in the ui parameter.

/*jslint onevar: true, undef: true, eqeqeq: true, bitwise: true,
  newcap: true, immed: true, nomen: false, white: false, plusplus: false,
  laxbreak: true */

/*global define, setTimeout */

define([
    "./apply",
    "./xform",
    "./operations",
    "./messages"
], function (apply, xform, operations, messages) {

    function xformEach (outgoing, ops) {
        var i, len, msg;
        for ( i = 0, len = outgoing.length; i < len; i++ ) {
            msg = outgoing[i];
            xform(messages.operations(msg), ops, function (aPrime, bPrime) {
                messages.operations(msg, aPrime);
                messages.document(msg, apply(messages.document(msg), aPrime));
                messages.revision(msg, messages.revision(msg)+1);
                ops = bPrime;
            });
        }
    }

    function error (msg) {
        throw new Error(msg);
    }

    function connect (socket, docId) {
        socket.send({
            type: "connect",
            data: {
                id: docId
            }
        });
    }

    function init (outgoing, socket, ui, initialData) {
        var previousDoc = messages.document(initialData),
            previousRevision = messages.revision(initialData),
            id = messages.id(initialData);

        ui.update(previousDoc);

        function loop () {
            var msg, uiDoc = ui.getDocument();
            if ( uiDoc !== previousDoc ) {
                msg = {};
                messages.operations(msg, operations.getOperations(previousDoc, uiDoc));
                messages.document(msg, uiDoc);
                messages.revision(msg, ++previousRevision);
                messages.id(msg, id);

                outgoing.push(msg);
                previousDoc = uiDoc;
            }
            setTimeout(loop, 50);
        }

        setTimeout(loop, 10);
    }

    // Might need to start sending client id's back and forth. Don't really want
    // to have to do a deep equality test on every check here.
    function isOurOutgoing (msg, outgoing) {
        var top = outgoing[0],
            topOps = messages.operations(top),
            msgOps = messages.operations(msg),
            i = 0,
            len = msgOps.length;
        if ( messages.id(msg) !== messages.id(top) ) {
            return false;
        }
        if ( messages.rev(msg) !== messages.rev(top) ) {
            return false;
        }
        if ( len !== topOps.length ) {
            return false;
        }
        if ( topOps.join() !== msgOps.join() ) {
            return false;
        }
        return true;
    }

    return {
        OTDocument: function (opts) {
            var outgoing = [],
                socket = opts.socket || error("socket is required"),
                ui = opts.socket || error("ui is required"),
                docId = opts.id,
                initialized = false;

            connect(socket, docId);

            // TODO: what happens if we receive an update message from the
            // server and we update the client and they lose what they were just
            // typeing because we havent saved the operations in the outgoing
            // buffer yet? Do I need to merge the main loop and handling of
            // socket messages? Maybe just have the socket's receive handler
            // queue events in an inbox and have the main loop process one
            // change that the client is creating, then one message from the
            // inbox.

            socket.receive(function (event) {
                var msg;

                switch ( event.type ) {

                case "init":
                    if ( ! initialized ) {
                        init(outgoing, socket, ui, event.data);
                    } else {
                        error("Already initialized");
                    }
                    break;

                case "update":
                    msg = event.data;
                    if ( isOurOutgoing(msg, outgoing) ) {
                        outgoing.shift();
                    } else {
                        // TODO: need to handle cursor selection and index
                        xformEach(outgoing, messages.operations(msg));
                        ui.update(messages.document(outgoing[outgoing.length-1]));
                    }

                    if ( outgoing.length > 0 ) {
                        socket.send({
                            type: "update",
                            data: outgoing[0]
                        });
                    }
                    break;

                default:
                    throw new Error("Unknown event type: " + event.type);

                }
            });
        }
    };

});<commit_msg>Fixing a bunch of bugs in the client.js, still not fully functional however<commit_after>// This modules defines the behavior of the client's OT. It handles the
// buffering of operations yet to be committed to the master document and the
// responsibility of transforming those operations if the server sends new
// operations before they have all been committed.
//
// While this code is meant to run on the client, it does not contain any DOM
// manipulation, or browser specific code. All of that is abstracted and
// sandboxed within the `ui` option for the `OTDocument` constructor. One could
// fairly easily use some front end other than the browser with little to no
// changes so long as they provide the functions required in the ui parameter.

/*jslint onevar: true, undef: true, eqeqeq: true, bitwise: true,
  newcap: true, immed: true, nomen: false, white: false, plusplus: false,
  laxbreak: true */

/*global define, setTimeout */

define([
    "./apply",
    "./xform",
    "./operations",
    "./messages"
], function (apply, xform, operations, messages) {

    function xformEach (outgoing, ops) {
        var i, len, msg;
        for ( i = 0, len = outgoing.length; i < len; i++ ) {
            msg = outgoing[i];
            xform(messages.operations(msg), ops, function (aPrime, bPrime) {
                messages.operations(msg, aPrime);
                messages.document(msg, apply(messages.document(msg), aPrime));
                messages.revision(msg, messages.revision(msg)+1);
                ops = bPrime;
            });
        }
    }

    function error (msg) {
        throw new Error(msg);
    }

    function connect (socket, docId) {
        socket.send({
            type: "connect",
            data: {
                id: docId
            }
        });
    }

    function init (outgoing, socket, ui, initialData) {
        var previousDoc = messages.document(initialData),
            previousRevision = messages.revision(initialData),
            id = messages.id(initialData);

        ui.update(previousDoc); // TODO: cursor position

        function loop () {
            var msg,
                oldOutgoingLength = outgoing.length,
                uiDoc = ui.getDocument();
            if ( uiDoc !== previousDoc ) {
                msg = {};
                messages.operations(msg, operations.getOperations(previousDoc, uiDoc));
                messages.document(msg, uiDoc);
                messages.revision(msg, ++previousRevision);
                messages.id(msg, id);

                outgoing.push(msg);
                previousDoc = uiDoc;

                if ( oldOutgoingLength === 0 ) {
                    socket.send({
                        type: "update",
                        data: outgoing[0]
                    });
                }
            }
            setTimeout(loop, 1000);
        }

        setTimeout(loop, 10);
    }

    // Might need to start sending client id's back and forth. Don't really want
    // to have to do a deep equality test on every check here.
    function isOurOutgoing (msg, outgoing) {
        var top = outgoing[0],
            topOps = messages.operations(top),
            msgOps = messages.operations(msg),
            i = 0,
            len = msgOps.length;
        if ( messages.id(msg) !== messages.id(top) ) {
            return false;
        }
        if ( messages.revision(msg) !== messages.revision(top) ) {
            return false;
        }
        if ( len !== topOps.length ) {
            return false;
        }
        if ( topOps.join() !== msgOps.join() ) {
            return false;
        }
        return true;
    }

    return {
        OTDocument: function (opts) {
            var outgoing = [],
                socket = opts.socket || error("socket is required"),
                ui = opts.ui || error("ui is required"),
                docId = opts.id,
                initialized = false;

            connect(socket, docId);

            // TODO: what happens if we receive an update message from the
            // server and we update the client and they lose what they were just
            // typeing because we havent saved the operations in the outgoing
            // buffer yet? Do I need to merge the main loop and handling of
            // socket messages? Maybe just have the socket's receive handler
            // queue events in an inbox and have the main loop process one
            // change that the client is creating, then one message from the
            // inbox.

            socket.onMessage(function (event) {
                var msg;

                switch ( event.type ) {

                case "connect":
                    if ( ! initialized ) {
                        init(outgoing, socket, ui, event.data);
                    } else {
                        error("Already initialized");
                    }
                    break;

                case "update":
                    msg = event.data;
                    if ( outgoing.length && isOurOutgoing(msg, outgoing) ) {
                        outgoing.shift();
                    } else {
                        // TODO: need to handle cursor selection and index
                        xformEach(outgoing, messages.operations(msg));

                        // TODO: cursor position
                        if ( outgoing.length ) {
                            ui.update(messages.document(outgoing[outgoing.length-1]));
                        } else {
                            ui.update(messages.document(msg));
                        }
                    }
                    break;

                default:
                    throw new Error("Unknown event type: " + event.type);

                }
            });
        }
    };

});<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter,
    util_inherit = require('util').inherits;

var BeanstalkdClient = function() {
	var Fivebeans = require('fivebeans').client,

		fivebeans_settings = require('./settings').fivebeans_settings;
	this.printer = require('./printer');

	this.client = new Fivebeans(
		fivebeans_settings.host_name, fivebeans_settings.port_address
	);

	this.is_connected = false;
	this.tube = fivebeans_settings.tube;
};

util_inherit(BeanstalkdClient, EventEmitter);

BeanstalkdClient.prototype.createClient = function() {
	var self = this;

	if (self.is_connected)
		self.emit('connected');
	else {
		self.client
			.on('connect', function() {
				// Client can now be used
				self.is_connected = true;
				self.printer('Beanstalkd client created');
				self.emit('connected');
			})
			.on('error', function(error) {
				// Connection failure
				self.printer('', error);
				self.emit('failed', 'createClient');
			})
			.on('close', function() {
				// Underlying connection has closed
			})
			.connect();
	}
};

BeanstalkdClient.prototype.endClient = function() {
	var self = this;

	self.client.end();
	self.is_connected = false;
	self.printer('Beanstalkd client ended');
};

BeanstalkdClient.prototype.consumeJob = function(callback) {
	var self = this;

	if (self.is_connected) {
		self.client.reserve(function(error, jobid, payload) {
			if (!self.printer('Reserving jobid: ' + jobid, error))
				callback(jobid, payload);
			else
				self.emit('failed');
		});
	}
	else
		self.printer('', 'There are 0 active beanstalkd clients');
};

BeanstalkdClient.prototype.produceJob = function(priority, delay, ttr, payloads) {
	var self = this;

	if (self.is_connected) {
		var each = require('async').each;

		each(payloads, function(payload, callback) {
			if (typeof payload == 'object')
				payload = JSON.stringify(payload);

			self.client.put(priority, delay, ttr, payload,
				function(error, jobid) {
				self.printer('Added jobid: ' + jobid + ' to queue', error);
				if (!error)
					self.emit('produced');
				else
					self.emit('failed', 'produceJob');
			});
			callback();
		}, function(error) {
			if (self.printer('Sent payload(s) to beanstalkd server', error))
				self.emit('failed', 'produceJob');
		});
	}
	else
		self.printer('', 'There are 0 active beanstalkd clients');
};

BeanstalkdClient.prototype.destroyJob = function(jobid, forward_value) {
	var self = this;

	if (self.is_connected) {
		self.client.destroy(jobid, function(error) {
			if (!self.printer('Deleted jobid: ' + jobid, error))
				self.emit('destroyed', forward_value);
			else
				self.emit('failed', 'destroyJob');
		});
	}
	else
		self.printer('There are 0 active beanstalkd clients');
};

BeanstalkdClient.prototype.useTube = function() {
	var self = this;

	if (self.is_connected) {
		self.client.use(self.tube, function(error, tubename) {
			if (!self.printer('Using tube: ' + tubename, error))
				self.emit('used');
			else
				self.emit('failed', 'useTube');
		});
	}
	else
		self.printer('', 'There are 0 active beanstalkd clients');
};

BeanstalkdClient.prototype.watchTube = function() {
	var self = this;

	if (self.is_connected) {
		self.client.watch(self.tube, function(error, numwatched) {
			if (!self.printer('This client is now watching ' + numwatched +
				' tubes which includes: default and ' + self.tube, error))
				self.emit('watched');
			else
				self.emit('failed', 'watchTube');
		});
	}
	else
		self.printer('', 'There are 0 active beanstalkd clients');
};

module.exports = BeanstalkdClient;
<commit_msg>Corrected tabs<commit_after>var EventEmitter = require('events').EventEmitter,
    util_inherit = require('util').inherits;

var BeanstalkdClient = function() {
	var Fivebeans = require('fivebeans').client,

        fivebeans_settings = require('./settings').fivebeans_settings;
	this.printer = require('./printer');

	this.client = new Fivebeans(
		fivebeans_settings.host_name, fivebeans_settings.port_address
	);

	this.is_connected = false;
	this.tube = fivebeans_settings.tube;
};

util_inherit(BeanstalkdClient, EventEmitter);

BeanstalkdClient.prototype.createClient = function() {
	var self = this;

	if (self.is_connected)
		self.emit('connected');
	else {
		self.client
			.on('connect', function() {
				// Client can now be used
				self.is_connected = true;
				self.printer('Beanstalkd client created');
				self.emit('connected');
			})
			.on('error', function(error) {
				// Connection failure
				self.printer('', error);
				self.emit('failed', 'createClient');
			})
			.on('close', function() {
				// Underlying connection has closed
			})
			.connect();
	}
};

BeanstalkdClient.prototype.endClient = function() {
	var self = this;

	self.client.end();
	self.is_connected = false;
	self.printer('Beanstalkd client ended');
};

BeanstalkdClient.prototype.consumeJob = function(callback) {
	var self = this;

	if (self.is_connected) {
		self.client.reserve(function(error, jobid, payload) {
			if (!self.printer('Reserving jobid: ' + jobid, error))
				callback(jobid, payload);
			else
				self.emit('failed');
		});
	}
	else
		self.printer('', 'There are 0 active beanstalkd clients');
};

BeanstalkdClient.prototype.produceJob = function(priority, delay, ttr, payloads) {
	var self = this;

	if (self.is_connected) {
		var each = require('async').each;

		each(payloads, function(payload, callback) {
			if (typeof payload == 'object')
				payload = JSON.stringify(payload);

			self.client.put(priority, delay, ttr, payload,
				function(error, jobid) {
				self.printer('Added jobid: ' + jobid + ' to queue', error);
				if (!error)
					self.emit('produced');
				else
					self.emit('failed', 'produceJob');
			});
			callback();
		}, function(error) {
			if (self.printer('Sent payload(s) to beanstalkd server', error))
				self.emit('failed', 'produceJob');
		});
	}
	else
		self.printer('', 'There are 0 active beanstalkd clients');
};

BeanstalkdClient.prototype.destroyJob = function(jobid, forward_value) {
	var self = this;

	if (self.is_connected) {
		self.client.destroy(jobid, function(error) {
			if (!self.printer('Deleted jobid: ' + jobid, error))
				self.emit('destroyed', forward_value);
			else
				self.emit('failed', 'destroyJob');
		});
	}
	else
		self.printer('There are 0 active beanstalkd clients');
};

BeanstalkdClient.prototype.useTube = function() {
	var self = this;

	if (self.is_connected) {
		self.client.use(self.tube, function(error, tubename) {
			if (!self.printer('Using tube: ' + tubename, error))
				self.emit('used');
			else
				self.emit('failed', 'useTube');
		});
	}
	else
		self.printer('', 'There are 0 active beanstalkd clients');
};

BeanstalkdClient.prototype.watchTube = function() {
	var self = this;

	if (self.is_connected) {
		self.client.watch(self.tube, function(error, numwatched) {
			if (!self.printer('This client is now watching ' + numwatched +
				' tubes which includes: default and ' + self.tube, error))
				self.emit('watched');
			else
				self.emit('failed', 'watchTube');
		});
	}
	else
		self.printer('', 'There are 0 active beanstalkd clients');
};

module.exports = BeanstalkdClient;
<|endoftext|>


<commit_before>var fs        = require('fs');
var net       = require('net');
var events    = require('events');
var path      = require('path');

var irc = {};

var config_path = (process.env.IRC_NODE_PATH ||
                   process.env.HOME + '/.ircnode');
var config_file = config_path + '/config';
var user_file   = config_path + '/users.json';
var plugin_dir  = config_path + '/plugins/';

var exists = path.existsSync(config_path);
if (!exists) {
  fs.mkdirSync(config_path, 0755);
}
var exists = path.existsSync(plugin_dir);
if (!exists) {
  fs.mkdirSync(plugin_dir, 0755);
}

var exists = path.existsSync(config_file);
if(!exists) {
  console.log('Creating a new config file');
  fs.openSync(config_file, 'w+');
  fs.writeFileSync(config_file, fs.readFileSync('./config.sample'));
}
irc.config = JSON.parse(fs.readFileSync(config_file));

path.exists(user_file, function (exists) {
  if(!exists) {
    console.log('Creating a new users.json file');
    fs.openSync(user_file, 'w+');
    fs.writeFileSync(user_file, fs.readFileSync('./users.json.sample'));
  }
  irc.users = JSON.parse(fs.readFileSync(user_file));
});

irc.command_char = '!';
irc.debug = true;
irc.emitter = new events.EventEmitter();

irc.is_admin = function(nick) {
  if (typeof irc.users[nick] === 'undefined')
    return false;

  return (irc.users[nick].auth === 'admin' || irc.users[nick].auth === 'owner');
}

irc.is_owner = function(nick) {
  if (typeof irc.users[nick] === 'undefined')
    return false;

  return (irc.users[nick].auth === 'owner');
};

irc.privmsg  = function (chan, msg) {
  irc._socket.write('PRIVMSG ' + chan + ' :' + msg + '\r\n');
};

irc.splitcmd = function (data) {
  var action = {};
  var params = data.split(' ');

  var nickuser = data.substring(0, data.indexOf(' '));
  action.nick = nickuser.split('!')[0];
  action.user = nickuser.split('!')[1].split('@')[0];
  action.host = nickuser.split('!')[1].split('@')[1];

  action.channel = params[2];

  params[3] = params[3].slice(2);

  action.cmd = params[3];
  action.params = params.slice(4);
  action.data   = data;

  return action;
};

irc.act = function(options, callback) {
  if (irc.debug) console.log(options);
  var string = options.action + ' ';
  if (typeof options.params !== 'undefined') {
    string += options.params.join(' ');
  }
  if (typeof options.longParam !== 'undefined') {
    string += ' :' + options.longParam;
  }
  if (irc.debug) console.log(string);
  irc._socket.write(string + '\r\n', callback);
};

irc.join = function (channel, callback) {
  irc.act({action: 'JOIN', params: [channel]}, callback);
}

irc.nick = function (nick, callback) {
  irc.act({action: 'NICK', params: [nick]}, callback);
};

irc.user = function (user, mode, realName, callback) {
  irc.act({action: 'USER', params: [user, mode, '*'],
          longParam: realName}, callback);
};

irc._socket = net.connect(irc.config.port, irc.config.address, function () {
  var nick      = irc.config.nick;
  var user      = irc.config.user;
  var realName  = irc.config.realName;
  var chan      = irc.config.chan;

  irc.nick(nick, function() {
    irc.user(user, '8', realName, function() {
      var has_admin = false;
      for (var u in irc.users) {
        if (irc.is_admin(u)) {
          has_admin = true;
        }
      }
      if (!has_admin) {
        throw ("An admin must be configured in users.json!");
      }

      if (chan instanceof Array) {
        for (var i = 0, l = chan.length; i < l; i += 1) {
          irc.join(chan[i]);
        }
      } else {
        irc.join(chan);
      }
    });
  });
});

irc._socket.on('data', function (data) {
  data = data.toString();

  if (irc.debug) {
    console.log(data);
  }

  var params = data.split(' ');
  if (data[0] === ':') {
    // Chop off initial colon, send to emitter.
    // also chop off \r\n
    irc.emitter.emit(params[1], data.slice(1, -2));
  } else {
    irc.emitter.emit(params[0], data);
  }
});

irc.emitter.on('PING', function (data) {
  irc._socket.write('PONG ' + data.slice(data.indexOf(':')) + '\r\n');
});

irc.emitter.on('PRIVMSG', function (data) {

  // Look for first character of the message.
  if (data[data.indexOf(':') + 1] === irc.command_char) {
    var action = irc.splitcmd(data);
    if (irc.debug) console.log(action);
    irc.emitter.emit(action.cmd, action);
  }
});

global.irc = irc;
irc.plugins = [];
fs.readdir(plugin_dir, function(err, files) {
  for (var i = 0, len = files.length; i < len; i += 1) {
    var plugin = require(plugin_dir + files[i]);
    plugin.enabled = true;
    irc.plugins.push(plugin);
    irc.emitter.on(plugin.name, plugin.handler);
  }
});

irc.emitter.on('disable', function(act) {
  if (irc.is_admin(act.nick) === true) {
    for (var p in irc.plugins) {
      if (irc.plugins[p].name === act.params[0]) {
        irc.plugins[p].enabled = false;
        irc.emitter.removeListener(irc.plugins[p].name, irc.plugins[p].handler);
        irc.privmsg(act.channel, act.params[0] + ' disabled');
      }
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: not authorized');
  }
});

irc.emitter.on('enable', function(act) {
  if (irc.is_admin(act.nick) === true) {
    for (var p in irc.plugins) {
      if (irc.plugins[p].name === act.params[0] &&
          irc.plugins[p].enabled === false) {
        irc.plugins[p].enabled = true;
        irc.emitter.on(irc.plugins[p].name, irc.plugins[p].handler);
        irc.privmsg(act.channel, act.params[0] + ' enabled');
      }
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: not authorized');
  }
});

irc.emitter.on('set_auth', function (act) {
  if (typeof user === 'undefined')
    irc.users[nick] = {};

  var user  = irc.users[nick];
  var nick  = act.params[0];
  var level = act.params[1];
  if (act.params.length < 2) {
    irc.privmsg(act.channel, 'ERROR: Insufficient parameters');
    return (1);
  }
  if (level !== 'user' && level !== 'owner' && level !== 'admin') {
    irc.privmsg(act.channel, 'ERROR: Invalid parameter: ' + level)
    return (1);
  }
  if (irc.is_owner(act.nick)) {
    if (nick === act.nick) {
      irc.privmsg(act.channel, 'ERROR: Cannot change your own permissions!');
    } else {
      user.auth = level;
      irc.privmsg(act.channel, nick + ' made to ' + level);
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: Insufficient privileges');
  }
});

irc.emitter.on('PRIVMSG', function(data) {
  var nick = data.slice(0,data.indexOf('!'));
  if (typeof irc.users[nick] === 'undefined') {
    irc.users[nick] = {};
  }
  irc.users[nick].seen_time = new Date().toUTCString();
  irc.users[nick].seen_msg  = data.slice(data.indexOf(':') + 1);
  irc.users[nick].seen_channel = data.split(' ')[2];
});

irc.emitter.on('seen', function(act) {
  var nick = act.params[0] ? act.params : act.nick;
  irc.privmsg(act.channel, nick + ' last seen: ' + irc.users[nick].seen_time +
              " saying '" + irc.users[nick].seen_msg + "' in " +
              irc.users[nick].seen_channel);
});
<commit_msg>jshint now passes.<commit_after>var fs        = require('fs');
var net       = require('net');
var events    = require('events');
//var path      = require('path');

var irc = {};

var config_path = (process.env.IRC_NODE_PATH ||
                   process.env.HOME + '/.ircnode');
var config_file = config_path + '/config';
var user_file   = config_path + '/users.json';
var plugin_dir  = config_path + '/plugins/';

var exists = fs.existsSync(config_path);
if (!exists) {
  fs.mkdirSync(config_path, '0755');
}
var exists = fs.existsSync(plugin_dir);
if (!exists) {
  fs.mkdirSync(plugin_dir, '0755');
}

var exists = fs.existsSync(config_file);
if (!exists) {
  console.log('Creating a new config file');
  fs.openSync(config_file, 'w+');
  fs.writeFileSync(config_file, fs.readFileSync('./config.sample'));
}
irc.config = JSON.parse(fs.readFileSync(config_file));

fs.exists(user_file, function (exists) {
  if (!exists) {
    console.log('Creating a new users.json file');
    fs.openSync(user_file, 'w+');
    fs.writeFileSync(user_file, fs.readFileSync('./users.json.sample'));
  }
  irc.users = JSON.parse(fs.readFileSync(user_file));
});

irc.command_char = '!';
irc.debug = true;
irc.emitter = new events.EventEmitter();

irc.is_admin = function (nick) {
  if (typeof irc.users[nick] === 'undefined')
    return false;

  return (irc.users[nick].auth === 'admin' || irc.users[nick].auth === 'owner');
};

irc.is_owner = function (nick) {
  if (typeof irc.users[nick] === 'undefined') {
    return false;
  }

  return (irc.users[nick].auth === 'owner');
};

irc.privmsg  = function (chan, msg) {
  irc._socket.write('PRIVMSG ' + chan + ' :' + msg + '\r\n');
};

irc.splitcmd = function (data) {
  var action = {};
  var params = data.split(' ');

  var nickuser = data.substring(0, data.indexOf(' '));
  action.nick = nickuser.split('!')[0];
  action.user = nickuser.split('!')[1].split('@')[0];
  action.host = nickuser.split('!')[1].split('@')[1];

  action.channel = params[2];

  params[3] = params[3].slice(2);

  action.cmd = params[3];
  action.params = params.slice(4);
  action.data   = data;

  return action;
};

irc.act = function (options, callback) {
  if (irc.debug) console.log(options);
  var string = options.action + ' ';
  if (typeof options.params !== 'undefined') {
    string += options.params.join(' ');
  }
  if (typeof options.longParam !== 'undefined') {
    string += ' :' + options.longParam;
  }
  if (irc.debug) console.log(string);
  irc._socket.write(string + '\r\n', callback);
};

irc.join = function (channel, callback) {
  irc.act({action: 'JOIN', params: [channel]}, callback);
};

irc.nick = function (nick, callback) {
  irc.act({action: 'NICK', params: [nick]}, callback);
};

irc.user = function (user, mode, realName, callback) {
  irc.act({action: 'USER', params: [user, mode, '*'],
          longParam: realName}, callback);
};

irc._socket = net.connect(irc.config.port, irc.config.address, function () {
  var nick      = irc.config.nick;
  var user      = irc.config.user;
  var realName  = irc.config.realName;
  var chan      = irc.config.chan;

  irc.nick(nick, function () {
    irc.user(user, '8', realName, function () {
      var has_admin = false;
      for (var u in irc.users) {
        if (irc.is_admin(u)) {
          has_admin = true;
        }
      }
      if (!has_admin) {
        throw ("An admin must be configured in users.json!");
      }

      if (chan instanceof Array) {
        for (var i = 0, l = chan.length; i < l; i += 1) {
          irc.join(chan[i]);
        }
      } else {
        irc.join(chan);
      }
    });
  });
});

irc._socket.on('data', function (data) {
  data = data.toString();

  if (irc.debug) {
    console.log(data);
  }

  var params = data.split(' ');
  if (data[0] === ':') {
    // Chop off initial colon, send to emitter.
    // also chop off \r\n
    irc.emitter.emit(params[1], data.slice(1, -2));
  } else {
    irc.emitter.emit(params[0], data);
  }
});

irc.emitter.on('PING', function (data) {
  irc._socket.write('PONG ' + data.slice(data.indexOf(':')) + '\r\n');
});

irc.emitter.on('PRIVMSG', function (data) {

  // Look for first character of the message.
  if (data[data.indexOf(':') + 1] === irc.command_char) {
    var action = irc.splitcmd(data);
    if (irc.debug) console.log(action);
    irc.emitter.emit(action.cmd, action);
  }
});

global.irc = irc;
irc.plugins = [];
fs.readdir(plugin_dir, function (err, files) {
  for (var i = 0, len = files.length; i < len; i += 1) {
    var plugin = require(plugin_dir + files[i]);
    plugin.enabled = true;
    irc.plugins.push(plugin);
    irc.emitter.on(plugin.name, plugin.handler);
  }
});

irc.emitter.on('disable', function (act) {
  if (irc.is_admin(act.nick) === true) {
    for (var p in irc.plugins) {
      if (irc.plugins[p].name === act.params[0]) {
        irc.plugins[p].enabled = false;
        irc.emitter.removeListener(irc.plugins[p].name, irc.plugins[p].handler);
        irc.privmsg(act.channel, act.params[0] + ' disabled');
      }
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: not authorized');
  }
});

irc.emitter.on('enable', function (act) {
  if (irc.is_admin(act.nick) === true) {
    for (var p in irc.plugins) {
      if (irc.plugins[p].name === act.params[0] &&
          irc.plugins[p].enabled === false) {
        irc.plugins[p].enabled = true;
        irc.emitter.on(irc.plugins[p].name, irc.plugins[p].handler);
        irc.privmsg(act.channel, act.params[0] + ' enabled');
      }
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: not authorized');
  }
});

irc.emitter.on('set_auth', function (act) {
  var nick  = act.params[0];
  var level = act.params[1];

  if (typeof irc.users[nick] === 'undefined')
    irc.users[nick] = {};

  var user  = irc.users[nick];

  if (act.params.length < 2) {
    irc.privmsg(act.channel, 'ERROR: Insufficient parameters');
    return (1);
  }
  if (level !== 'user' && level !== 'owner' && level !== 'admin') {
    irc.privmsg(act.channel, 'ERROR: Invalid parameter: ' + level);
    return (1);
  }
  if (irc.is_owner(act.nick)) {
    if (nick === act.nick) {
      irc.privmsg(act.channel, 'ERROR: Cannot change your own permissions!');
    } else {
      user.auth = level;
      irc.privmsg(act.channel, nick + ' made to ' + level);
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: Insufficient privileges');
  }
});

irc.emitter.on('PRIVMSG', function (data) {
  var nick = data.slice(0, data.indexOf('!'));
  if (typeof irc.users[nick] === 'undefined') {
    irc.users[nick] = {};
  }
  irc.users[nick].seen_time = new Date().toUTCString();
  irc.users[nick].seen_msg  = data.slice(data.indexOf(':') + 1);
  irc.users[nick].seen_channel = data.split(' ')[2];
});

irc.emitter.on('seen', function (act) {
  var nick = act.params[0] ? act.params : act.nick;
  irc.privmsg(act.channel, nick + ' last seen: ' + irc.users[nick].seen_time +
              " saying '" + irc.users[nick].seen_msg + "' in " +
              irc.users[nick].seen_channel);
});
<|endoftext|>


<commit_before>'use strict';
<commit_msg>Implement Zepto.<commit_after>'use strict';
window.$ = require('zepto-node');
<|endoftext|>


<commit_before>var fs        = require('fs');
var net       = require('net');
var events    = require('events');

var irc = {};

var config_path = (process.env.IRC_NODE_PATH ||
                   process.env.HOME + '/.ircnode');
var config_file = config_path + '/config';
var user_file   = config_path + '/users.json';
var plugin_dir  = config_path + '/plugins/';

irc.config = JSON.parse(fs.readFileSync(config_file));

fs.readFile(user_file, function(err, data) {
  if (err) {
    console.log("users.json file must exist!");
    throw err
  }
  irc.users = JSON.parse(data);
});

irc.command_char = '!';
irc.debug = process.env.IRC_NODE_DEBUG === 'true';
irc.emitter = new events.EventEmitter();

irc.is_admin = function(nick) {
  if (typeof irc.users[nick] === 'undefined')
    return false;

  return (irc.users[nick].auth === 'admin' || irc.users[nick].auth === 'owner');
}

irc.is_owner = function(nick) {
  if (typeof irc.users[nick] === 'undefined')
    return false;

  return (irc.users[nick].auth === 'owner');
};

irc.privmsg  = function (chan, msg) {
  irc._socket.write('PRIVMSG ' + chan + ' :' + msg + '\r\n');
};

irc.splitcmd = function (data) {
  var action = {};
  var params = data.split(' ');

  var nickuser = data.substring(0, data.indexOf(' '));
  action.nick = nickuser.split('!')[0];
  action.user = nickuser.split('!')[1].split('@')[0];
  action.host = nickuser.split('!')[1].split('@')[1];

  action.channel = params[2];

  params[3] = params[3].slice(2);

  action.cmd = params[3];
  action.params = params.slice(4);
  action.data   = data;

  return action;
};

irc.act = function(options, callback) {
  if (irc.debug) console.log(options);
  var string = options.action + ' ';
  if (typeof options.params !== 'undefined') {
    string += options.params.join(' ');
  }
  if (typeof options.longParam !== 'undefined') {
    string += ' :' + options.longParam;
  }
  if (irc.debug) console.log(string);
  irc._socket.write(string + '\r\n', callback);
};

irc.join = function (channel, callback) {
  irc.act({action: 'JOIN', params: [channel]}, callback);
}

irc.nick = function (nick, callback) {
  irc.act({action: 'NICK', params: [nick]}, callback);
};

irc.user = function (user, mode, realName, callback) {
  irc.act({action: 'USER', params: [user, mode, '*'],
          longParam: realName}, callback);
};

irc._socket = net.connect(irc.config.port, irc.config.address, function () {
  var nick      = irc.config.nick;
  var user      = irc.config.user;
  var realName  = irc.config.realName;
  var chan      = irc.config.chan;

  irc.nick(nick, function() {
    irc.user(user, '8', realName, function() {
      var has_admin = false;
      for (var u in irc.users) {
        if (irc.is_admin(u)) {
          has_admin = true;
        }
      }
      if (!has_admin) {
        throw ("An admin must be configured in users.json!");
      }

      if (chan instanceof Array) {
        for (var i = 0, l = chan.length; i < l; i += 1) {
          irc.join(chan[i]);
        }
      } else {
        irc.join(chan);
      }
    });
  });
});

irc._socket.on('data', function (data) {
  data = data.toString();

  if (irc.debug) {
    console.log(data);
  }

  var params = data.split(' ');
  if (data[0] === ':') {
    // Chop off initial colon, send to emitter.
    // also chop off \r\n
    irc.emitter.emit(params[1], data.slice(1, -2));
  } else {
    irc.emitter.emit(params[0], data);
  }
});

irc.emitter.on('PING', function (data) {
  irc._socket.write('PONG ' + data.slice(data.indexOf(':')) + '\r\n');
});

irc.emitter.on('PRIVMSG', function (data) {

  // Look for first character of the message.
  if (data[data.indexOf(':') + 1] === irc.command_char) {
    var action = irc.splitcmd(data);
    if (irc.debug) console.log(action);
    irc.emitter.emit(action.cmd, action);
  }
});

global.irc = irc;
irc.plugins = [];
fs.readdir(plugin_dir, function(err, files) {
  for (var i = 0, len = files.length; i < len; i += 1) {
    var plugin = require(plugin_dir + files[i]);
    plugin.enabled = true;
    irc.plugins.push(plugin);
    irc.emitter.on(plugin.name, plugin.handler);
  }
});

irc.emitter.on('disable', function(act) {
  if (irc.is_admin(act.nick) === true) {
    for (var p in irc.plugins) {
      if (irc.plugins[p].name === act.params[0]) {
        irc.plugins[p].enabled = false;
        irc.emitter.removeListener(irc.plugins[p].name, irc.plugins[p].handler);
        irc.privmsg(act.channel, act.params[0] + ' disabled');
      }
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: not authorized');
  }
});

irc.emitter.on('enable', function(act) {
  if (irc.is_admin(act.nick) === true) {
    for (var p in irc.plugins) {
      if (irc.plugins[p].name === act.params[0] &&
          irc.plugins[p].enabled === false) {
        irc.plugins[p].enabled = true;
        irc.emitter.on(irc.plugins[p].name, irc.plugins[p].handler);
        irc.privmsg(act.channel, act.params[0] + ' enabled');
      }
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: not authorized');
  }
});

irc.emitter.on('set_auth', function (act) {
  if (typeof user === 'undefined')
    irc.users[nick] = {};

  var user  = irc.users[nick];
  var nick  = act.params[0];
  var level = act.params[1];
  if (act.params.length < 2) {
    irc.privmsg(act.channel, 'ERROR: Insufficient parameters');
    return (1);
  }
  if (level !== 'user' && level !== 'owner' && level !== 'admin') {
    irc.privmsg(act.channel, 'ERROR: Invalid parameter: ' + level)
    return (1);
  }
  if (irc.is_owner(act.nick)) {
    if (nick === act.nick) {
      irc.privmsg(act.channel, 'ERROR: Cannot change your own permissions!');
    } else {
      user.auth = level;
      irc.privmsg(act.channel, nick + ' made to ' + level);
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: Insufficient privileges');
  }
});

irc.emitter.on('PRIVMSG', function(data) {
  var nick = data.slice(0,data.indexOf('!'));
  if (typeof irc.users[nick] === 'undefined') {
    irc.users[nick] = {};
  }
  irc.users[nick].seen_time = new Date().toUTCString();
  irc.users[nick].seen_msg  = data.slice(data.indexOf(':') + 1);
  irc.users[nick].seen_channel = data.split(' ')[2];
});

irc.emitter.on('seen', function(act) {
  var nick = act.params[0] ? act.params : act.nick;
  if (typeof irc.users[nick] === 'undefined' ||
      typeof irc.users[nick].seen_msg === 'undefined' ||
      typeof irc.users[nick].seen_time === 'undefined') {
    irc.privmsg(act.channel, 'Unknown nick: ' + nick);
    return (1);
  }
  irc.privmsg(act.channel, nick + ' last seen: ' + irc.users[nick].seen_time +
              " saying '" + irc.users[nick].seen_msg + "' in " +
              irc.users[nick].seen_channel);
});
<commit_msg>added semicolons for better code<commit_after>var fs        = require('fs');
var net       = require('net');
var events    = require('events');

var irc = {};

var config_path = (process.env.IRC_NODE_PATH ||
                   process.env.HOME + '/.ircnode');
var config_file = config_path + '/config';
var user_file   = config_path + '/users.json';
var plugin_dir  = config_path + '/plugins/';

irc.config = JSON.parse(fs.readFileSync(config_file));

fs.readFile(user_file, function(err, data) {
  if (err) {
    console.log("users.json file must exist!");
    throw err;
  }
  irc.users = JSON.parse(data);
});

irc.command_char = '!';
irc.debug = process.env.IRC_NODE_DEBUG === 'true';
irc.emitter = new events.EventEmitter();

irc.is_admin = function(nick) {
  if (typeof irc.users[nick] === 'undefined')
    return false;

  return (irc.users[nick].auth === 'admin' || irc.users[nick].auth === 'owner');
};

irc.is_owner = function(nick) {
  if (typeof irc.users[nick] === 'undefined')
    return false;

  return (irc.users[nick].auth === 'owner');
};

irc.privmsg  = function (chan, msg) {
  irc._socket.write('PRIVMSG ' + chan + ' :' + msg + '\r\n');
};

irc.splitcmd = function (data) {
  var action = {};
  var params = data.split(' ');

  var nickuser = data.substring(0, data.indexOf(' '));
  action.nick = nickuser.split('!')[0];
  action.user = nickuser.split('!')[1].split('@')[0];
  action.host = nickuser.split('!')[1].split('@')[1];

  action.channel = params[2];

  params[3] = params[3].slice(2);

  action.cmd = params[3];
  action.params = params.slice(4);
  action.data   = data;

  return action;
};

irc.act = function(options, callback) {
  if (irc.debug) console.log(options);
  var string = options.action + ' ';
  if (typeof options.params !== 'undefined') {
    string += options.params.join(' ');
  }
  if (typeof options.longParam !== 'undefined') {
    string += ' :' + options.longParam;
  }
  if (irc.debug) console.log(string);
  irc._socket.write(string + '\r\n', callback);
};

irc.join = function (channel, callback) {
  irc.act({action: 'JOIN', params: [channel]}, callback);
};

irc.nick = function (nick, callback) {
  irc.act({action: 'NICK', params: [nick]}, callback);
};

irc.user = function (user, mode, realName, callback) {
  irc.act({action: 'USER', params: [user, mode, '*'],
          longParam: realName}, callback);
};

irc._socket = net.connect(irc.config.port, irc.config.address, function () {
  var nick      = irc.config.nick;
  var user      = irc.config.user;
  var realName  = irc.config.realName;
  var chan      = irc.config.chan;

  irc.nick(nick, function() {
    irc.user(user, '8', realName, function() {
      var has_admin = false;
      for (var u in irc.users) {
        if (irc.is_admin(u)) {
          has_admin = true;
        }
      }
      if (!has_admin) {
        throw ("An admin must be configured in users.json!");
      }

      if (chan instanceof Array) {
        for (var i = 0, l = chan.length; i < l; i += 1) {
          irc.join(chan[i]);
        }
      } else {
        irc.join(chan);
      }
    });
  });
});

irc._socket.on('data', function (data) {
  data = data.toString();

  if (irc.debug) {
    console.log(data);
  }

  var params = data.split(' ');
  if (data[0] === ':') {
    // Chop off initial colon, send to emitter.
    // also chop off \r\n
    irc.emitter.emit(params[1], data.slice(1, -2));
  } else {
    irc.emitter.emit(params[0], data);
  }
});

irc.emitter.on('PING', function (data) {
  irc._socket.write('PONG ' + data.slice(data.indexOf(':')) + '\r\n');
});

irc.emitter.on('PRIVMSG', function (data) {

  // Look for first character of the message.
  if (data[data.indexOf(':') + 1] === irc.command_char) {
    var action = irc.splitcmd(data);
    if (irc.debug) console.log(action);
    irc.emitter.emit(action.cmd, action);
  }
});

global.irc = irc;
irc.plugins = [];
fs.readdir(plugin_dir, function(err, files) {
  for (var i = 0, len = files.length; i < len; i += 1) {
    var plugin = require(plugin_dir + files[i]);
    plugin.enabled = true;
    irc.plugins.push(plugin);
    irc.emitter.on(plugin.name, plugin.handler);
  }
});

irc.emitter.on('disable', function(act) {
  if (irc.is_admin(act.nick) === true) {
    for (var p in irc.plugins) {
      if (irc.plugins[p].name === act.params[0]) {
        irc.plugins[p].enabled = false;
        irc.emitter.removeListener(irc.plugins[p].name, irc.plugins[p].handler);
        irc.privmsg(act.channel, act.params[0] + ' disabled');
      }
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: not authorized');
  }
});

irc.emitter.on('enable', function(act) {
  if (irc.is_admin(act.nick) === true) {
    for (var p in irc.plugins) {
      if (irc.plugins[p].name === act.params[0] &&
          irc.plugins[p].enabled === false) {
        irc.plugins[p].enabled = true;
        irc.emitter.on(irc.plugins[p].name, irc.plugins[p].handler);
        irc.privmsg(act.channel, act.params[0] + ' enabled');
      }
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: not authorized');
  }
});

irc.emitter.on('set_auth', function (act) {
  if (typeof user === 'undefined')
    irc.users[nick] = {};

  var user  = irc.users[nick];
  var nick  = act.params[0];
  var level = act.params[1];
  if (act.params.length < 2) {
    irc.privmsg(act.channel, 'ERROR: Insufficient parameters');
    return (1);
  }
  if (level !== 'user' && level !== 'owner' && level !== 'admin') {
    irc.privmsg(act.channel, 'ERROR: Invalid parameter: ' + level);
    return (1);
  }
  if (irc.is_owner(act.nick)) {
    if (nick === act.nick) {
      irc.privmsg(act.channel, 'ERROR: Cannot change your own permissions!');
    } else {
      user.auth = level;
      irc.privmsg(act.channel, nick + ' made to ' + level);
    }
  } else {
    irc.privmsg(act.channel, 'ERROR: Insufficient privileges');
  }
});

irc.emitter.on('PRIVMSG', function(data) {
  var nick = data.slice(0,data.indexOf('!'));
  if (typeof irc.users[nick] === 'undefined') {
    irc.users[nick] = {};
  }
  irc.users[nick].seen_time = new Date().toUTCString();
  irc.users[nick].seen_msg  = data.slice(data.indexOf(':') + 1);
  irc.users[nick].seen_channel = data.split(' ')[2];
});

irc.emitter.on('seen', function(act) {
  var nick = act.params[0] ? act.params : act.nick;
  if (typeof irc.users[nick] === 'undefined' ||
      typeof irc.users[nick].seen_msg === 'undefined' ||
      typeof irc.users[nick].seen_time === 'undefined') {
    irc.privmsg(act.channel, 'Unknown nick: ' + nick);
    return (1);
  }
  irc.privmsg(act.channel, nick + ' last seen: ' + irc.users[nick].seen_time +
              " saying '" + irc.users[nick].seen_msg + "' in " +
              irc.users[nick].seen_channel);
});
<|endoftext|>


<commit_before>$(function(){
    var requestUrl = '/picselection/ajax',
        imgBox = null,
        cropHints = [];
    $("#submit").on('click',function(){
        /*count*/
        var images = [],
            pics = document.forms[0].pic,
            sum = 0,
            index = []

	// 筛选索引
        if(!(pics[0] == null || pics[0] == undefined)) {
            for (var i = 0;i < pics.length; ++i){
                if (pics[i].checked){
                    index.push(i);
                    sum++;
                }
            }
            // 获取数据
            var imgTemp;
            for(var i in index){
                var index_i = index[i];
                imgTemp = imgBox[index_i];
                if ((cropHints[index_i].bottom != 0) && (cropHints[index_i].right != 0)){
                    imgTemp.cropHint = cropHints[index_i];
                }
                images.push(JSON.stringify(imgTemp));
            }
        }else{
            if(pics.checked){
                imgBox[0].cropHint = cropHints[0];
                images.push(JSON.stringify(imgBox[0]));
                sum = 1;
            }
        }
        if (sum > 0){
            if(confirm("当前选中了" + sum + "张图片。是否确认提交？")){
                /*get poiId*/
                var poiId = $('.city').attr("data-id"),
                    postData = {
                        poiId: poiId,
                        images : images
                    };
                console.log(postData);
                /*post data*/
                $.ajax({
                    url : requestUrl,
                    type: "post",
                    data: postData,
                    dataType: "json",
                    traditional: true,
                    dataProcess: false,
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
                    success : function (msg) {
                        if (msg.code == 0){
                            alert('提交成功.');
                            $(this).attr('data-submit','true');
                        }
                        else{
                            alert('Failed to submit!');
                        }
                    },
                    error : function () {
                        alert('Error!!!');
                    }
                })
            }
        }else{
            alert('当前并未选中任何图片，请先选择符合合适的图片！');
        }
    })

    $("#next").on('click',function(){
        $('#J_search_text').val('');
        if ($('#submit').attr('data-submit') == "true"){
            $.ajax({
                url : requestUrl,
                type: "GET",
                data: {},
                success : function (data) {
                    console.log(data);

                    if (data.code == 0){
                        imgBox = data.images;
                        /*modify the DOM*/
                        $('form').remove();
                        $('.city').children('b').text(data.name);
                        $('.city').attr('data-id' , data.poiId);
                        $('.imgCnt').children('b').text(data.images.length);
                        $('.restCity').children('b').text(data.rest);
                        $('.doneCity').children('b').text(data.done);

                        /*add the DOM*/
                        $('.hd').after('<form></form>');
                        var imgBlock;
                        for(var i in imgBox){
                            imgBlock =
                                '
' +
                                    '' +
                                        '' +
                                    '' +
                                    '<input class="pic" name="pic" type="checkbox" value="' + i + '"/>' +
                                '
';
                            $('form').append(imgBlock);
                            cropHints[i] = {
                                "top": 0,
                                "left": 0,
                                "bottom": 0,
                                "right": 0
                            };
                        }

                        /*add the imgLayer*/
                        $('a.img').on('click', function(){
                            $('.sd_layer').css("display","block");
                            var index = $(this).attr("data-id");
                                img = '';
                            $('.img_layer .img_can').append(img);
                            $('.img_layer').css("display","block");
                            $('#ow').val(imgBox[index].w);
                            $('#oh').val(imgBox[index].h);

                            var selectFlag = false;//if cut ,the flag change to true
                            function showCoords(c){
                                selectFlag = true;
                                $('#x1').val(c.x);
                                $('#y1').val(c.y);
                                $('#x2').val(c.x2);
                                $('#y2').val(c.y2);
                                $('#w').val(c.w);
                                $('#h').val(c.h);
                                $('#cw').val(jcrop_api.getBounds()[0]);
                                $('#ch').val(jcrop_api.getBounds()[1]);
                            };

                            function clearCoords(){
                                $('#x1').val('');
                                $('#y1').val('');
                                $('#x2').val('');
                                $('#y2').val('');
                                $('#w').val('');
                                $('#h').val('');
                            };

                            $('#imageCrop').Jcrop({
                                onChange: showCoords,
                                onSelect: showCoords,
                                onRelease: clearCoords
                            },function(){
                                jcrop_api = this;
                            });

                            $('#coords').on('change','input',function(e){
                                var x1 = $('#x1').val(),
                                    x2 = $('#x2').val(),
                                    y1 = $('#y1').val(),
                                    y2 = $('#y2').val();
                                jcrop_api.setSelect([x1,y1,x2,y2]);
                            });

                            /*close sdLayer*/
                            $('.sd_layer').on('click', function(){
                                $(this).css("display","none");
                                $('.img_layer').css("display","none");
                                $('#coords input').val('');
                                $('.img_layer .img_can').empty();
                            });
                            $('#close').on('click',function(){
                                $('.sd_layer').trigger('click');
                            })

                            $('#imgSubmit').off('click');
                            $('#imgSubmit').on('click',function(){
                                if (!selectFlag){
                                    if(confirm("并未对该图进行裁剪,是否保持当前尺寸?")){
                                        var ow = $('#ow').val(),
                                            oh = $('#oh').val(),
                                            cropHint;
                                        ow = (ow % 2) ? (ow - 1) : ow;
                                        oh = (oh % 2) ? (oh - 1) : oh;
                                        cropHint = {
                                            "top": 0,
                                            "left": 0,
                                            "bottom": oh,
                                            "right": ow
                                        };
                                        cropHints[index] = cropHint;
                                        alert("裁剪成功!");
                                        $('.sd_layer').trigger('click');
                                    }else{

                                    }
                                }else{
                                    var x1 = $('#x1').val(),
                                        x2 = $('#x2').val(),
                                        y1 = $('#y1').val(),
                                        y2 = $('#y2').val(),
                                        cw = $('#cw').val(),
                                        ch = $('#ch').val(),
                                        ow = $('#ow').val(),
                                        oh = $('#oh').val(),
                                        left = x1 * ow / cw,
                                        top = y1 * oh / ch,
                                        right = x2 * ow / cw,
                                        bottom = y2 * oh / ch,
                                        cropHint= {};

                                    left = parseInt(left);
                                    left = (left % 2) ? (left + 1) : left;
                                    right = parseInt(right);
                                    right = (right % 2) ? (right - 1) : right;
                                    top = parseInt(top);
                                    top = (top % 2) ? (top + 1) : top;
                                    bottom = parseInt(bottom);
                                    bottom = (bottom % 2) ? (bottom - 1) : bottom;

                                    cropHint = {
                                        "top": top,
                                        "left": left,
                                        "bottom": bottom,
                                        "right": right
                                    };
                                    cropHints[index] = cropHint;
                                    alert("裁剪成功!");
                                    $('.sd_layer').trigger('click');
                                }
                            });
                        });
                    }else{
                        alert('Failed to get data!');
                    }
                },
                error : function () {
                    alert('Error!!!');
                }
            })
        }else{
            alert('请先提交改动!');
        }
    });

    // 查找
    $('#J_confirmSearch').click(function(){
        var search_text_row = $('#J_search_text').val(),
            search_text = $.trim(search_text_row),
            url = '/picselection/search';

        var lastInput = $(this).attr('data-last');
        if(search_text == ''){
            $(this).attr('data-last', '')
            alert("请输入城市或景点名字");
            return;
        }

        if(lastInput == search_text) {
            return;
        }else{
            $('#J_confirmSearch').attr('data-clicked', 'false');
        }

        var clickFlag = $(this).attr('data-clicked');
        if('false' == clickFlag){
            $('#J_confirmSearch').attr('data-clicked', 'true');
            $(this).attr('data-last', search_text)
            $.ajax({
                url : url,
                type: "GET",
                data: {search_text: search_text},
                success : function (data) {
                    console.log(data);

                    if (data.code == 0){
                        imgBox = null;
                        imgBox = data.images;
                        /*modify the DOM*/
                        $('form').remove();
                        $('.city').children('b').text(data.name);
                        $('.city').attr('data-id' , data.poiId);
                        $('.imgCnt').children('b').text(data.images.length);
                        $('.restCity').children('b').text(data.rest);
                        $('.doneCity').children('b').text(data.done);

                        /*add the DOM*/
                        $('.hd').after('<form></form>');
                        var imgBlock;
                        for(var i in imgBox){
                            imgBlock =
                                '
' +
                                    '' +
                                        '' +
                                    '' +
                                    '<input class="pic" name="pic" type="checkbox" value="' + i + '"/>' +
                                '
';
                            $('form').append(imgBlock);
                            cropHints[i] = {
                                "top": 0,
                                "left": 0,
                                "bottom": 0,
                                "right": 0
                            };
                        }

                        /*add the imgLayer*/
                        $('a.img').on('click', function(){
                            $('.sd_layer').css("display","block");
                            var index = $(this).attr("data-id");
                                img = '';
                            $('.img_layer .img_can').append(img);
                            $('.img_layer').css("display","block");
                            $('#ow').val(imgBox[index].w);
                            $('#oh').val(imgBox[index].h);

                            var selectFlag = false;//if cut ,the flag change to true
                            function showCoords(c){
                                selectFlag = true;
                                $('#x1').val(c.x);
                                $('#y1').val(c.y);
                                $('#x2').val(c.x2);
                                $('#y2').val(c.y2);
                                $('#w').val(c.w);
                                $('#h').val(c.h);
                                $('#cw').val(jcrop_api.getBounds()[0]);
                                $('#ch').val(jcrop_api.getBounds()[1]);
                            };

                            function clearCoords(){
                                $('#x1').val('');
                                $('#y1').val('');
                                $('#x2').val('');
                                $('#y2').val('');
                                $('#w').val('');
                                $('#h').val('');
                            };

                            $('#imageCrop').Jcrop({
                                onChange: showCoords,
                                onSelect: showCoords,
                                onRelease: clearCoords
                            },function(){
                                jcrop_api = this;
                            });

                            $('#coords').on('change','input',function(e){
                                var x1 = $('#x1').val(),
                                    x2 = $('#x2').val(),
                                    y1 = $('#y1').val(),
                                    y2 = $('#y2').val();
                                jcrop_api.setSelect([x1,y1,x2,y2]);
                            });

                            /*close sdLayer*/
                            $('.sd_layer').on('click', function(){
                                $(this).css("display","none");
                                $('.img_layer').css("display","none");
                                $('#coords input').val('');
                                $('.img_layer .img_can').empty();
                            });
                            $('#close').on('click',function(){
                                $('.sd_layer').trigger('click');
                            })

                            $('#imgSubmit').off('click');
                            $('#imgSubmit').on('click',function(){
                                if (!selectFlag){
                                    if(confirm("并未对该图进行裁剪,是否保持当前尺寸?")){
                                        var ow = $('#ow').val(),
                                            oh = $('#oh').val(),
                                            cropHint;
                                        ow = (ow % 2) ? (ow - 1) : ow;
                                        oh = (oh % 2) ? (oh - 1) : oh;
                                        cropHint = {
                                            "top": 0,
                                            "left": 0,
                                            "bottom": oh,
                                            "right": ow
                                        };
                                        cropHints[index] = cropHint;
                                        alert("裁剪成功!");
                                        $('.sd_layer').trigger('click');
                                    }else{

                                    }
                                }else{
                                    var x1 = $('#x1').val(),
                                        x2 = $('#x2').val(),
                                        y1 = $('#y1').val(),
                                        y2 = $('#y2').val(),
                                        cw = $('#cw').val(),
                                        ch = $('#ch').val(),
                                        ow = $('#ow').val(),
                                        oh = $('#oh').val(),
                                        left = x1 * ow / cw,
                                        top = y1 * oh / ch,
                                        right = x2 * ow / cw,
                                        bottom = y2 * oh / ch,
                                        cropHint= {};

                                    left = parseInt(left);
                                    left = (left % 2) ? (left + 1) : left;
                                    right = parseInt(right);
                                    right = (right % 2) ? (right - 1) : right;
                                    top = parseInt(top);
                                    top = (top % 2) ? (top + 1) : top;
                                    bottom = parseInt(bottom);
                                    bottom = (bottom % 2) ? (bottom - 1) : bottom;

                                    cropHint = {
                                        "top": top,
                                        "left": left,
                                        "bottom": bottom,
                                        "right": right
                                    };
                                    cropHints[index] = cropHint;
                                    alert("裁剪成功!");
                                    $('.sd_layer').trigger('click');
                                }
                            });
                        });

                    }else{
                        alert('数据查询失败，无相关景点或城市，请确认');
                    }
                },
                error : function () {
                    $('#J_confirmSearch').attr('data-clicked', 'false');
		    $('#J_confirmSearch').arrt('data-last', '');
                    alert('网络太卡 或者 代码罢工，赶紧呼叫程序猿');
                }
            })
        }
    })

    $(window).load(function(){
        $("#next").trigger('click');
        var wHeight = $(window).height(),
            wWidth = $(window).width(),
            imgBoxHeight = 634,
            imgBoxWidth = 1034,
            top = (wHeight - imgBoxHeight)/2,
            left = (wWidth - imgBoxWidth)/2;
        $('.img_layer').css('top' , top);
        $('.img_layer').css('left' , left);
    });
})
<commit_msg>little fix<commit_after>$(function(){
    var requestUrl = '/picselection/ajax',
        imgBox = null,
        cropHints = [];
    $("#submit").on('click',function(){
        /*count*/
        var images = [],
            pics = document.forms[0].pic,
            sum = 0,
            index = []

	// 筛选索引
        if(!(pics[0] == null || pics[0] == undefined)) {
            for (var i = 0;i < pics.length; ++i){
                if (pics[i].checked){
                    index.push(i);
                    sum++;
                }
            }
            // 获取数据
            var imgTemp;
            for(var i in index){
                var index_i = index[i];
                imgTemp = imgBox[index_i];
                if ((cropHints[index_i].bottom != 0) && (cropHints[index_i].right != 0)){
                    imgTemp.cropHint = cropHints[index_i];
                }
                images.push(JSON.stringify(imgTemp));
            }
        }else{
            if(pics.checked){
                imgBox[0].cropHint = cropHints[0];
                images.push(JSON.stringify(imgBox[0]));
                sum = 1;
            }
        }
        if (sum > 0){
            if(confirm("当前选中了" + sum + "张图片。是否确认提交？")){
                /*get poiId*/
                var poiId = $('.city').attr("data-id"),
                    postData = {
                        poiId: poiId,
                        images : images
                    };
                console.log(postData);
                /*post data*/
                $.ajax({
                    url : requestUrl,
                    type: "post",
                    data: postData,
                    dataType: "json",
                    traditional: true,
                    dataProcess: false,
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
                    success : function (msg) {
                        if (msg.code == 0){
                            alert('提交成功.');
                            $(this).attr('data-submit','true');
                        }
                        else{
                            alert('Failed to submit!');
                        }
                    },
                    error : function () {
                        alert('Error!!!');
                    }
                })
            }
        }else{
            alert('当前并未选中任何图片，请先选择符合合适的图片！');
        }
    })

    $("#next").on('click',function(){
        $('#J_search_text').val('');
        if ($('#submit').attr('data-submit') == "true"){
            $.ajax({
                url : requestUrl,
                type: "GET",
                data: {},
                success : function (data) {
                    console.log(data);

                    if (data.code == 0){
                        imgBox = data.images;
                        /*modify the DOM*/
                        $('form').remove();
                        $('.city').children('b').text(data.name);
                        $('.city').attr('data-id' , data.poiId);
                        $('.imgCnt').children('b').text(data.images.length);
                        $('.restCity').children('b').text(data.rest);
                        $('.doneCity').children('b').text(data.done);

                        /*add the DOM*/
                        $('.hd').after('<form></form>');
                        var imgBlock;
                        for(var i in imgBox){
                            imgBlock =
                                '
' +
                                    '' +
                                        '' +
                                    '' +
                                    '<input class="pic" name="pic" type="checkbox" value="' + i + '"/>' +
                                '
';
                            $('form').append(imgBlock);
                            cropHints[i] = {
                                "top": 0,
                                "left": 0,
                                "bottom": 0,
                                "right": 0
                            };
                        }

                        /*add the imgLayer*/
                        $('a.img').on('click', function(){
                            $('.sd_layer').css("display","block");
                            var index = $(this).attr("data-id");
                                img = '';
                            $('.img_layer .img_can').append(img);
                            $('.img_layer').css("display","block");
                            $('#ow').val(imgBox[index].w);
                            $('#oh').val(imgBox[index].h);

                            var selectFlag = false;//if cut ,the flag change to true
                            function showCoords(c){
                                selectFlag = true;
                                $('#x1').val(c.x);
                                $('#y1').val(c.y);
                                $('#x2').val(c.x2);
                                $('#y2').val(c.y2);
                                $('#w').val(c.w);
                                $('#h').val(c.h);
                                $('#cw').val(jcrop_api.getBounds()[0]);
                                $('#ch').val(jcrop_api.getBounds()[1]);
                            };

                            function clearCoords(){
                                $('#x1').val('');
                                $('#y1').val('');
                                $('#x2').val('');
                                $('#y2').val('');
                                $('#w').val('');
                                $('#h').val('');
                            };

                            $('#imageCrop').Jcrop({
                                onChange: showCoords,
                                onSelect: showCoords,
                                onRelease: clearCoords
                            },function(){
                                jcrop_api = this;
                            });

                            $('#coords').on('change','input',function(e){
                                var x1 = $('#x1').val(),
                                    x2 = $('#x2').val(),
                                    y1 = $('#y1').val(),
                                    y2 = $('#y2').val();
                                jcrop_api.setSelect([x1,y1,x2,y2]);
                            });

                            /*close sdLayer*/
                            $('.sd_layer').on('click', function(){
                                $(this).css("display","none");
                                $('.img_layer').css("display","none");
                                $('#coords input').val('');
                                $('.img_layer .img_can').empty();
                            });
                            $('#close').on('click',function(){
                                $('.sd_layer').trigger('click');
                            })

                            $('#imgSubmit').off('click');
                            $('#imgSubmit').on('click',function(){
                                if (!selectFlag){
                                    if(confirm("并未对该图进行裁剪,是否保持当前尺寸?")){
                                        var ow = $('#ow').val(),
                                            oh = $('#oh').val(),
                                            cropHint;
                                        ow = (ow % 2) ? (ow - 1) : ow;
                                        oh = (oh % 2) ? (oh - 1) : oh;
                                        cropHint = {
                                            "top": 0,
                                            "left": 0,
                                            "bottom": oh,
                                            "right": ow
                                        };
                                        cropHints[index] = cropHint;
                                        alert("裁剪成功!");
                                        $('.sd_layer').trigger('click');
                                    }else{

                                    }
                                }else{
                                    var x1 = $('#x1').val(),
                                        x2 = $('#x2').val(),
                                        y1 = $('#y1').val(),
                                        y2 = $('#y2').val(),
                                        cw = $('#cw').val(),
                                        ch = $('#ch').val(),
                                        ow = $('#ow').val(),
                                        oh = $('#oh').val(),
                                        left = x1 * ow / cw,
                                        top = y1 * oh / ch,
                                        right = x2 * ow / cw,
                                        bottom = y2 * oh / ch,
                                        cropHint= {};

                                    left = parseInt(left);
                                    left = (left % 2) ? (left + 1) : left;
                                    right = parseInt(right);
                                    right = (right % 2) ? (right - 1) : right;
                                    top = parseInt(top);
                                    top = (top % 2) ? (top + 1) : top;
                                    bottom = parseInt(bottom);
                                    bottom = (bottom % 2) ? (bottom - 1) : bottom;

                                    cropHint = {
                                        "top": top,
                                        "left": left,
                                        "bottom": bottom,
                                        "right": right
                                    };
                                    cropHints[index] = cropHint;
                                    alert("裁剪成功!");
                                    $('.sd_layer').trigger('click');
                                }
                            });
                        });
                    }else{
                        alert('Failed to get data!');
                    }
                },
                error : function () {
                    alert('Error!!!');
                }
            })
        }else{
            alert('请先提交改动!');
        }
    });

    // 查找
    $('#J_confirmSearch').click(function(){
        var search_text_row = $('#J_search_text').val(),
            search_text = $.trim(search_text_row),
            url = '/picselection/search';

        var lastInput = $(this).attr('data-last');
        if(search_text == ''){
            $(this).attr('data-last', '')
            alert("请输入城市或景点名字");
            return;
        }

        if(lastInput == search_text) {
            return;
        }else{
            $('#J_confirmSearch').attr('data-clicked', 'false');
        }

        var clickFlag = $(this).attr('data-clicked');
        if('false' == clickFlag){
            $('#J_confirmSearch').attr('data-clicked', 'true');
            $(this).attr('data-last', search_text)
            $.ajax({
                url : url,
                type: "GET",
                data: {search_text: search_text},
                success : function (data) {
                    console.log(data);

                    if (data.code == 0){
                        imgBox = null;
                        imgBox = data.images;
                        /*modify the DOM*/
                        $('form').remove();
                        $('.city').children('b').text(data.name);
                        $('.city').attr('data-id' , data.poiId);
                        $('.imgCnt').children('b').text(data.images.length);
                        $('.restCity').children('b').text(data.rest);
                        $('.doneCity').children('b').text(data.done);

                        /*add the DOM*/
                        $('.hd').after('<form></form>');
                        var imgBlock;
                        for(var i in imgBox){
                            imgBlock =
                                '
' +
                                    '' +
                                        '' +
                                    '' +
                                    '<input class="pic" name="pic" type="checkbox" value="' + i + '"/>' +
                                '
';
                            $('form').append(imgBlock);
                            cropHints[i] = {
                                "top": 0,
                                "left": 0,
                                "bottom": 0,
                                "right": 0
                            };
                        }

                        /*add the imgLayer*/
                        $('a.img').on('click', function(){
                            $('.sd_layer').css("display","block");
                            var index = $(this).attr("data-id");
                                img = '';
                            $('.img_layer .img_can').append(img);
                            $('.img_layer').css("display","block");
                            $('#ow').val(imgBox[index].w);
                            $('#oh').val(imgBox[index].h);

                            var selectFlag = false;//if cut ,the flag change to true
                            function showCoords(c){
                                selectFlag = true;
                                $('#x1').val(c.x);
                                $('#y1').val(c.y);
                                $('#x2').val(c.x2);
                                $('#y2').val(c.y2);
                                $('#w').val(c.w);
                                $('#h').val(c.h);
                                $('#cw').val(jcrop_api.getBounds()[0]);
                                $('#ch').val(jcrop_api.getBounds()[1]);
                            };

                            function clearCoords(){
                                $('#x1').val('');
                                $('#y1').val('');
                                $('#x2').val('');
                                $('#y2').val('');
                                $('#w').val('');
                                $('#h').val('');
                            };

                            $('#imageCrop').Jcrop({
                                onChange: showCoords,
                                onSelect: showCoords,
                                onRelease: clearCoords
                            },function(){
                                jcrop_api = this;
                            });

                            $('#coords').on('change','input',function(e){
                                var x1 = $('#x1').val(),
                                    x2 = $('#x2').val(),
                                    y1 = $('#y1').val(),
                                    y2 = $('#y2').val();
                                jcrop_api.setSelect([x1,y1,x2,y2]);
                            });

                            /*close sdLayer*/
                            $('.sd_layer').on('click', function(){
                                $(this).css("display","none");
                                $('.img_layer').css("display","none");
                                $('#coords input').val('');
                                $('.img_layer .img_can').empty();
                            });
                            $('#close').on('click',function(){
                                $('.sd_layer').trigger('click');
                            })

                            $('#imgSubmit').off('click');
                            $('#imgSubmit').on('click',function(){
                                if (!selectFlag){
                                    if(confirm("并未对该图进行裁剪,是否保持当前尺寸?")){
                                        var ow = $('#ow').val(),
                                            oh = $('#oh').val(),
                                            cropHint;
                                        ow = (ow % 2) ? (ow - 1) : ow;
                                        oh = (oh % 2) ? (oh - 1) : oh;
                                        cropHint = {
                                            "top": 0,
                                            "left": 0,
                                            "bottom": oh,
                                            "right": ow
                                        };
                                        cropHints[index] = cropHint;
                                        alert("裁剪成功!");
                                        $('.sd_layer').trigger('click');
                                    }else{

                                    }
                                }else{
                                    var x1 = $('#x1').val(),
                                        x2 = $('#x2').val(),
                                        y1 = $('#y1').val(),
                                        y2 = $('#y2').val(),
                                        cw = $('#cw').val(),
                                        ch = $('#ch').val(),
                                        ow = $('#ow').val(),
                                        oh = $('#oh').val(),
                                        left = x1 * ow / cw,
                                        top = y1 * oh / ch,
                                        right = x2 * ow / cw,
                                        bottom = y2 * oh / ch,
                                        cropHint= {};

                                    left = parseInt(left);
                                    left = (left % 2) ? (left + 1) : left;
                                    right = parseInt(right);
                                    right = (right % 2) ? (right - 1) : right;
                                    top = parseInt(top);
                                    top = (top % 2) ? (top + 1) : top;
                                    bottom = parseInt(bottom);
                                    bottom = (bottom % 2) ? (bottom - 1) : bottom;

                                    cropHint = {
                                        "top": top,
                                        "left": left,
                                        "bottom": bottom,
                                        "right": right
                                    };
                                    cropHints[index] = cropHint;
                                    alert("裁剪成功!");
                                    $('.sd_layer').trigger('click');
                                }
                            });
                        });

                    }else{
                        alert('数据查询失败，无相关景点或城市，请确认');
                    }
                },
                error : function () {
                    $('#J_confirmSearch').attr('data-clicked', 'false');
		    $('#J_confirmSearch').arrt('data-last', '');
                    alert('网络太卡 或者 代码罢工，赶紧呼叫程序猿');
                }
            })
        }
    })

    $(window).load(function(){
        $("#next").trigger('click');
        var wHeight = $(window).height(),
            wWidth = $(window).width(),
            imgBoxHeight = 634,
            imgBoxWidth = 1034,
            top = (wHeight - imgBoxHeight)/2,
            left = (wWidth - imgBoxWidth)/2;
        $('.img_layer').css('top' , top);
        $('.img_layer').css('left' , left);
    });
})
<|endoftext|>


<commit_before>var legend = document.getElementById('legend');
var lastUpdated;
var chart;
var table;

function init() {
  chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
  table = new google.visualization.DataTable();
  table.addColumn('number', 'Lat');
  table.addColumn('number', 'Lng');
  table.addColumn('number', 'Pageviews');
  table.addColumn('number', 'Commitments');
  refreshData();
}

// Displays the points data provided.
function displayPoints(data) {

  return new Promise(function(resolve, reject) {
    for (var i = 0; i < data.length; i++) {
      table.addRow([data[i].Coordinates[0], data[i].Coordinates[1], data[i].Action === 'view' ? 1 : 0, data[i].Action === 'commitment' ? 1 : 0]);
      var options = {
        sizeAxis: {
          minValue: 0,
          maxValue: 100
        },
        region: '021',
        displayMode: 'markers',
        colorAxis: {
          colors: ['#e7711c', '#4374e0']
        } // orange to blue
      };

      chart.draw(table, options);
    }

    resolve('All points processed');
  });
}

// https://developers.google.com/web/fundamentals/getting-started/primers/promises
function get(url) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();

    var lastUpdatedString = '';
    if (lastUpdated != null) {
      lastUpdatedString = '?lastupdated=' + lastUpdated;
    }

    lastUpdated = new Date() / 1000;

    req.open('GET', url + lastUpdatedString);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function callPromise() {
  return new Promise(function(resolve, reject) {

    get('/rest/live/read').then(JSON.parse).then(displayPoints).then(function() {
      console.log("callPromise Success!");
      resolve('Success!');
    }, function(error) {
      console.error("callPromise Failed!", error);
      reject(Error(error));
    });
  });
}

// https://gist.github.com/KartikTalwar/2306741
function refreshData() {
  x = 3; // 3 Seconds

  callPromise().then(function() {
    setTimeout(refreshData, x * 1000);
  }, function(error) {
    console.error(error);
    setTimeout(refreshData, x * 1000);
  });
}
<commit_msg>Display the whole world<commit_after>var legend = document.getElementById('legend');
var lastUpdated;
var chart;
var table;

function init() {
  chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
  table = new google.visualization.DataTable();
  table.addColumn('number', 'Lat');
  table.addColumn('number', 'Lng');
  table.addColumn('number', 'Pageviews');
  table.addColumn('number', 'Commitments');
  refreshData();
}

// Displays the points data provided.
function displayPoints(data) {

  return new Promise(function(resolve, reject) {
    for (var i = 0; i < data.length; i++) {
      table.addRow([data[i].Coordinates[0], data[i].Coordinates[1], data[i].Action === 'view' ? 1 : 0, data[i].Action === 'commitment' ? 1 : 0]);
      var options = {
        sizeAxis: {
          minValue: 0,
          maxValue: 100
        },
        region: 'world',
        displayMode: 'markers',
        colorAxis: {
          colors: ['#e7711c', '#4374e0']
        } // orange to blue
      };

      chart.draw(table, options);
    }

    resolve('All points processed');
  });
}

// https://developers.google.com/web/fundamentals/getting-started/primers/promises
function get(url) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();

    var lastUpdatedString = '';
    if (lastUpdated != null) {
      lastUpdatedString = '?lastupdated=' + lastUpdated;
    }

    lastUpdated = new Date() / 1000;

    req.open('GET', url + lastUpdatedString);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function callPromise() {
  return new Promise(function(resolve, reject) {

    get('/rest/live/read').then(JSON.parse).then(displayPoints).then(function() {
      console.log("callPromise Success!");
      resolve('Success!');
    }, function(error) {
      console.error("callPromise Failed!", error);
      reject(Error(error));
    });
  });
}

// https://gist.github.com/KartikTalwar/2306741
function refreshData() {
  x = 3; // 3 Seconds

  callPromise().then(function() {
    setTimeout(refreshData, x * 1000);
  }, function(error) {
    console.error(error);
    setTimeout(refreshData, x * 1000);
  });
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 NetBlocks Project <https://netblocks.org>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

global.Promise = require('bluebird');
const WhoisIP = require('./check');
const prettyjson = require('prettyjson');
const argv = require('yargs')
  .command('whois-rdap', 'RDAP IP WHOIS client')
  .usage('Usage: $0 [options] [ip ...]')
  .example('$0 8.8.8.8', 'query the specified IPv4/IPv6 address')
  .demandCommand(1)
  .boolean('verbose')
  .alias('v', 'verbose')
  .describe('v', 'enable verbose debug output')
  .boolean('pretty')
  .alias('p', 'pretty')
  //.default('p', process.stdout.isTTY)
  .describe('p', 'pretty-print RDAP output')
  .help('h')
  .alias('h', 'help')
  .epilog('The NetBlocks Project <https://netblocks.org>')
  .argv;

const VERBOSE = argv.verbose;
const ips = argv._;

var whois = new WhoisIP();
// TODO: Pass verbose flag down to the backend

whois.connect().then(() => {
  return whois.check(ips[0]).then((res) => {
    if (argv.pretty) {
      console.log(prettyjson.render(res.rdap));
    } else  {
      console.log(JSON.stringify(res.rdap, null, '  '));
    }
    if (VERBOSE)
      console.error(res.object_id);
  });
}).finally(() => {
  if (whois.client)
    return whois.client.close();
});
<commit_msg>Add --force feature to CLI<commit_after>// Copyright (c) 2017 NetBlocks Project <https://netblocks.org>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

global.Promise = require('bluebird');
const WhoisIP = require('./check');
const prettyjson = require('prettyjson');
const argv = require('yargs')
  .command('whois-rdap', 'RDAP IP WHOIS client')
  .usage('Usage: $0 [options] [ip ...]')
  .example('$0 8.8.8.8', 'query the specified IPv4/IPv6 address')
  .demandCommand(1)
  .boolean('force')
  .alias('f', 'force')
  .boolean('verbose')
  .alias('v', 'verbose')
  .describe('v', 'enable verbose debug output')
  .boolean('pretty')
  .alias('p', 'pretty')
  //.default('p', process.stdout.isTTY)
  .describe('p', 'pretty-print RDAP output')
  .help('h')
  .alias('h', 'help')
  .epilog('The NetBlocks Project <https://netblocks.org>')
  .argv;

const VERBOSE = argv.verbose;
const ips = argv._;

var whois = new WhoisIP();
// TODO: Pass verbose flag down to the backend

whois.connect().then(() => {
  if (argv.force)
    whois.ttl_secs = 0;
  return whois.check(ips[0]).then((res) => {
    if (argv.pretty) {
      console.log(prettyjson.render(res.rdap));
    } else  {
      console.log(JSON.stringify(res.rdap, null, '  '));
    }
    if (VERBOSE)
      console.error(res.object_id);
  });
}).finally(() => {
  if (whois.client)
    return whois.client.close();
});
<|endoftext|>