<commit_before>
/**
 * Module dependencies.
 */

var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');

/**
 * Module exports.
 */

module.exports = Adapter;

/**
 * Memory adapter constructor.
 *
 * @param {Namespace} nsp
 * @api public
 */

function Adapter(nsp){
  this.nsp = nsp;
  this.rooms = {};
  this.sids = {};
  this.encoder = new parser.Encoder();
}

/**
 * Inherits from `EventEmitter`.
 */

Adapter.prototype.__proto__ = Emitter.prototype;

/**
 * Adds a socket from a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.add = function(id, room, fn){
  this.sids[id] = this.sids[id] || {};
  this.sids[id][room] = true;
  this.rooms[room] = this.rooms[room] || {};
  this.rooms[room][id] = true;
  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.del = function(id, room, fn){
  this.sids[id] = this.sids[id] || {};
  this.rooms[room] = this.rooms[room] || {};
  delete this.sids[id][room];
  delete this.rooms[room][id];
  if(this.rooms[room].length == 0){
    delete this.rooms[room];
  }
  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from all rooms it's joined.
 *
 * @param {String} socket id
 * @api public
 */

Adapter.prototype.delAll = function(id, fn){
  var rooms = this.sids[id];
  if (rooms) {
    for (var room in rooms) {
      if (rooms.hasOwnProperty(room)) {
        delete this.rooms[room][id];
      }

      if(this.rooms[room].length == 0){
        delete this.rooms[room];
      }
    }
  }
  delete this.sids[id];
};

/**
 * Broadcasts a packet.
 *
 * Options:
 *  - `flags` {Object} flags for this packet
 *  - `except` {Array} sids that should be excluded
 *  - `rooms` {Array} list of rooms to broadcast to
 *
 * @param {Object} packet object
 * @api public
 */

Adapter.prototype.broadcast = function(packet, opts){
  var rooms = opts.rooms || [];
  var except = opts.except || [];
  var flags = opts.flags || {};
  var ids = {};
  var self = this;
  var socket;

  packet.nsp = this.nsp.name;
  this.encoder.encode(packet, function(encodedPackets) {
    if (rooms.length) {
      for (var i = 0; i < rooms.length; i++) {
        var room = self.rooms[rooms[i]];
        if (!room) continue;
        for (var id in room) {
          if (room.hasOwnProperty(id)) {
            if (ids[id] || ~except.indexOf(id)) continue;
            socket = self.nsp.connected[id];
            if (socket) {
              socket.packet(encodedPackets, true, flags.volatile);
              ids[id] = true;
            }
          }
        }
      }
    } else {
      for (var id in self.sids) {
        if (self.sids.hasOwnProperty(id)) {
          if (~except.indexOf(id)) continue;
          socket = self.nsp.connected[id];
          if (socket) socket.packet(encodedPackets, true, flags.volatile);
        }
      }
    }
  });
};
<commit_msg>Style<commit_after>
/**
 * Module dependencies.
 */

var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');

/**
 * Module exports.
 */

module.exports = Adapter;

/**
 * Memory adapter constructor.
 *
 * @param {Namespace} nsp
 * @api public
 */

function Adapter(nsp){
  this.nsp = nsp;
  this.rooms = {};
  this.sids = {};
  this.encoder = new parser.Encoder();
}

/**
 * Inherits from `EventEmitter`.
 */

Adapter.prototype.__proto__ = Emitter.prototype;

/**
 * Adds a socket from a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.add = function(id, room, fn){
  this.sids[id] = this.sids[id] || {};
  this.sids[id][room] = true;
  this.rooms[room] = this.rooms[room] || {};
  this.rooms[room][id] = true;
  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.del = function(id, room, fn){
  this.sids[id] = this.sids[id] || {};
  this.rooms[room] = this.rooms[room] || {};
  delete this.sids[id][room];
  delete this.rooms[room][id];
  if (!this.rooms[room].length) {
    delete this.rooms[room];
  }

  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from all rooms it's joined.
 *
 * @param {String} socket id
 * @api public
 */

Adapter.prototype.delAll = function(id, fn){
  var rooms = this.sids[id];
  if (rooms) {
    for (var room in rooms) {
      if (rooms.hasOwnProperty(room)) {
        delete this.rooms[room][id];
      }

      if (!this.rooms[room].length) {
        delete this.rooms[room];
      }
    }
  }
  delete this.sids[id];
};

/**
 * Broadcasts a packet.
 *
 * Options:
 *  - `flags` {Object} flags for this packet
 *  - `except` {Array} sids that should be excluded
 *  - `rooms` {Array} list of rooms to broadcast to
 *
 * @param {Object} packet object
 * @api public
 */

Adapter.prototype.broadcast = function(packet, opts){
  var rooms = opts.rooms || [];
  var except = opts.except || [];
  var flags = opts.flags || {};
  var ids = {};
  var self = this;
  var socket;

  packet.nsp = this.nsp.name;
  this.encoder.encode(packet, function(encodedPackets) {
    if (rooms.length) {
      for (var i = 0; i < rooms.length; i++) {
        var room = self.rooms[rooms[i]];
        if (!room) continue;
        for (var id in room) {
          if (room.hasOwnProperty(id)) {
            if (ids[id] || ~except.indexOf(id)) continue;
            socket = self.nsp.connected[id];
            if (socket) {
              socket.packet(encodedPackets, true, flags.volatile);
              ids[id] = true;
            }
          }
        }
      }
    } else {
      for (var id in self.sids) {
        if (self.sids.hasOwnProperty(id)) {
          if (~except.indexOf(id)) continue;
          socket = self.nsp.connected[id];
          if (socket) socket.packet(encodedPackets, true, flags.volatile);
        }
      }
    }
  });
};
<|endoftext|>


<commit_before>/**
 * Created by Samuel on 6/4/2016.
 * Simple wrapper functions to produce shorter UUIDs for cookies, maybe everything?
 */

var anyBase = require('any-base');
var uuid = require('node-uuid');

var flickrBase58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
var cookieBase90 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+-./:<=>?@[]^_`{|}~";

/**
 * Takes a UUID, strips the dashes, and translates.
 * @param {string} longId
 * @param {function(string)} translator
 * @returns {string}
 */
function shortenUUID (longId, translator) {
    return translator(longId.replace(/-/g,''));
}

/**
 * Translate back to hex and turn back into UUID format, with dashes
 * @param {string} shortId
 * @param {function(string)} translator
 * @returns {string}
 */
function enlargeUUID(shortId, translator) {
    var uu1 = translator(shortId);
    var leftPad = "";
    var m;

    // Pad out UUIDs beginning with zeros (any number shorter than 32 characters of hex)
    for (var i = 0, len = 32-uu1.length; i < len; ++i) {
        leftPad += "0";
    }

    // Join the zero padding and the UUID and then slice it up with match
    m = (leftPad + uu1).match(/(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/);

    // Accumulate the matches and join them.
    return [m[1], m[2], m[3], m[4], m[5]].join('-');
}

/**
 * @constructor
 * @param {string?} toAlphabet - Defaults to flickrBase58 if not provided
 * @returns {{new: (function()),
 *  uuid: (function()),
 *  fromUUID: (function(string)),
 *  toUUID: (function(string)),
 *  alphabet: (string)}}
 */
function MakeConvertor(toAlphabet) {

    var fromHex = anyBase(anyBase.HEX, toAlphabet);
    var toHex = anyBase(toAlphabet, anyBase.HEX);

    return {
        fromUUID: function(uuid) { return shortenUUID(uuid, fromHex); },
        toUUID: function(shortUuid) { return enlargeUUID(shortUuid, toHex); },
    };
}

module.exports = {
    new: MakeConvertor,
    b58: MakeConvertor(flickrBase58),
    constants: {
        flickrBase58: flickrBase58,
        cookieBase90: cookieBase90
    }
};
<commit_msg>Add default alphabet<commit_after>/**
 * Created by Samuel on 6/4/2016.
 * Simple wrapper functions to produce shorter UUIDs for cookies, maybe everything?
 */

var anyBase = require('any-base');
var uuid = require('node-uuid');

var flickrBase58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
var cookieBase90 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+-./:<=>?@[]^_`{|}~";

/**
 * Takes a UUID, strips the dashes, and translates.
 * @param {string} longId
 * @param {function(string)} translator
 * @returns {string}
 */
function shortenUUID (longId, translator) {
    return translator(longId.replace(/-/g,''));
}

/**
 * Translate back to hex and turn back into UUID format, with dashes
 * @param {string} shortId
 * @param {function(string)} translator
 * @returns {string}
 */
function enlargeUUID(shortId, translator) {
    var uu1 = translator(shortId);
    var leftPad = "";
    var m;

    // Pad out UUIDs beginning with zeros (any number shorter than 32 characters of hex)
    for (var i = 0, len = 32-uu1.length; i < len; ++i) {
        leftPad += "0";
    }

    // Join the zero padding and the UUID and then slice it up with match
    m = (leftPad + uu1).match(/(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/);

    // Accumulate the matches and join them.
    return [m[1], m[2], m[3], m[4], m[5]].join('-');
}

/**
 * @constructor
 * @param {string?} toAlphabet - Defaults to flickrBase58 if not provided
 * @returns {{new: (function()),
 *  uuid: (function()),
 *  fromUUID: (function(string)),
 *  toUUID: (function(string)),
 *  alphabet: (string)}}
 */
function MakeConvertor(toAlphabet) {

    // Default to Flickr 58
    var useAlphabet = toAlphabet || flickrBase58;

    // UUIDs are in hex, so we translate to and from.
    var fromHex = anyBase(anyBase.HEX, useAlphabet);
    var toHex = anyBase(useAlphabet, anyBase.HEX);

    return {
        fromUUID: function(uuid) { return shortenUUID(uuid, fromHex); },
        toUUID: function(shortUuid) { return enlargeUUID(shortUuid, toHex); },
    };
}

module.exports = {
    new: MakeConvertor,
    b58: MakeConvertor(flickrBase58),
    constants: {
        flickrBase58: flickrBase58,
        cookieBase90: cookieBase90
    }
};
<|endoftext|>


<commit_before>exports.nodeBefore = function(node) {
  if (~['ExpressionStatement', 'VariableDeclaration', 'ReturnStatement'].indexOf(node.type)) {
    var end = true;
    var token = node.endToken;

    while (isEmpty(token) || isComment(token)) {
      if (end) {
        end = false;
      }
      token = token.prev;
    }

    if (!isSemicolon(token)) {
      var semicolon = {
        type: 'Punctuator',
        value: ';',
        prev: token,
        next: token.next,
        root: token.root
      };

      if (token.next) {
        token.next.prev = semicolon;
      } else if (token.root) {
        token.root.endToken = semicolon;
      }

      token.next = semicolon;

      if (end) {
        node.endToken = semicolon;
      }
    }
  } else if ('EmptyStatement' === node.type) {
    // FIXME: Basically, setting value to an empty string
    // and changing type to "EmptyStatement" for "WhiteSpace",
    // "Indent", and "LineBreak" is a workaround to prevent a bug.
    // See https://github.com/bulyshko/esformatter-semicolons/issues/2
    var token = node.startToken;
    var prev = token.prev;

    while (isEmpty(prev)) {
      prev.type = 'EmptyStatement';
      prev.value = '';
      prev = prev.prev;
    }

    token.value = '';
  }
};

function isEmpty(token) {
  return token &&
    (token.type === 'WhiteSpace' ||
    token.type === 'Indent' ||
    token.type === 'LineBreak');
}

function isComment(token) {
  return token &&
    (token.type === 'LineComment' ||
    token.type === 'BlockComment');
}

function isSemicolon(token) {
  return token && token.type === 'Punctuator' && token.value === ';';
}
<commit_msg>Ignore variable declarations in for statements<commit_after>exports.nodeBefore = function(node) {
  if (~['ExpressionStatement', 'VariableDeclaration', 'ReturnStatement'].indexOf(node.type)) {
    var end = true;
    var token = node.endToken;

    while (isEmpty(token) || isComment(token)) {
      if (end) {
        end = false;
      }
      token = token.prev;
    }

    if (!isSemicolon(token) && !isLoop(node.parent)) {
      var semicolon = {
        type: 'Punctuator',
        value: ';',
        prev: token,
        next: token.next,
        root: token.root
      };

      if (token.next) {
        token.next.prev = semicolon;
      } else if (token.root) {
        token.root.endToken = semicolon;
      }

      token.next = semicolon;

      if (end) {
        node.endToken = semicolon;
      }
    }
  } else if ('EmptyStatement' === node.type) {
    // FIXME: Basically, setting value to an empty string
    // and changing type to "EmptyStatement" for "WhiteSpace",
    // "Indent", and "LineBreak" is a workaround to prevent a bug.
    // See https://github.com/bulyshko/esformatter-semicolons/issues/2
    var token = node.startToken;
    var prev = token.prev;

    while (isEmpty(prev)) {
      prev.type = 'EmptyStatement';
      prev.value = '';
      prev = prev.prev;
    }

    token.value = '';
  }
};

function isEmpty(token) {
  return token &&
    (token.type === 'WhiteSpace' ||
    token.type === 'Indent' ||
    token.type === 'LineBreak');
}

function isComment(token) {
  return token &&
    (token.type === 'LineComment' ||
    token.type === 'BlockComment');
}

function isSemicolon(token) {
  return token && token.type === 'Punctuator' && token.value === ';';
}

function isLoop(node) {
  return node && ~['ForStatement', 'ForInStatement'].indexOf(node.type);
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var util = require('util');
var semver = require('semver');
var BPromise = require('bluebird');

exports.name = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')).name;

var listVersions = function() {
  // find all of the versions of node installed by n.
  var file = path.join(process.env.N_PREFIX || '/usr/local', 'n/versions');
  var result = [];
  if (fs.existsSync(file)) {
    result = fs.readdirSync(file).filter(function(name) {
      return name[0] !== '.';
    });
  }
  return result;
};

var installedVersion = function(matching) {
  var version = null;
  listVersions().forEach(function(v) {
    if (semver.satisfies(v, matching)) {
      if (!version || semver.gt(v, version)) {
        version = v;
      }
    }
  });
  return version;
};

exports.match = function(version) {
  return BPromise.resolve()
  .then(function() { return installedVersion(version); })
  .then(function(use) {
    var command = util.format('n %s > /dev/null;', use);
    var result = { version: use, command: command };
    return use ? result : BPromise.reject('no version matching ' + version);
  });
};
<commit_msg>Changed export style.<commit_after>var fs = require('fs');
var path = require('path');
var util = require('util');
var semver = require('semver');
var BPromise = require('bluebird');

var name = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')).name;

var listVersions = function() {
  // find all of the versions of node installed by n.
  var file = path.join(process.env.N_PREFIX || '/usr/local', 'n/versions');
  var result = [];
  if (fs.existsSync(file)) {
    result = fs.readdirSync(file).filter(function(name) {
      return name[0] !== '.';
    });
  }
  return result;
};

var installedVersion = function(matching) {
  var version = null;
  listVersions().forEach(function(v) {
    if (semver.satisfies(v, matching)) {
      if (!version || semver.gt(v, version)) {
        version = v;
      }
    }
  });
  return version;
};

var match = function(version) {
  return BPromise.resolve()
  .then(function() { return installedVersion(version); })
  .then(function(use) {
    var command = util.format('n %s > /dev/null;', use);
    var result = { version: use, command: command };
    return use ? result : BPromise.reject('no version matching ' + version);
  });
};

module.exports = {
  name: name,
  match: match
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

//TODO remember why I did this
require('./src/Turbulence');
require('./src/Executors/LocalExecutor');
require('./src/Reporters/JadeHtmlReportGenerator');
require('./src/Http/UnirestHttpClient');
require('./src/Reporters/__test__/StubFs');

var Hapi = require('Hapi');

var fs = require('fs');
var globule = require('globule');
var argh = require('argh');

var args = argh.argv;
var filenames = args.argv ? args.argv : [];

if (!args.slave) {
    if (filenames[0] === '{}') {
        var file = '';
        process.stdin.on('readable', function () {
            var chunk = process.stdin.read();
            if (chunk !== null) {
                file += chunk;
            }
        });

        process.stdin.on('end', function () {
            run(file);
        });
    } else {
        if (args.master) {
            if (typeof args.master !== 'string') {
                console.error('Must supply at least 1 slave url');
                return;
            }
        }

        if (filenames.length === 0) {
            filenames = globule.find('**/*.turbulence');
        } else {
            filenames = filenames.reduce(function (array, next) {
                return array.concat(globule.find(next));
            }, []);
        }

        var errored = false;
        var files = '';
        var x = 0;
        for (var i = 0; i < filenames.length; i++) {
            var name = filenames[i];
            fs.readFile(name, function (err, file) {
                if (err) {
                    console.error('File \'' + name + '\' does not exist');
                    errored = true;
                } else {
                    files += file;
                    x++;
                    if (x === filenames.length && !errored) {
                        run(files);
                    }
                }
            });
        }
    }

    function run(file) {
        var T = new require('./src/Turbulence').Turbulence;

        var E;
        if (args.master) {
            E = function () {
                var RemoteExecutor = require('./src/Executors/RemoteExecutor').RemoteExecutor;
                return new RemoteExecutor(args.master);
            };
        } else {
            E = new require('./src/Executors/LocalExecutor').LocalExecutor;
        }

        var R = require('./src/Reporters/JadeHtmlReportGenerator').JadeHtmlReportGenerator;
        var H = require('./src/Http/UnirestHttpClient').UnirestHttpClient;
        var F = require('./src/Reporters/__test__/StubFs').StubFs;
        var turbulence = new T(new H(), new E(), new R(new F()));
        eval(file)
            .report()
            .then(function () {
            })
            .catch(console.error);
    }
} else {
    var DistributedTurbulence = new require('./src/DistributedTurbulence').DistributedTurbulence;

    var server = new Hapi.Server();
    server.connection({port: 7777});
    server.start(function (err) {
        if (err) {
            throw err;
        }

        // console.log('Listening for test plans');
    });

    server.route({
        handler: new DistributedTurbulence().route,
        method: 'POST',
        path: '/'
    });
}
<commit_msg>Fixing imports.<commit_after>#!/usr/bin/env node

var Hapi = require('hapi');

var fs = require('fs');
var globule = require('globule');
var argh = require('argh');

var args = argh.argv;
var filenames = args.argv ? args.argv : [];

if (!args.slave) {
    if (filenames[0] === '{}') {
        var file = '';
        process.stdin.on('readable', function () {
            var chunk = process.stdin.read();
            if (chunk !== null) {
                file += chunk;
            }
        });

        process.stdin.on('end', function () {
            run(file);
        });
    } else {
        if (args.master) {
            if (typeof args.master !== 'string') {
                console.error('Must supply at least 1 slave url');
                return;
            }
        }

        if (filenames.length === 0) {
            filenames = globule.find('**/*.turbulence');
        } else {
            filenames = filenames.reduce(function (array, next) {
                return array.concat(globule.find(next));
            }, []);
        }

        var errored = false;
        var files = '';
        var x = 0;
        for (var i = 0; i < filenames.length; i++) {
            var name = filenames[i];
            fs.readFile(name, function (err, file) {
                if (err) {
                    console.error('File \'' + name + '\' does not exist');
                    errored = true;
                } else {
                    files += file;
                    x++;
                    if (x === filenames.length && !errored) {
                        run(files);
                    }
                }
            });
        }
    }

    function run(file) {
        var T = new require('./src/Turbulence').Turbulence;

        var E;
        if (args.master) {
            E = function () {
                var RemoteExecutor = require('./src/Executors/RemoteExecutor').RemoteExecutor;
                return new RemoteExecutor(args.master);
            };
        } else {
            E = new require('./src/Executors/LocalExecutor').LocalExecutor;
        }

        var R = require('./src/Reporters/JadeHtmlReportGenerator').JadeHtmlReportGenerator;
        var H = require('./src/Http/UnirestHttpClient').UnirestHttpClient;
        var F = require('./src/Reporters/__test__/StubFs').StubFs;
        var turbulence = new T(new H(), new E(), new R(new F()));
        eval(file)
            .report()
            .then(function () {
            })
            .catch(console.error);
    }
} else {
    var DistributedTurbulence = new require('./src/DistributedTurbulence').DistributedTurbulence;

    var server = new Hapi.Server();
    server.connection({port: 7777});
    server.start(function (err) {
        if (err) {
            throw err;
        }

        // console.log('Listening for test plans');
    });

    server.route({
        handler: new DistributedTurbulence().route,
        method: 'POST',
        path: '/'
    });
}
<|endoftext|>


<commit_before>/**
 *
 */
var baseURL = "https://gadfly-api.herokuapp.com/gadfly/api/v1.0/gap_fill_questions"
var http = require('http');
var https = require('https');
var request = require('request');
var d = require('domain').create()

replies = {
    idk: new RegExp(/^(idk|not sure|i don\'t know|don\'t know')/i),
    stop: new RegExp(/^(stop|Stop|STOP)/i),
};

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */
function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function(err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */
var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */
if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment.')
    console.log('If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment')
    process.exit(1);
}

/*
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function(bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function(bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/*
 * Core bot logic
 */
controller.on('bot_channel_join', function(bot, message) {
    bot.reply(message, "I'm here!")
});

controller.hears(['what\'s your purpose', 'why are you here', 'what do you do'], ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
    bot.reply(message, 'Hi there! I\'m a bot. If you paste a news article URL here, I can ask you questions about it.');
});

controller.hears(['hey', 'hello', 'hi', 'greetings', 'sup', 'yo'], ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
     bot.reply(message, 'Hi there! I\'m a bot. If you paste a news article URL here, I can ask you questions about it.');
 });

controller.hears(['http(.*)'], ['ambient', 'direct_mention', 'mention', 'direct_message'], function(bot, message) {
    url = message.text.replace("<", "").replace(">", "")
    bot.startConversation(message, function(err, convo) {
        convo.ask('I see you posted a link. Would you like to be quizzed on it?', [
        {
            pattern: bot.utterances.no,
            callback: function(response, convo) {
                convo.say('Perhaps later.')
                convo.next();
            }
        },
        {
            pattern: bot.utterances.yes,
            callback: function(response, convo) {
                convo.say('Cool, you said: ' + response.text);
                callGadfly(url, convo, bot)
            }
        },
        {
            default: true,
            callback: function(response, convo) {
                convo.repeat();
                convo.next();
            }
        }
        ]);
    })
});

controller.hears(['more', 'next', 'bring it on'], ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
    bot.startConversation(message, function(err, convo) {
        convo.ask('Ready?', [
        {
            pattern: bot.utterances.yes,
            callback: function(response, convo) {
                convo.say('Alright!')
                callGadfly(url, convo, bot)
            }
        },
        {
            pattern: bot.utterances.no,
            callback: function(response,convo) {
                convo.say('Okay, ready when you are.')
                convo.next();
            }
        }
        ]);
    });
});

// call the gadfly web api to get questions from the user input article.
// randomize the question to be asked using getRandomInt & push it to the conversation
function callGadfly (url, convo, bot) {
    var apiURL = baseURL + "?url=" + url;
    d.on('error', function(err) {
        convo.say('Uh oh! Hang on, something went wrong behind the scenes.')
        convo.say('I\'m just a bot so I don\'t know what went wrong. But I\'m pretty sure people will fix it.')
        convo.next()
        console.log(err.stack)
    });
    d.run(function() {
        request(apiURL, function(e, r, b) {
        if (e) {
            console.log(e);
            callback(true);
            return;
        }
        obj = JSON.parse(b)
        questions = obj['questions']
        index = getRandomInt(obj['num_questions'])
        q = questions[index]
        convo.next();
        convo.ask(q.question_text, [
        {
            pattern: q.correct_answer,
            callback: function(response, convo) {
                msg = {}
                currentChannel = convo.source_message.channel;
                convo.say('That is correct! :100: Say more and mention me to get more questions.');
                bot.say({
                    text: 'Click on the :white_check_mark: if you liked this question or the :x: if you think this question needs improvement.',
                    channel: currentChannel
                });
                if (currentChannel[0] == 'G') {
                    bot.api.groups.history({
                    channel: currentChannel,
                    count: 1,
                    inclusive: 1
                }, function (err, body) {
                    if (err) {
                        console.log(err);
                    }
                    bot.api.reactions.add({
                        timestamp: body.messages[0].ts,
                        channel: currentChannel,
                        name: 'white_check_mark'
                    });
                    bot.api.reactions.add({
                        timestamp: body.messages[0].ts,
                        channel: currentChannel,
                        name: 'x'
                    });
                });
                }
                /*bot.api.reactions.get({
                    timestamp: msg.ts,
                    channel: msg.channel
                }, function(err) {
                    if (err) {
                        console.log(err)
                    }
                    console.log()
                });*/
                convo.next();
            }
        },
        {
            pattern: replies.idk,
            callback: function(response, convo) {
                convo.say('That\'s okay! If you want, you can read the article here' + ' ' + url);
                convo.next();
            }
        },
        {
            pattern: replies.stop,
            callback: function(response, convo) {
                convo.say('I heard you loud and clear boss.');
                convo.next();
            }
        },
        {
            default: true,
            callback: function(response, convo) {
                convo.say('Whoops! That is incorrect. :frowning:');
                convo.repeat();
                convo.next();
            }
        }
        ]);
    });
    });
};

// get random integers between 0-12
function getRandomInt(range) {
    return Math.floor(Math.random() * range);
}

// stop
controller.hears(['stop', 'Stop', 'STOP', 'stahp', 'STAHP'],['direct_message','mention'], function(bot, message) {
    return bot.reply(message, 'I heard you loud and clear boss.');
});

// for personality
controller.hears(['who are you', 'are you a bot', 'what are you'], ['direct_message','mention','direct_mention'], function(bot, message) {
    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    }, function(err) {
        if (err) {
            console.log(err)
        }
        bot.reply(message, 'I\'m just a poor bot, I need no sympathy, Because I\'m easy come, easy go.');
    });
});
controller.hears('open the (.*) doors',['direct_message','mention'], function(bot, message) {
  var doorType = message.match[1]; //match[1] is the (.*) group. match[0] is the entire group (open the (.*) doors).
  if (doorType === 'pod bay') {
    return bot.reply(message, 'I\'m sorry, Dave. I\'m afraid I can\'t do that.');
  }
  return bot.reply(message, 'Okay');
});

//monitor reactions
/*controller.on('reaction_added', function(bot, message) {
    console.log(message.reaction)
})*/

// all un-handled direct mentions get a reaction and a pat response!
controller.on('direct_message, mention, direct_mention', function(bot, message) {
    bot.reply(message, 'Hi there! I\'m a bot. If you paste a news article URL here, I can ask you questions about it.');
});<commit_msg>conversation edits added<commit_after>/**
 *
 */
var baseURL = "https://gadfly-api.herokuapp.com/gadfly/api/v1.0/gap_fill_questions"
var http = require('http');
var https = require('https');
var request = require('request');
var d = require('domain').create()

replies = {
    idk: new RegExp(/^(idk|not sure|i don\'t know|don\'t know')/i),
    stop: new RegExp(/^(stop|Stop|STOP)/i),
};

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */
function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function(err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */
var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */
if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment.')
    console.log('If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment')
    process.exit(1);
}

/*
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function(bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function(bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/*
 * Core bot logic
 */
controller.on('bot_channel_join', function(bot, message) {
    bot.reply(message, "I'm here!")
});

controller.hears(['what\'s your purpose', 'why are you here', 'what do you do'], ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
    bot.reply(message, 'Hi there! I\'m a bot. If you paste a news article URL in this channel, I can start asking you questions about it.');
});

controller.hears(['hey', 'hello', 'hi', 'greetings', 'sup', 'yo'], ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
     bot.reply(message, 'Hi there! I\'m a bot. If you paste a news article URL in this channel, I can start asking you questions about it.');
 });

controller.hears(['http(.*)'], ['ambient', 'direct_mention', 'mention', 'direct_message'], function(bot, message) {
    url = message.text.replace("<", "").replace(">", "")
    bot.startConversation(message, function(err, convo) {
        convo.ask('I see you posted a link. Would you like to be quizzed on it?', [
        {
            pattern: bot.utterances.no,
            callback: function(response, convo) {
                convo.say('Perhaps later.')
                convo.next();
            }
        },
        {
            pattern: bot.utterances.yes,
            callback: function(response, convo) {
                convo.say('Cool, you said: ' + response.text);
                callGadfly(url, convo, bot)
            }
        },
        {
            default: true,
            callback: function(response, convo) {
                convo.repeat();
                convo.next();
            }
        }
        ]);
    })
});

controller.hears(['more', 'next', 'bring it on'], ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
    bot.startConversation(message, function(err, convo) {
        convo.ask('Ready?', [
        {
            pattern: bot.utterances.yes,
            callback: function(response, convo) {
                convo.say('Alright!')
                callGadfly(url, convo, bot)
            }
        },
        {
            pattern: bot.utterances.no,
            callback: function(response,convo) {
                convo.say('Okay, ready when you are.')
                convo.next();
            }
        }
        ]);
    });
});

// call the gadfly web api to get questions from the user input article.
// randomize the question to be asked using getRandomInt & push it to the conversation
function callGadfly (url, convo, bot) {
    var apiURL = baseURL + "?url=" + url;
    d.on('error', function(err) {
        convo.say('Uh oh! Hang on, something went wrong behind the scenes.')
        convo.say('I\'m just a bot so I don\'t know what went wrong. But I\'m pretty sure people will fix it.')
        convo.next()
        console.log(err.stack)
    });
    d.run(function() {
        request(apiURL, function(e, r, b) {
        if (e) {
            console.log(e);
            callback(true);
            return;
        }
        obj = JSON.parse(b)
        questions = obj['questions']
        index = getRandomInt(obj['num_questions'])
        q = questions[index]
        convo.next();
        convo.ask(q.question_text, [
        {
            pattern: q.correct_answer,
            callback: function(response, convo) {
                msg = {}
                currentChannel = convo.source_message.channel;
                convo.say('That is correct! :100: Say more and mention me to get more questions.');
                bot.say({
                    text: 'Click on the :thumbsup: if you liked this question or the :thumbsdown: if you think this question needs improvement.',
                    channel: currentChannel
                });
                bot.api.group.history({
                    channel: currentChannel,
                    count: 1,
                    inclusive: 1
                }, function (err, body) {
                    if (err) {
                        console.log(err);
                    }
                    bot.api.reactions.add({
                        timestamp: body.messages[0].ts,
                        channel: currentChannel,
                        name: 'thumbsup'
                    });
                    bot.api.reactions.add({
                        timestamp: body.messages[0].ts,
                        channel: currentChannel,
                        name: 'thumbsdown'
                    });
                });
                convo.next();
            }
        },
        {
            pattern: replies.idk,
            callback: function(response, convo) {
                convo.say('That\'s okay! If you want, you can read the article here' + ' ' + url);
                convo.next();
            }
        },
        {
            pattern: replies.stop,
            callback: function(response, convo) {
                convo.say('I heard you loud and clear boss.');
                convo.next();
            }
        },
        {
            default: true,
            callback: function(response, convo) {
                convo.say('Whoops! That is incorrect. :frowning:');
                convo.repeat();
                convo.next();
            }
        }
        ]);
    });
    });
};

// get random integers between 0-12
function getRandomInt(range) {
    return Math.floor(Math.random() * range);
}

// stop
controller.hears(['stop', 'Stop', 'STOP', 'stahp', 'STAHP'],['direct_message','mention'], function(bot, message) {
    return bot.reply(message, 'I heard you loud and clear boss.');
});

// for personality
controller.hears(['who are you', 'are you a bot', 'what are you'], ['direct_message','mention','direct_mention'], function(bot, message) {
    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    }, function(err) {
        if (err) {
            console.log(err)
        }
        bot.reply(message, 'I\'m just a poor bot, I need no sympathy, Because I\'m easy come, easy go.');
    });
});
controller.hears('open the (.*) doors',['direct_message','mention'], function(bot, message) {
  var doorType = message.match[1]; //match[1] is the (.*) group. match[0] is the entire group (open the (.*) doors).
  if (doorType === 'pod bay') {
    return bot.reply(message, 'I\'m sorry, Dave. I\'m afraid I can\'t do that.');
  }
  return bot.reply(message, 'Okay');
});

//monitor reactions
controller.on('reaction_added', function(bot, message) {
    if (message.user != 'U11CYN007') {
        console.log(message.reaction)
    }
})

// all un-handled direct mentions get a reaction and a pat response!
controller.on('direct_message, mention, direct_mention', function(bot, message) {
    bot.reply(message, 'Hi there! I\'m a bot. If you paste a news article URL here, I can ask you questions about it.');
});<|endoftext|>


<commit_before>var gm = require('gm'),
  temp = require('temp'),
  fs = require('fs');

function randomIntInc(low, high) {
  return Math.floor(Math.random() * (high - low + 1) + low);
}

module.exports = function (options, buffer, callback) {

  if (!callback && typeof buffer === 'function') {
    callback = buffer;
    buffer = options;
    options = {};
  }

  var shiftXMaxPercent = options.shiftXMaxPercent || 1,
    shiftYMaxPercent = options.shiftYMaxPercent || 1

  gm(buffer).identify(function (err, data) {
    if (err) {
      callback(err);
    }

    var imgWidth = data.size.width,
      imgHeight = data.size.height,
      shiftX = randomIntInc(0, imgHeight * shiftXMaxPercent),
      shiftY = randomIntInc(0, imgWidth * shiftYMaxPercent),
      tempImgRoll = temp.path({
        suffix: '.' + data.format
      }),
      tempImg = temp.path({
        suffix: '.' + data.format
      });;

    //TODO: uhh, how about some async
    gm(buffer)
      .write(tempImg, function () {
        gm(buffer)
          .roll(shiftX, shiftY)
          .write(tempImgRoll, function () {

            gm().setFormat(data.format)
              .in('-page', '+0+0')
              .in(tempImgRoll)
              .in('-page', '+' + 0 + '+' + 0)
              .compose('Add')
              .in(tempImg)
              .mosaic()
              .toBuffer(function (err, buff) {
                fs.unlinkSync(tempImg);
                if (err) callback(err);
                gm(buff)
                // .crop(imgWidth - shiftX, imgHeight - shiftY, shiftX, shiftY)
                //  .resize(imgWidth, imgHeight)
                .toBuffer(function (err, buffy) {
                  if (err) callback(err);
                  callback(null, buffy);
                })
              });
          });
      });
  });
};<commit_msg>switch to flatten and push format set down to final buffer step<commit_after>var gm = require('gm'),
  temp = require('temp'),
  fs = require('fs');

function randomIntInc(low, high) {
  return Math.floor(Math.random() * (high - low + 1) + low);
}

module.exports = function (options, buffer, callback) {

  if (!callback && typeof buffer === 'function') {
    callback = buffer;
    buffer = options;
    options = {};
  }

  var shiftXMaxPercent = options.shiftXMaxPercent || 1,
    shiftYMaxPercent = options.shiftYMaxPercent || 1;

  gm(buffer).identify(function (err, data) {
    if (err) {
      callback(err);
    }

    var imgWidth = data.size.width,
      imgHeight = data.size.height,
      shiftX = randomIntInc(0, imgHeight * shiftXMaxPercent),
      shiftY = randomIntInc(0, imgWidth * shiftYMaxPercent),
      tempImgRoll = temp.path({
        suffix: '.' + data.format
      }),
      tempImg = temp.path({
        suffix: '.' + data.format
      });

    //TODO: uhh, how about some async
    gm(buffer)
      .write(tempImg, function () {
        gm(buffer)
          .roll(shiftX, shiftY)
          .write(tempImgRoll, function () {
            gm()
              .in('-page', '+0+0')
              .in(tempImgRoll)
              .in('-page', '+' + 0 + '+' + 0)
              .compose('Add')
              .in(tempImg)
              .flatten()
              .toBuffer(function (err, buff) {
                fs.unlinkSync(tempImg);
                if (err) callback(err);
                gm(buff).setFormat(data.format)
                  .toBuffer(function (err, buffy) {
                    if (err) callback(err);
                    callback(null, buffy);
                  });
              });
          });
      });
  });
};<|endoftext|>


<commit_before>#! /usr/bin/env node

var path = require('path')
var join = path.join
var fs = require('fs')
var moduleDeps = require('module-deps')
var resolve = require('resolve')
var through = require('through2')
var nodepack = require('nodepack')
var sort = require('sort-stream')
var deterministic = require('./deterministic')
var pack = require('./pack')

// io.js native modules
var native_modules = [
  'assert', 'buffer', 'child_process', 'cluster', 'console',
  'constants', 'crypto', 'dgram', 'dns', 'domain', 'events',
  'freelist', 'fs', 'http', 'https', 'module', 'net', 'os',
  'path', 'process', 'punycode', 'querystring', 'readline',
  'repl', 'smalloc', 'stream', 'string_decoder', 'sys',
  'timers', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'zlib'
]

var argv = require('minimist')(process.argv.slice(2), {
  alias: {
    f: 'filter',
    p: 'prelude',
    v: 'version'
  }
})

if(argv.version)
  return console.log(require('./package.json').version)

var filter = [].concat(argv.filter).concat(native_modules)

function exists (p) {
  try {
    (fs.accessSync || fs.statSync)(p)
    return true
  } catch (err) {
    return false
  }
}

function pkgRoot (file) {
  var dir = path.dirname(file)
    , prev
  while (true) {
    if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules')))
      return dir

    if (prev === dir) {
      throw new Error('Could not find module root for ' + file)
    }

    prev = dir
    dir = join(dir, '..')
  }
}

if(!argv._[0]) {
  console.error('usage: noderify entry.js > bundle.js')
  process.exit(1)
}

var entry = path.resolve(argv._[0])

var replace = {}
var deps = moduleDeps({
  ignoreMissing: true,
  globalTransform: function (file, opts) {
    return through(function (chunk, enc, cb) {
      chunk += ''
      var s = this
      var m = chunk.match(/require\(.bindings.\)\(.([\-_a-zA-Z0-9.]+).\)/)
      if (m) {
        var basedir = pkgRoot(file)
        var n = m[1].substr(-5) === '.node' ? m[1] : m[1]+ '.node'
        resolve('./build/Release/'+n, {basedir: pkgRoot(file), extensions: ['.node']},
          function (err, p) {
            chunk = chunk.replace(m[0], "require('./"+path.relative(basedir, p)+"')")
            s.push(chunk)
            cb()
          })
      } else {
        s.push(chunk)
        cb()
      }
    })
  },
  filter: function (s) {
    return !~filter.indexOf(s)
  },
  resolve: function (a, b, cb) {
    return resolve (a, {
        basedir: path.dirname(b.filename),
        extensions: ['.js', '.json', '.node']
      },
      function (err, file) {
        if (file) {
          if (file[0] !== '/') {
            var c = a.split('/')[0]
            if (c[0] !== '.') console.error('missing dependency. need to install:', c)
          } else if (file && file.substr(-5) === '.node') {
            replace[a] = path.relative(path.dirname(entry), file)
            return cb(null, null)
          }
        }

        cb(null, /^\//.test(file) ? file : null)
    })
  },
  postFilter: function (id, file, pkg) {
    return !!file
  }
})
  .on('data', function (e) {
    e.id = path.relative(process.cwd(), e.id)
    e.source = e.source.replace(/^\s*#![^\n]*/, '\n')
    // secret magic sauce
    for (var id in replace) {
      e.source = e.source.replace(new RegExp("require\\(\\'"+id+"\\'\\)", 'g'), "require('./"+replace[id]+"')")
    }

    try {
      JSON.parse(e.source)
      e.source = 'module.exports = ' + e.source
    } catch (e) { }

    for(var k in e.deps) {
      // console.error(e.id, k, e.deps[k])
      if(!e.deps[k])
        delete e.deps[k]
      else
        e.deps[k] = path.relative(process.cwd(), e.deps[k])
    }
  })

var opts = {raw: true}
if (argv.prelude) {
  var preludePath = path.resolve(argv.prelude)
  opts.prelude = fs.readFileSync(preludePath, 'utf-8')
  opts.preludePath = preludePath
}

if(opts.shebang !== false)
  console.log('#! /usr/bin/env node')

deps
  .pipe(deterministic(function (err, content, deps, entry) {
      if(err) throw err
      console.log(pack(content, deps, entry))
    }))
//  .pipe(sort(function (a, b) {
//    return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
//  }))
//
//  .pipe(nodepack(opts))
//  .pipe(process.stdout)
//
deps.end(entry)
<commit_msg>use new deterministic bundle and packing<commit_after>#! /usr/bin/env node

var path = require('path')
var join = path.join
var fs = require('fs')
var moduleDeps = require('module-deps')
var resolve = require('resolve')
var through = require('through2')
var sort = require('sort-stream')
var deterministic = require('./deterministic')
var pack = require('./pack')

// io.js native modules
var native_modules = [
  'assert', 'buffer', 'child_process', 'cluster', 'console',
  'constants', 'crypto', 'dgram', 'dns', 'domain', 'events',
  'freelist', 'fs', 'http', 'https', 'module', 'net', 'os',
  'path', 'process', 'punycode', 'querystring', 'readline',
  'repl', 'smalloc', 'stream', 'string_decoder', 'sys',
  'timers', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'zlib'
]

var argv = require('minimist')(process.argv.slice(2), {
  alias: {
    f: 'filter',
    p: 'prelude',
    v: 'version'
  }
})

if(argv.version)
  return console.log(require('./package.json').version)

var filter = [].concat(argv.filter).concat(native_modules)

function exists (p) {
  try {
    (fs.accessSync || fs.statSync)(p)
    return true
  } catch (err) {
    return false
  }
}

function pkgRoot (file) {
  var dir = path.dirname(file)
    , prev
  while (true) {
    if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules')))
      return dir

    if (prev === dir) {
      throw new Error('Could not find module root for ' + file)
    }

    prev = dir
    dir = join(dir, '..')
  }
}

if(!argv._[0]) {
  console.error('usage: noderify entry.js > bundle.js')
  process.exit(1)
}

var entry = path.resolve(argv._[0])

var replace = {}
var deps = moduleDeps({
  ignoreMissing: true,
  globalTransform: function (file, opts) {
    return through(function (chunk, enc, cb) {
      chunk += ''
      var s = this
      var m = chunk.match(/require\(.bindings.\)\(.([\-_a-zA-Z0-9.]+).\)/)
      if (m) {
        var basedir = pkgRoot(file)
        var n = m[1].substr(-5) === '.node' ? m[1] : m[1]+ '.node'
        resolve('./build/Release/'+n, {basedir: pkgRoot(file), extensions: ['.node']},
          function (err, p) {
            chunk = chunk.replace(m[0], "require('./"+path.relative(basedir, p)+"')")
            s.push(chunk)
            cb()
          })
      } else {
        s.push(chunk)
        cb()
      }
    })
  },
  filter: function (s) {
    return !~filter.indexOf(s)
  },
  resolve: function (a, b, cb) {
    return resolve (a, {
        basedir: path.dirname(b.filename),
        extensions: ['.js', '.json', '.node']
      },
      function (err, file) {
        if (file) {
          if (file[0] !== '/') {
            var c = a.split('/')[0]
            if (c[0] !== '.') console.error('missing dependency. need to install:', c)
          } else if (file && file.substr(-5) === '.node') {
            replace[a] = path.relative(path.dirname(entry), file)
            return cb(null, null)
          }
        }

        cb(null, /^\//.test(file) ? file : null)
    })
  },
  postFilter: function (id, file, pkg) {
    return !!file
  }
})
  .on('data', function (e) {
    e.id = path.relative(process.cwd(), e.id)
    e.source = e.source.replace(/^\s*#![^\n]*/, '\n')
    // secret magic sauce
    for (var id in replace) {
      e.source = e.source.replace(new RegExp("require\\(\\'"+id+"\\'\\)", 'g'), "require('./"+replace[id]+"')")
    }

    try {
      JSON.parse(e.source)
      e.source = 'module.exports = ' + e.source
    } catch (e) { }

    for(var k in e.deps) {
      // console.error(e.id, k, e.deps[k])
      if(!e.deps[k])
        delete e.deps[k]
      else
        e.deps[k] = path.relative(process.cwd(), e.deps[k])
    }
  })

var opts = {raw: true}
if (argv.prelude) {
  var preludePath = path.resolve(argv.prelude)
  opts.prelude = fs.readFileSync(preludePath, 'utf-8')
  opts.preludePath = preludePath
}

if(opts.shebang !== false)
  console.log('#! /usr/bin/env node')

deps
  .pipe(deterministic(function (err, content, deps, entry) {
      if(err) throw err
      console.log(pack(content, deps, entry))
    }))

deps.end(entry)
<|endoftext|>


<commit_before>/**
 Copyright 2017 KiKe. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 **/
'use strict';
var Alexa = require('alexa-sdk');
var _ = require('lodash');
var data = require('./data');

var MOLECULE_ALEXA_STATE = {
    START: "STARTMODE",
    HELP: "HELPMODE"
};

var languageString = {
    "en": {
        "translation": {
            "WELCOME_MESSAGE": "Welcome to Molecule! You can ask me about any Molecules",
            "PROPERTIES": "%s of %s is %s",
            "CHEMICAL_FORMULA": "%s for %s is %s",
            "MOLECULE_ERROR_MESSAGE": "I don't have any information for %s.",
            "PROPERTIES_ERROR_MESSAGE": "I don't have any information on %s of %s."
        }
    }
};

exports.handler = function (event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.resources = languageString;
    alexa.registerHandlers(newSessionHandlers, startMoleculeHandlers);
    alexa.execute();
};

var newSessionHandlers = {
    "LaunchRequest": function () {
        this.handler.state = MOLECULE_ALEXA_STATE.START;
        this.emitWithState("GetMolecules", this.event.request.intent.slots);
    },
    "GetMoleculeIntent": function () {
        this.handler.state = MOLECULE_ALEXA_STATE.START;
        this.emitWithState("GetMolecules", this.event.request.intent.slots);
    },
    "AMAZON.StartOverIntent": function () {
        this.handler.state = MOLECULE_ALEXA_STATE.START;
        this.emitWithState("GetMolecules", true);
    },
    "AMAZON.HelpIntent": function () {
        this.handler.state = MOLECULE_ALEXA_STATE.HELP;
        this.emitWithState("helpIntent", true);
    },
    "Unhandled": function () {
        var speechOutput = this.t("START_UNHANDLED");
        this.emit(":ask", speechOutput, speechOutput);
    }
};

var startMoleculeHandlers = Alexa.CreateStateHandler(MOLECULE_ALEXA_STATE.START, {

    "GetMolecules": function (slots) {
        var moleculeName = slots.MoleculeName.value;
        var moleculeData = [];
        var _this = this;
        var speechOutput;

        data.httpGet(moleculeName, function (result) {

            moleculeData = result.data;

            var dataIndex = _.findIndex(moleculeData, function (mol) {
                return mol.IUPACName.toLowerCase() == moleculeName.toLowerCase();
            });

            if (dataIndex != -1) {
                if (slots.Properties && slots.Properties.value) {
                    var propertiesIndex = _.findIndex(moleculeData[dataIndex].properties, function (prop) {
                        return prop.valueTitle.toLowerCase() == slots.Properties.value.toLowerCase();
                    });

                    var proObj = moleculeData[dataIndex].properties[propertiesIndex];
                    speechOutput += _this.t("PROPERTIES", proObj.valueTitle, moleculeName, proObj.valueData);

                    if (propertiesIndex == -1) {
                        speechOutput += _this.t("PROPERTIES_ERROR_MESSAGE", slots.Properties.value, moleculeName);
                    }

                }

                if (slots.ChemicalFormula && slots.ChemicalFormula.value) {

                    var cheObj = moleculeData[dataIndex].chemicalFormula;
                    speechOutput += _this.t("CHEMICAL_FORMULA", slots.ChemicalFormula.value, moleculeName, cheObj);

                }

            } else {
                speechOutput += _this.t("MOLECULE_ERROR_MESSAGE", moleculeName);
            }

            if (speechOutput) {
                _this.emit(":tell", speechOutput);
            } else {
                _this.emit(":tell", _this.t("WELCOME_MESSAGE"));
            }

        });
    }
});

<commit_msg>Improved functionality<commit_after>/**
 Copyright 2017 KiKe. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 **/
'use strict';
var Alexa = require('alexa-sdk');
var _ = require('lodash');
var data = require('./data');

var MOLECULE_ALEXA_STATE = {
    START: "STARTMODE",
    HELP: "HELPMODE"
};

var languageString = {
    "en": {
        "translation": {
            "WELCOME_MESSAGE": "Welcome to Molecule! You can ask me about any Molecules",
            "PROPERTIES": "%s of %s is %s",
            "CHEMICAL_FORMULA": "%s for %s is %s",
            "MOLECULE_ERROR_MESSAGE": "I don't have any information for %s.",
            "PROPERTIES_ERROR_MESSAGE": "I don't have any information on %s of %s.",
            "NOTHING_FOUND": "Sorry! I din't catch that. Please try again"
        }
    }
};

exports.handler = function (event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.resources = languageString;
    alexa.registerHandlers(newSessionHandlers, startMoleculeHandlers);
    alexa.execute();
};

var newSessionHandlers = {
    "LaunchRequest": function () {
        this.handler.state = MOLECULE_ALEXA_STATE.START;
        this.emitWithState("GetMolecules", this.event.request.intent.slots);
    },
    "GetMoleculeIntent": function () {
        this.handler.state = MOLECULE_ALEXA_STATE.START;
        this.emitWithState("GetMolecules", this.event.request.intent.slots);
    },
    "AMAZON.StartOverIntent": function () {
        this.handler.state = MOLECULE_ALEXA_STATE.START;
        this.emitWithState("GetMolecules", true);
    },
    "AMAZON.HelpIntent": function () {
        this.handler.state = MOLECULE_ALEXA_STATE.HELP;
        this.emitWithState("helpIntent", true);
    },
    "Unhandled": function () {
        var speechOutput = this.t("START_UNHANDLED");
        this.emit(":ask", speechOutput, speechOutput);
    }
};

var startMoleculeHandlers = Alexa.CreateStateHandler(MOLECULE_ALEXA_STATE.START, {

    "GetMolecules": function (slots) {
        var moleculeName = slots.MoleculeName.value;
        var moleculeData = [];
        var _this = this;
        var speechOutput;

        data.httpGet(moleculeName, function (result) {

            moleculeData = result.data;

            var dataIndex = _.findIndex(moleculeData, function (mol) {
                return mol.IUPACName.toLowerCase() == moleculeName.toLowerCase();
            });

            /**
             * Handle molecule request
             * **/
            if (dataIndex != -1) {

                /**
                 * Handle properties request
                 * **/
                if (slots.Properties && slots.Properties.value) {
                    var propertiesIndex = _.findIndex(moleculeData[dataIndex].properties, function (prop) {
                        return prop.valueTitle.toLowerCase() == slots.Properties.value.toLowerCase();
                    });

                    var proObj = moleculeData[dataIndex].properties[propertiesIndex];
                    speechOutput += _this.t("PROPERTIES", proObj.valueTitle, moleculeName, proObj.valueData);

                    if (propertiesIndex == -1) speechOutput += _this.t("PROPERTIES_ERROR_MESSAGE", slots.Properties.value, moleculeName);
                }

                /**
                 * Handle chemical formula request
                 * **/
                if (slots.ChemicalFormula && slots.ChemicalFormula.value) {
                    var chemicalFormula = moleculeData[dataIndex].chemicalFormula;
                    speechOutput += _this.t("CHEMICAL_FORMULA", slots.ChemicalFormula.value, moleculeName, chemicalFormula);
                }

                /**
                 * Handle speech is undefined
                 * **/
                if (!speechOutput) {
                    speechOutput += _this.t("NOTHING_FOUND");
                }

            } else {
                speechOutput += _this.t("MOLECULE_ERROR_MESSAGE", moleculeName);
            }

            if (speechOutput) {
                _this.emit(":tell", speechOutput);
            } else {
                _this.emit(":tell", _this.t("WELCOME_MESSAGE"));
            }

        });
    }
});

<|endoftext|>


<commit_before>/*jslint node: true, vars: true, indent: 4 */
(function (module) {
    "use strict";

    var ua = require('mobile-agent'),
        constants = {
            TRAILING_SCRIPTS: 'trailingScripts',
            STYLESHEETS: 'stylesheets',
            SCRIPTS: 'scripts',
            TEMPLATE_FILES: 'templateFiles'
        },
        AGENT_TYPES = ['Android', 'Browser', 'iOS', 'iPad', 'iPhone', 'Mac', 'Mobile', 'webOS', 'Windows', 'Cordova', 'CordovaDefault'],
        cache = {
            templates: {},
            files: {}
        },
        HTTP_NOT_FOUND = 404,
        path = require("path"),
        hbars = require("handlebars"),
        util = require("./lib/util"),
        locate = util.locate,
        fs = require("fs"),
        async = require('async');

    function locateSync(dirs, file, idx) {
        var i = idx || 0;

        if (i >= dirs.length) {
            throw new Error("file " + file + " not found in " + dirs);
        }

        var qfile = path.join(dirs[i], file);

        if (fs.existsSync(qfile)) {
            return qfile;
        } else {
            return locateSync(dirs, file, i + 1);
        }
    }

    function merge(masterAssetData, newAssetData) {

        var assetKeys = Object.keys(newAssetData);
        var i = assetKeys.length;
        var propName;

        while (i--) {
            propName = assetKeys[i];
            var newAssetDataValue = newAssetData[propName];

            if (Array.isArray(newAssetDataValue)) {
                if (masterAssetData[propName]) {
                    masterAssetData[propName] = masterAssetData[propName].concat(newAssetDataValue);
                } else {
                    masterAssetData[propName] = newAssetDataValue;
                }

            } else {

                if (typeof newAssetDataValue === 'object') {

                    var newAssetDataValueKeys = Object.keys(newAssetDataValue);
                    var j = newAssetDataValueKeys.length;
                    var prop;

                    while (j--) {
                        prop = newAssetDataValueKeys[j];
                        var newAssetDataObjectValue = newAssetDataValue[prop];

                        if (Array.isArray(newAssetDataObjectValue)) {
                            if (masterAssetData[propName] && masterAssetData[propName][prop]) {
                                masterAssetData[propName][prop] = masterAssetData[propName][prop].concat(newAssetDataObjectValue);
                            } else {
                                masterAssetData[propName][prop] = newAssetDataObjectValue;
                            }
                        } else {
                            masterAssetData[propName][prop] = newAssetDataObjectValue;
                        }
                    }
                } else {
                    masterAssetData[propName] = newAssetDataValue;
                }
            }
        }
    }

    function _filterByAgent(agentInfo, propName, assets, filtered) {
        var agentKeys = agentInfo.agentTypes;
        var agentType;

        assets.forEach(function (asset) {
            if (typeof asset === 'string') {
                if (filtered[propName]) {
                    filtered[propName].push(asset);
                } else {
                    filtered[propName] = [asset];
                }
            } else if (asset.agents) {
                var i = agentKeys.length;
                while (i--) {
                    agentType = agentKeys[i];
                    if (asset.agents.indexOf(agentType.toLowerCase()) >= 0 || asset.agents.indexOf(agentType) >= 0) {
                        if (filtered[propName]) {
                            filtered[propName].push(asset.name);
                        } else {
                            filtered[propName] = [asset];
                        }
                    }
                }
            }
        });
    }

    function filter(agentInfo, defaults) {
        var filtered = {};
        var defaultKeys = Object.keys(defaults);
        var i = defaultKeys.length;
        var propName;
        var propValue;

        while (i--) {
            propName = defaultKeys[i];
            propValue = defaults[propName];
            switch (propName) {
                case constants.TRAILING_SCRIPTS:
                case constants.STYLESHEETS:
                case constants.SCRIPTS:
                    _filterByAgent(agentInfo, propName, propValue, filtered);
                    break;
                default:
                    filtered[propName] = propValue;
                    break;
            }
        }

        return filtered;

    }

    function _getUserAgentHash(req) {
        var agent = ua(req.headers['user-agent']);
        var hash = '';
        var agentTypes = [];

        AGENT_TYPES.forEach(function (type) {
            var newVal = '0';
            if (agent[type]) {
                agentTypes.push(type);
                newVal = '1';
            } else if (req.query['agent'] === type) {
                agentTypes.push(req.query['agent']);
                newVal = '1';
            }

            hash = hash + newVal;
        });

        return {
            hash: hash,
            agentTypes: agentTypes
        };
    }

    function getCachedModule(req, namespace) {
        if(!namespace) {
            return undefined;
        }
        console.log("originalUrl: " + req.originalUrl);
        var agentInfo = _getUserAgentHash(req);
        var userAgentHash = agentInfo.hash;
        if (namespace) {
            if (namespace && cache[namespace] && cache[namespace][userAgentHash]) {
                return cache[namespace][userAgentHash];
            } else {
                return undefined;
            }
        }
    }

    function getModule(req, module) {
        console.log("originalUrl: " + req.originalUrl);
        var agentInfo = _getUserAgentHash(req);
        var userAgentHash = agentInfo.hash;

        if (cache[userAgentHash]) {
            console.log("cached userAgentHash: " + userAgentHash);
            return cache[userAgentHash];
        } else {
            var mod = filter(agentInfo, module);
            cache[userAgentHash] = mod;
            console.log("NOT cached userAgentHash: " + userAgentHash);

            return mod;
        }
    } // 01110010001

    function setModule(req, module, namespace) {
        var agentInfo = _getUserAgentHash(req);
        var userAgentHash = agentInfo.hash;
        if (namespace) {
            if(!cache[namespace]) {
                cache[namespace] = {};
            }
            if(!cache[namespace][userAgentHash]) {
                cache[namespace][userAgentHash] = module;
            }
        } else {
            if (cache[userAgentHash]) {
                cache[userAgentHash] = module;
            } else {
                cache[userAgentHash] = module;
            }
        }
    }

    function load(cache, file, cb, debug) {
        if (Object.prototype.toString.call(file) === '[object Function]') {
            return file(cb);
        }

        var cached = cache.files[file];

        if (cached) {
            return cb(undefined, cached);
        }

        fs.readFile(file, "utf-8", function (err, content) {
            if (err) {
                return cb(err);
            }

            cache.files[file] = content;

            return cb(undefined, content);
        });
    }

    function compileHtml(mod, file, statusCode, debug, cb) {
        var cached = cache.templates[file];

        if (cached) {
            return cb(undefined, mod, cached, statusCode);
        }

        return locate(mod["public"], file, function (err, qfile) {
            if (err) {
                if (statusCode === HTTP_NOT_FOUND) {
                    return (cb)?cb(err):undefined;
                }

                return compileHtml(mod, "/404.html", cb, HTTP_NOT_FOUND, debug);
            }
            return load(cache, qfile, function (err, content) {
                if (err) {
                    return cb(err);
                }

                var template = hbars.compile(content);

                cache.templates[file] = template;

                return cb(undefined, mod, template, statusCode);
            }, debug);
        });
    }

    function compileSite(mod, debug, cb) {
        var htmlFiles = mod.htmlFiles,
            rawHtml = [],
            idx = 0,
            templateFiles = mod.templateFiles,
            templateHtml = [],
            file;

        function loadHtmlFiles(cb) {
            var pos = idx++;
            async.each(htmlFiles, function (file, callback) {
                load(cache, file, function (err, content) {
                    if (err) {
                        return callback(err);
                    }

                    rawHtml[pos] = content;
                    return callback();
                }, debug);
            }, cb);
        }

        function loadTemplateFiles(cb) {
            async.each(templateFiles, function (file, callback) {
                var name = path.basename(file, '.html');

                load(cache, file, function (err, content) {
                    if (err) {
                        return callback(err);
                    }

                    templateHtml.push({
                        name: name,
                        content: content
                    });
                    return callback();
                }, debug);
            }, cb);
        }

        if (!mod.compileSite) {
            async.parallel([
                loadHtmlFiles,
                loadTemplateFiles
            ], function (err) {
                if (err) {
                    debug.error(err);
                }
                mod.htmlFiles = rawHtml;
                mod.templateFiles = templateHtml;
                mod.compileSite = true;
                cb();
            });
        } else {
            cb();
        }
    }

    module.exports = {
        merge: merge,
        filter: filter,
        getCachedModule: getCachedModule,
        getModule: getModule,
        setModule: setModule,
        compileSite: compileSite,
        compileHtml: compileHtml,
        locateSync: locateSync
    };

})(module);<commit_msg>cache list that is filtered by user agent.<commit_after>/*jslint node: true, vars: true, indent: 4 */
(function (module) {
    "use strict";

    var ua = require('mobile-agent'),
        constants = {
            TRAILING_SCRIPTS: 'trailingScripts',
            STYLESHEETS: 'stylesheets',
            SCRIPTS: 'scripts',
            TEMPLATE_FILES: 'templateFiles'
        },
        AGENT_TYPES = ['Android', 'Browser', 'iOS', 'iPad', 'iPhone', 'Mac', 'Mobile', 'webOS', 'Windows', 'Cordova', 'CordovaDefault'],
        cache = {
            templates: {},
            files: {}
        },
        HTTP_NOT_FOUND = 404,
        path = require("path"),
        hbars = require("handlebars"),
        util = require("./lib/util"),
        locate = util.locate,
        fs = require("fs"),
        async = require('async');

    function locateSync(dirs, file, idx) {
        var i = idx || 0;

        if (i >= dirs.length) {
            throw new Error("file " + file + " not found in " + dirs);
        }

        var qfile = path.join(dirs[i], file);

        if (fs.existsSync(qfile)) {
            return qfile;
        } else {
            return locateSync(dirs, file, i + 1);
        }
    }

    function merge(masterAssetData, newAssetData) {

        var assetKeys = Object.keys(newAssetData);
        var i = assetKeys.length;
        var propName;

        while (i--) {
            propName = assetKeys[i];
            var newAssetDataValue = newAssetData[propName];

            //console.log('propName: ', propName);

            if (Array.isArray(newAssetDataValue)) {
                if (masterAssetData[propName]) {
                    masterAssetData[propName] = masterAssetData[propName].concat(newAssetDataValue);
                } else {
                    masterAssetData[propName] = newAssetDataValue;
                }

            } else {

                if (typeof newAssetDataValue === 'object') {

                    var newAssetDataValueKeys = Object.keys(newAssetDataValue);
                    var j = newAssetDataValueKeys.length;
                    var prop;

                    while (j--) {
                        prop = newAssetDataValueKeys[j];
                        var newAssetDataObjectValue = newAssetDataValue[prop];

                        if (Array.isArray(newAssetDataObjectValue)) {
                            if (masterAssetData[propName] && masterAssetData[propName][prop]) {
                                masterAssetData[propName][prop] = masterAssetData[propName][prop].concat(newAssetDataObjectValue);
                            } else {
                                masterAssetData[propName][prop] = newAssetDataObjectValue;
                            }
                        } else {
                            masterAssetData[propName][prop] = newAssetDataObjectValue;
                        }
                    }
                } else {
                    masterAssetData[propName] = newAssetDataValue;
                }
            }
        }
    }

    function _filterByAgent(agentInfo, propName, assets, filtered) {
        var agentKeys = agentInfo.agentTypes;
        var agentType;

        assets.forEach(function (asset) {
            if (typeof asset === 'string') {
                if (filtered[propName]) {
                    filtered[propName].push(asset);
                } else {
                    filtered[propName] = [asset];
                }
            } else if (asset.agents) {
                var i = agentKeys.length;
                while (i--) {
                    agentType = agentKeys[i];
                    if (asset.agents.indexOf(agentType.toLowerCase()) >= 0 || asset.agents.indexOf(agentType) >= 0) {
                        if (filtered[propName]) {
                            filtered[propName].push(asset.name);
                        } else {
                            filtered[propName] = [asset];
                        }
                    }
                }
            }
        });
    }

    function filter(agentInfo, defaults) {
        var filtered = {};
        var defaultKeys = Object.keys(defaults);
        var i = defaultKeys.length;
        var propName;
        var propValue;

        while (i--) {
            propName = defaultKeys[i];
            propValue = defaults[propName];
            switch (propName) {
                case constants.TRAILING_SCRIPTS:
                case constants.STYLESHEETS:
                case constants.SCRIPTS:
                    _filterByAgent(agentInfo, propName, propValue, filtered);
                    break;
                default:
                    filtered[propName] = propValue;
                    break;
            }
        }

        return filtered;

    }

    function _getUserAgentHash(req) {
        var agent = ua(req.headers['user-agent']);
        var hash = '';
        var agentTypes = [];

        AGENT_TYPES.forEach(function (type) {
            var newVal = '0';
            if (agent[type]) {
                agentTypes.push(type);
                newVal = '1';
            } else if (req.query['agent'] === type) {
                agentTypes.push(req.query['agent']);
                newVal = '1';
            }

            hash = hash + newVal;
        });

        return {
            hash: hash,
            agentTypes: agentTypes
        };
    }

    function getCachedModule(req, namespace) {
        //console.log('getCachedModule: ', namespace);
        if(!namespace) {
            return undefined;
        }
        console.log("originalUrl: " + req.originalUrl);
        var agentInfo = _getUserAgentHash(req);
        var userAgentHash = agentInfo.hash;
        if (namespace) {
            if (namespace && cache[namespace] && cache[namespace][userAgentHash]) {
                return cache[namespace][userAgentHash];
            } else {
                return undefined;
            }
        }
    }

    function getModule(req, module) {
        //console.log('getModule: ');
        //console.log("originalUrl: " + req.originalUrl);
        var agentInfo = _getUserAgentHash(req);
        var userAgentHash = agentInfo.hash;

        if (cache[userAgentHash]) {
            console.log("cached userAgentHash: " + userAgentHash);
            return cache[userAgentHash];
        } else {
            var mod = filter(agentInfo, module);
            cache[userAgentHash] = mod;
            console.log("NOT cached userAgentHash: " + userAgentHash);

            return mod;
        }
    } // 01110010001

    function setModule(req, module, namespace) {
        //console.log('setModule: ', namespace);

        var agentInfo = _getUserAgentHash(req);
        var userAgentHash = agentInfo.hash;
        var mod = filter(agentInfo, module);
        if (namespace) {
            if(!cache[namespace]) {
                cache[namespace] = {};
            }
            if(!cache[namespace][userAgentHash]) {
                cache[namespace][userAgentHash] = mod;
            }
        } else {
            if (cache[userAgentHash]) {
                cache[userAgentHash] = mod;
            } else {
                cache[userAgentHash] = mod;
            }
        }
    }

    function load(cache, file, cb, debug) {
        if (Object.prototype.toString.call(file) === '[object Function]') {
            return file(cb);
        }

        var cached = cache.files[file];

        if (cached) {
            return cb(undefined, cached);
        }

        fs.readFile(file, "utf-8", function (err, content) {
            if (err) {
                return cb(err);
            }

            cache.files[file] = content;

            return cb(undefined, content);
        });
    }

    function compileHtml(mod, file, statusCode, debug, cb) {
        var cached = cache.templates[file];

        if (cached) {
            return cb(undefined, mod, cached, statusCode);
        }

        return locate(mod["public"], file, function (err, qfile) {
            if (err) {
                if (statusCode === HTTP_NOT_FOUND) {
                    return (cb)?cb(err):undefined;
                }

                return compileHtml(mod, "/404.html", cb, HTTP_NOT_FOUND, debug);
            }
            return load(cache, qfile, function (err, content) {
                if (err) {
                    return cb(err);
                }

                var template = hbars.compile(content);

                cache.templates[file] = template;

                return cb(undefined, mod, template, statusCode);
            }, debug);
        });
    }

    function compileSite(mod, debug, cb) {
        var htmlFiles = mod.htmlFiles,
            rawHtml = [],
            idx = 0,
            templateFiles = mod.templateFiles,
            templateHtml = [],
            file;

        function loadHtmlFiles(cb) {
            var pos = idx++;
            async.each(htmlFiles, function (file, callback) {
                load(cache, file, function (err, content) {
                    if (err) {
                        return callback(err);
                    }

                    rawHtml[pos] = content;
                    return callback();
                }, debug);
            }, cb);
        }

        function loadTemplateFiles(cb) {
            async.each(templateFiles, function (file, callback) {
                var name = path.basename(file, '.html');

                load(cache, file, function (err, content) {
                    if (err) {
                        return callback(err);
                    }

                    templateHtml.push({
                        name: name,
                        content: content
                    });
                    return callback();
                }, debug);
            }, cb);
        }

        if (!mod.compileSite) {
            async.parallel([
                loadHtmlFiles,
                loadTemplateFiles
            ], function (err) {
                if (err) {
                    debug.error(err);
                }
                mod.htmlFiles = rawHtml;
                mod.templateFiles = templateHtml;
                mod.compileSite = true;
                cb();
            });
        } else {
            cb();
        }
    }

    module.exports = {
        merge: merge,
        filter: filter,
        getCachedModule: getCachedModule,
        getModule: getModule,
        setModule: setModule,
        compileSite: compileSite,
        compileHtml: compileHtml,
        locateSync: locateSync
    };

})(module);<|endoftext|>


<commit_before>var Discord = require('discord.io');
var BOT_TOKEN = require('./BOT-TOKEN.json');
var ITEM_LIST = require('./itemlist.json');
var bot = new Discord.Client({
    token: BOT_TOKEN.token,
    autorun: true
});
var bot_activation_string = '!lucy';
var ITEM_LIST_KEYS = Object.keys(ITEM_LIST);

bot.on('ready', function() {
    console.log(bot.username + " - (" + bot.id + ")");
    console.log("To share this bot please use the following URL: https://discordapp.com/oauth2/authorize?&client_id=" + bot.id + "&scope=bot&permissions=0");
    console.log("I've loaded the file and it has: " + ITEM_LIST_KEYS.length + " items.");
});

bot.on('message', function(user, userID, channelID, message, event) {

    var bot_string_regex = new RegExp(bot_activation_string, 'i');
    if (bot_string_regex.test(message)) {
        var item_lookup_string = message.replace(bot_activation_string + " ", "");
        var found_item = ITEM_LIST[item_lookup_string];
        // console.log(found_item);
        var reply_message = "I can't seem to find '" + item_lookup_string + "', perhaps you wanted '" + ITEM_LIST_KEYS[getRandomIntInclusive(0, ITEM_LIST_KEYS.length-1)] + "' instead?";
        if(found_item) {
            reply_message = "Is this what you are looking for? " + found_item.url;
        }
        bot.sendMessage({
            to: channelID,
            message: reply_message
        });
    }
});

function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
<commit_msg>Added csvtojson parsing and cleaned up some introduction messages<commit_after>//External Dependencies
var Discord = require('discord.io');
var Converter = require("csvtojson").Converter;
var converter = new Converter({});

//Configurable Paramaters
var BOT_TOKEN = require('./BOT-TOKEN.json');
var BOT_ACTIVATION_STRING = '!lucy';

var ITEM_LIST = [];

converter.fromFile("./itemlist.txt",function(err,result){
    console.log("Converting csv to json...");
    if(err) {
        console.log(err);
        process.exit(-1);
    } else {
        ITEM_LIST = result;
        console.log("I've loaded the file and it has: " + ITEM_LIST.length + " items.");
    }
});

var bot = new Discord.Client({
    token: BOT_TOKEN.token,
    autorun: true
});

bot.on('ready', function() {
    console.log(bot.username + " has begun operation.");
    console.log("To share this bot please use the following URL: \n==========\nhttps://discordapp.com/oauth2/authorize?&client_id=" + bot.id + "&scope=bot&permissions=0\n==========");
});

bot.on('message', function(user, userID, channelID, message, event) {

    var bot_string_regex = new RegExp(BOT_ACTIVATION_STRING, 'i');
    if (bot_string_regex.test(message)) {
        var item_lookup_string = message.replace(BOT_ACTIVATION_STRING + " ", "");
        var found_item = {};
        var reply_message = "I am broken.";
        if(found_item) {
            reply_message = found_item.lucylink;
        }
        bot.sendMessage({
            to: channelID,
            message: reply_message
        });
    }
});

function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
<|endoftext|>


<commit_before>/* global window */
/* eslint-disable spaced-comment, new-cap, comma-dangle */
var is = require('./source/is');
var proxy = require('./source/proxy');
var read = require('./source/read');
var write = require('./source/write');
var assign = require('./source/assign');
var validate = require('./source/validate');
var assignStrategyDefault = require('./source/strategies/assign-default');
var dotStrategyDefault = require('./source/strategies/dot-default');

/*!
 * Public methods.
 */
var fns = 'res exe cfg get set'.split(' ');

/*!
 * Mixing behaviors.
 */
var assignStrategy = assign(assignStrategyDefault);

/*!
 * A global GUID counter for objects.
 */
var guid = 1;

/*!
 * Define a local copy of `DotCfg`.
 * @param namespace: A string containing a qualified name to identify objects from.
 * @param scope: A object that have system-wide relevance.
 * @param strategy: A function that configures the input values.
 */
var DotCfg = function (namespace/*?*/, scope/*?*/, strategy/*?*/) {
	if (!is.primitive(namespace)) {
		strategy = scope;
		scope = namespace;
		namespace = undefined;
	}
	var expose = is.undef(global) ? window : global;
	var self = is.primitive(scope) ? expose : scope;
	var fn = is.fn(strategy) ? strategy : dotStrategyDefault;
	return new DotCfg.fn.init(namespace, self, fn);
};

/*!
 * Create a instance of `DotCfg`.
 * @param namespace: A string containing a qualified name to identify objects from.
 * @param scope: A object that have system-wide relevance.
 * @param strategy: A function that configures the input values.
 */
var init = function (namespace/*?*/, scope/*?*/, strategy/*?*/) {
	if (is.string(namespace)) {
		scope[namespace] = scope[namespace] || Object.create(null);
		scope = scope[namespace];
	}
	this.strategy = strategy;
	this.extends = proxy(assign(strategy), this, scope);
	this.namespace = namespace || 'dot' + guid;
	this.scope = validate(scope, this, fns);
	guid++;
	return this.scope();
};

/*!
 * Write/Read/Delete/Update a config with strategy method if needed.
 * @param notation:
 * @param value:
 * @param strategy:
 */
var cfg = function (notation/*?*/, value/*?*/, strategy/*?*/) {
	var hasArg = arguments.length > 1;
	if (!notation) {
		return this.scope(true);
	}
	if (notation === true) {
		var cp = assignStrategy({}, this.scope());
		for (var id = 0, key, acc; id < fns.length; id++) {
			key = fns[id];
			acc = '@' + key;
			if (cp[acc]) {
				cp[key] = cp[acc];
				delete cp[acc];
			} else {
				delete cp[key];
			}
		}
		return cp;
	}
	if (is.primitive(notation)) {
		return hasArg ? this.set(notation, value, strategy) : this.get(notation);
	}
	return this.extends(notation);
};

/*!
 * Read safely a key containing a function or a simple property.
 * @param notation: A object path.
 * @param ...rest: Arguments for the object.
 */
var res = function (notation/*!*/) {
	var scope = this.scope();
	var part = read(scope, notation);
	var args = Array.prototype.slice.call(arguments, 1);
	return is.fn(part) ? part.apply(scope, args) : part;
};

/*!
 * *** DEPRECATED METHOD ***
 * Read safely a key containing a function or a simple property.
 * @param notation: A object path.
 * @param ...rest: Arguments for the object.
 */
var exe = function (notation/*!*/) {
	if (is.fn(console && console.warn)) {
		console.warn('DotCfg: "exe" method is deprecated, call "res" method instead!');
	}
	return res(notation);
};

/*!
 * Write in scope.
 * @param notation: A object path.
 * @param value: Arguments for the object.
 * @param strategy: Arguments for the object.
 */
var setter = function (notation/*!*/, value/*!*/, strategy/*?*/) {
	var fn = !is.undef(value) && is.fn(strategy) ? strategy : this.strategy;
	return write(this.scope(), notation, value, fn);
};

/*!
 * Read scope notation.
 * @param notation: A object path.
 * @param defaultValue: A fallback value.
 */
var getter = function (notation/*!*/, defaultValue/*?*/) {
	var value = read(this.scope(), notation);
	return is.undef(value) ? defaultValue : value;
};

/*!
 * @public Methods and properties.
 */
DotCfg.prototype = {
	constructor: DotCfg,
	init: init,
	cfg: cfg,
	get: getter,
	set: setter,
	res: res,
	exe: exe,
};

/*!
 * Expose `DotCfg` and some static methods.
 * @static strategy: Default notation strategy.
 * @static assign: Default mixing strategy.
 */
DotCfg.fn = DotCfg.prototype;
DotCfg.fn.init.prototype = DotCfg.fn;
DotCfg.strategy = dotStrategyDefault;
DotCfg.assign = assignStrategy;
module.exports = DotCfg;
<commit_msg>chore: enable object as entry<commit_after>/* global window */
/* eslint-disable spaced-comment, new-cap, comma-dangle */
var is = require('./source/is');
var proxy = require('./source/proxy');
var read = require('./source/read');
var write = require('./source/write');
var assign = require('./source/assign');
var validate = require('./source/validate');
var assignStrategyDefault = require('./source/strategies/assign-default');
var dotStrategyDefault = require('./source/strategies/dot-default');

/*!
 * Public methods.
 */
var fns = 'res exe cfg get set'.split(' ');

/*!
 * Mixing behaviors.
 */
var assignStrategy = assign(assignStrategyDefault);

/*!
 * A global GUID counter for objects.
 */
var guid = 1;

/*!
 * returns a boolean indicating whether the object has
 * the specified property as own (not inherited) property
 */
var hasOwnProperty = Object.prototype.hasOwnProperty;

/*!
 * Define a local copy of `DotCfg`.
 * @param namespace: A string containing a qualified name to identify objects from.
 * @param scope: A object that have system-wide relevance.
 * @param strategy: A function that configures the input values.
 */
var DotCfg = function (namespace/*?*/, scope/*?*/, strategy/*?*/) {
	if (!is.primitive(namespace)) {
		strategy = scope;
		scope = namespace;
		namespace = undefined;
	}
	var expose = is.undef(global) ? window : global;
	var self = is.primitive(scope) ? expose : scope;
	var fn = is.fn(strategy) ? strategy : dotStrategyDefault;
	return new DotCfg.fn.init(namespace, self, fn);
};

/*!
 * Create a instance of `DotCfg`.
 * @param namespace: A string containing a qualified name to identify objects from.
 * @param scope: A object that have system-wide relevance.
 * @param strategy: A function that configures the input values.
 */
var init = function (namespace/*?*/, scope/*?*/, strategy/*?*/) {
	if (is.string(namespace)) {
		scope[namespace] = scope[namespace] || Object.create(null);
		scope = scope[namespace];
	}
	this.strategy = strategy;
	this.extends = proxy(assign(strategy), this, scope);
	this.namespace = namespace || 'dot' + guid;
	this.scope = validate(scope, this, fns);
	guid++;
	return this.scope();
};

/*!
 * Write/Read/Delete/Update a config with strategy method if needed.
 * @param notation:
 * @param value:
 * @param strategy:
 */
var cfg = function (notation/*?*/, value/*?*/, strategy/*?*/) {
	var hasArg = arguments.length > 1;
	if (!notation) {
		return this.scope(true);
	}
	if (notation === true) {
		var cp = assignStrategy({}, this.scope());
		for (var id = 0, key, acc; id < fns.length; id++) {
			key = fns[id];
			acc = '@' + key;
			if (cp[acc]) {
				cp[key] = cp[acc];
				delete cp[acc];
			} else {
				delete cp[key];
			}
		}
		return cp;
	}
	if (is.primitive(notation)) {
		return hasArg ? this.set(notation, value, strategy) : this.get(notation);
	}
	return this.extends(notation);
};

/*!
 * Read safely a key containing a function or a simple property.
 * @param notation: A object path.
 * @param ...rest: Arguments for the object.
 */
var res = function (notation/*!*/) {
	var scope = this.scope();
	var part = read(scope, notation);
	var args = Array.prototype.slice.call(arguments, 1);
	return is.fn(part) ? part.apply(scope, args) : part;
};

/*!
 * *** DEPRECATED METHOD ***
 * Read safely a key containing a function or a simple property.
 * @param notation: A object path.
 * @param ...rest: Arguments for the object.
 */
var exe = function (notation/*!*/) {
	if (is.fn(console && console.warn)) {
		console.warn('DotCfg: "exe" method is deprecated, call "res" method instead!');
	}
	return res(notation);
};

/*!
 * Write in scope.
 * @param notation: A object path.
 * @param value: Arguments for the object.
 * @param strategy: Arguments for the object.
 */
var setter = function (notation/*!*/, value/*!*/, strategy/*?*/) {
	var fn = !is.undef(value) && is.fn(strategy) ? strategy : this.strategy;
	if (is.object(notation)) {
		var context;
		for (var key in notation) {
			if (hasOwnProperty.call(notation, key)) {
				context = write(this.scope(), key, notation[key], fn);
			}
		}
		return context;
	}
	return write(this.scope(), notation, value, fn);
};

/*!
 * Read scope notation.
 * @param notation: A object path.
 * @param defaultValue: A fallback value.
 */
var getter = function (notation/*!*/, defaultValue/*?*/) {
	var value = read(this.scope(), notation);
	return is.undef(value) ? defaultValue : value;
};

/*!
 * @public Methods and properties.
 */
DotCfg.prototype = {
	constructor: DotCfg,
	init: init,
	cfg: cfg,
	get: getter,
	set: setter,
	res: res,
	exe: exe,
};

/*!
 * Expose `DotCfg` and some static methods.
 * @static strategy: Default notation strategy.
 * @static assign: Default mixing strategy.
 */
DotCfg.fn = DotCfg.prototype;
DotCfg.fn.init.prototype = DotCfg.fn;
DotCfg.strategy = dotStrategyDefault;
DotCfg.assign = assignStrategy;
module.exports = DotCfg;
<|endoftext|>