<commit_before>var fs = require('fs')
  , util = require('util')
  , define = require('cli-util').define
  , logger = require('cli-logger');

var defaults = {
  level: {
    name: '--log-level [level]',
    description: 'set the log level',
    key: 'logLevel',
    callback: function level(req, arg, value) {
      var level = parseInt(value);
      if(!isNaN(level)) value = level;
      try {
        this.log.level(value);
      }catch(e) {
        this.raise(this.errors.EUNKNOWN_LOG_LEVEL, [value], e);
      }
    }
  },
  file: {
    name: '--log-file [file]',
    description: 'redirect to log file',
    key: 'logFile',
    callback: function file(req, arg, value) {
      var logger = require('cli-logger'), scope = this;
      var streams = this.log.streams, stream;
      stream = fs.createWriteStream(value, {flags: 'a'});
      stream.once('error', function(e) {
        scope.raise(scope.errors.ELOG_FILE, [value], e);
      })
      for(var i = 0;i < streams.length;i++) {
        streams[i].stream = stream;
        streams[i].type = logger.FILE;
      }
    }
  }
}

var keys = Object.keys(defaults);

var callbacks = {};
keys.forEach(function(key) {
  callbacks[defaults[key].key] = defaults[key].callback;
})

function configure(options) {
  var i, key;
  for(i = 0;i < keys.length;i++) {
    key = keys[i];
    if(options[key] && typeof(options[key]) === 'object'
      && !Array.isArray(options[key])) {
        options[key].name = options[key].name || defaults[key].name;
        options[key].description = options[key].description
          || defaults[key].description;
        this.option(options[key]);
        this.once(defaults[key].key, function(req, arg, value) {
          callbacks[arg.key()].call(this, req, arg, value);
        })
    }
  }
}

/**
 *  Decorates the program with a logger assigned to the log
 *  property of the program.
 *
 *  @param conf A configuration to pass when initializing
 *  the logger module.
 *  @param options An object defining common log options.
 */
module.exports = function(conf, options) {
  conf = conf || this.configure().log || {};

  if(!this.configure().log) {
    this.configure().log = conf;
  }

  var scope = this;
  var bitwise = conf && conf.bitwise !== undefined ? conf.bitwise : false;
  if(conf && conf.bitwise) delete conf.bitwise;
  var log = logger(conf, bitwise);

  var ttycolor;
  try {
    ttycolor = require('ttycolor');
  }catch(e) {}
  if(conf.colors !== false && ttycolor) {

    var ansi = ttycolor.ansi;

    //console.log(ansi.color);

    // prefer a console stream if colors are enabled
    // and the logger has not been configured with custom streams
    if(log.isDefault()) {
      log.useConsoleStream();

      // prefer a default prefix that styles differently
      log.conf.prefix = (conf.prefix !== undefined)
        ? conf.prefix : function(record, tty) {
          var fmt = conf.format || '%s ⚡'
            , nm = scope.name();

          console.log('conf prefix tty: ' + tty);
          if(!tty) {
            return util.format(fmt, nm);
          }
          //console.log(
            //'default color prefixer %s',
            //ansi(util.format(fmt, nm)).normal.bg.black);
          //return ansi(util.format(fmt, nm)).normal.bg.black;
          var c = ansi(nm).normal.valueOf(tty)
            + ansi(' ⚡').normal.cyan.valueOf(tty);
          //console.log('is instance %s', c instanceof ansi.color);
          //console.dir(c);
          return c;
        }
    }
  }else{
    conf.prefix = conf.prefix !== undefined ? conf.prefix : function(record) {
      var fmt = conf.format || '%s ⚡', nm = scope.name();
      return util.format(fmt, nm);
    }
  }
  define(this, 'log', log, false);
  if(options) configure.call(this, options);
  return this;
}
<commit_msg>Remove debug statement.<commit_after>var fs = require('fs')
  , util = require('util')
  , define = require('cli-util').define
  , logger = require('cli-logger');

var defaults = {
  level: {
    name: '--log-level [level]',
    description: 'set the log level',
    key: 'logLevel',
    callback: function level(req, arg, value) {
      var level = parseInt(value);
      if(!isNaN(level)) value = level;
      try {
        this.log.level(value);
      }catch(e) {
        this.raise(this.errors.EUNKNOWN_LOG_LEVEL, [value], e);
      }
    }
  },
  file: {
    name: '--log-file [file]',
    description: 'redirect to log file',
    key: 'logFile',
    callback: function file(req, arg, value) {
      var logger = require('cli-logger'), scope = this;
      var streams = this.log.streams, stream;
      stream = fs.createWriteStream(value, {flags: 'a'});
      stream.once('error', function(e) {
        scope.raise(scope.errors.ELOG_FILE, [value], e);
      })
      for(var i = 0;i < streams.length;i++) {
        streams[i].stream = stream;
        streams[i].type = logger.FILE;
      }
    }
  }
}

var keys = Object.keys(defaults);

var callbacks = {};
keys.forEach(function(key) {
  callbacks[defaults[key].key] = defaults[key].callback;
})

function configure(options) {
  var i, key;
  for(i = 0;i < keys.length;i++) {
    key = keys[i];
    if(options[key] && typeof(options[key]) === 'object'
      && !Array.isArray(options[key])) {
        options[key].name = options[key].name || defaults[key].name;
        options[key].description = options[key].description
          || defaults[key].description;
        this.option(options[key]);
        this.once(defaults[key].key, function(req, arg, value) {
          callbacks[arg.key()].call(this, req, arg, value);
        })
    }
  }
}

/**
 *  Decorates the program with a logger assigned to the log
 *  property of the program.
 *
 *  @param conf A configuration to pass when initializing
 *  the logger module.
 *  @param options An object defining common log options.
 */
module.exports = function(conf, options) {
  conf = conf || this.configure().log || {};

  if(!this.configure().log) {
    this.configure().log = conf;
  }

  var scope = this;
  var bitwise = conf && conf.bitwise !== undefined ? conf.bitwise : false;
  if(conf && conf.bitwise) delete conf.bitwise;
  var log = logger(conf, bitwise);

  var ttycolor;
  try {
    ttycolor = require('ttycolor');
  }catch(e) {}
  if(conf.colors !== false && ttycolor) {

    var ansi = ttycolor.ansi;

    //console.log(ansi.color);

    // prefer a console stream if colors are enabled
    // and the logger has not been configured with custom streams
    if(log.isDefault()) {
      log.useConsoleStream();

      // prefer a default prefix that styles differently
      log.conf.prefix = (conf.prefix !== undefined)
        ? conf.prefix : function(record, tty) {
          var fmt = conf.format || '%s ⚡'
            , nm = scope.name();

          if(!tty) {
            return util.format(fmt, nm);
          }
          //console.log(
            //'default color prefixer %s',
            //ansi(util.format(fmt, nm)).normal.bg.black);
          //return ansi(util.format(fmt, nm)).normal.bg.black;
          var c = ansi(nm).normal.valueOf(tty)
            + ansi(' ⚡').normal.cyan.valueOf(tty);
          //console.log('is instance %s', c instanceof ansi.color);
          //console.dir(c);
          return c;
        }
    }
  }else{
    conf.prefix = conf.prefix !== undefined ? conf.prefix : function(record) {
      var fmt = conf.format || '%s ⚡', nm = scope.name();
      return util.format(fmt, nm);
    }
  }
  define(this, 'log', log, false);
  if(options) configure.call(this, options);
  return this;
}
<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    es = require('event-stream'),
    gutil = require('gulp-util'),
    glob = require('glob');

var DIRECTIVE_REGEX = /^[\/\s#]*?=\s*?((?:require|include)(?:_tree|_directory)?)\s+(.*$)/mg;

var requiredFiles = {},
    extensions = [];

module.exports = function (params) {
    var params = params || {};
    requiredFiles = {};
    extensions = [];

    if (params.extensions) {
        extensions = typeof params.extensions === 'string' ? [params.extensions] : params.extensions;
    }

    function include(file, callback) {
        if (file.isNull()) {
            return callback(null, file);
        }

        if (file.isStream()) {
            throw new gutil.PluginError('gulp-include', 'stream not supported');
        }

        if (file.isBuffer()) {
            var newText = expand(String(file.contents), file.path);
            file.contents = new Buffer(newText);
        }

        callback(null, file);
    }

    return es.map(include)
};

function expand(fileContents, filePath) {
    var regexMatch,
        matches = [],
        returnText = fileContents,
        i, j;

    DIRECTIVE_REGEX.lastIndex = 0;

    while (regexMatch = DIRECTIVE_REGEX.exec(fileContents)) {
        matches.push(regexMatch);
    }

    i = matches.length;
    while (i--) {
        var match = matches[i],
            original = match[0],
            directiveType = match[1],
            start = match.index,
            end = start + original.length,
            thisMatchText = "",
            files = globMatch(match, filePath);

        if (directiveType.indexOf("_tree") !== -1 || directiveType.indexOf("_directory") !== -1) {
            thisMatchText += original + "\n";
        }

        for (j = 0; j < files.length; j++) {
            var fileName = files[j];
            thisMatchText += expand(String(fs.readFileSync(fileName)), fileName) + "\n";
            if (directiveType.indexOf('require') !== -1 || directiveType.indexOf('include') !== -1) requiredFiles[fileName] = true;
        }

        thisMatchText = thisMatchText || original;

        returnText = replaceStringByIndices(returnText, start, end, thisMatchText);
    }

    return returnText ? returnText : fileContents;
}

function globMatch(match, filePath) {
    var directiveType = match[1],
        relativeFilePath = match[2],
        files = [],
        globs = [],
        negations = [];

    if (directiveType.indexOf('_tree') !== -1) {
        relativeFilePath = relativeFilePath.concat('/**/*');
        directiveType = directiveType.replace('_tree', '');
    }

    if (directiveType.indexOf('_directory') !== -1) {
        relativeFilePath = relativeFilePath.concat('/*');
        directiveType = directiveType.replace('_directory', '');
    }

    if (directiveType === 'require' || directiveType === 'include') {
        if (relativeFilePath.charAt(0) === '[') {
            relativeFilePath = eval(relativeFilePath);
            for (var i = 0; i < relativeFilePath.length; i++) {
                if (relativeFilePath[i].charAt(0) === '!') {
                    negations.push(relativeFilePath[i].slice(1))
                } else {
                    globs.push(relativeFilePath[i])
                }
            }
        } else {
            globs.push(relativeFilePath);
        }

        for (var i = 0; i < globs.length; i++) {
            var globFiles = _internalGlob(globs[i], filePath);
            files = union(files, globFiles);
        }

        for (var i = 0; i < negations.length; i++) {
            var negationFiles = _internalGlob(negations[i].substring(1), filePath);
            files = difference(files, negationFiles);
        }
    }

    return files;
}

function _internalGlob(thisGlob, filePath) {
    var folderPath = path.dirname(filePath),
        fullPath = path.join(folderPath, thisGlob.replace(/['"]/g, '')),
        files;

    files = glob.sync(fullPath, {
        mark: true
    });

    files = files.filter(function (fileName) {
        var slashSplit = fileName.split(/[\\\/]/),
            thisExtension = fileName.split('.').pop();

        //Ignore directories
        if (slashSplit.pop() === '')
            return false;

        //Check for allowable extensions if specified, otherwise allow all extensions
        if (extensions.length > 0 && extensions.indexOf(thisExtension) === -1) {
            return false;
        }

        return true;

    });

    return files;
}

function replaceStringByIndices(string, start, end, replacement) {
    return string.substring(0, start) + replacement + string.substring(end);
}

//We can't use lo-dash's union function because it wouldn't support this: ["*.js", "app.js"], which requires app.js to come last
function union(arr1, arr2) {
    if (arr1.length == 0) return arr2;
    var index;
    for (var i = 0; i < arr2.length; i++) {
        if ((index = arr1.indexOf(arr2[i])) !== -1) arr1.splice(index, 1)
    }
    return arr1.concat(arr2);
}

function difference(arr1, arr2) {
    var index;
    for (var i = 0; i < arr2.length; i++) {
        while ((index = arr1.indexOf(arr2[i])) !== -1) {
            arr1.splice(index, 1)
        }
    }
    return arr1;
}<commit_msg>linting and code style<commit_after>var fs = require('fs'),
    path = require('path'),
    es = require('event-stream'),
    gutil = require('gulp-util'),
    glob = require('glob');

var DIRECTIVE_REGEX = /^[\/\s#]*?=\s*?((?:require|include)(?:_tree|_directory)?)\s+(.*$)/mg;

var requiredFiles = {},
    extensions = [];

module.exports = function (params) {
    var params = params || {};
    requiredFiles = {};
    extensions = [];

    if (params.extensions) {
        extensions = typeof params.extensions === 'string' ? [params.extensions] : params.extensions;
    }

    function include(file, callback) {
        if (file.isNull()) {
            return callback(null, file);
        }

        if (file.isStream()) {
            throw new gutil.PluginError('gulp-include', 'stream not supported');
        }

        if (file.isBuffer()) {
            var newText = expand(String(file.contents), file.path);
            file.contents = new Buffer(newText);
        }

        callback(null, file);
    }

    return es.map(include)
};

function expand(fileContents, filePath) {
    var regexMatch,
        matches = [],
        returnText = fileContents,
        i, j;

    DIRECTIVE_REGEX.lastIndex = 0;

    while (regexMatch = DIRECTIVE_REGEX.exec(fileContents)) {
        matches.push(regexMatch);
    }

    i = matches.length;
    while (i--) {
        var match = matches[i],
            original = match[0],
            directiveType = match[1],
            start = match.index,
            end = start + original.length,
            thisMatchText = "",
            files = globMatch(match, filePath);

        if (directiveType.indexOf("_tree") !== -1 || directiveType.indexOf("_directory") !== -1) {
            thisMatchText += original + "\n";
        }

        for (j = 0; j < files.length; j++) {
            var fileName = files[j];
            thisMatchText += expand(String(fs.readFileSync(fileName)), fileName) + "\n";
            if (directiveType.indexOf('require') !== -1 || directiveType.indexOf('include') !== -1) {
                requiredFiles[fileName] = true;
            }
        }

        thisMatchText = thisMatchText || original;

        returnText = replaceStringByIndices(returnText, start, end, thisMatchText);
    }

    return returnText ? returnText : fileContents;
}

function globMatch(match, filePath) {
    var directiveType = match[1],
        relativeFilePath = match[2],
        files = [],
        globs = [],
        negations = [];

    if (directiveType.indexOf('_tree') !== -1) {
        relativeFilePath = relativeFilePath.concat('/**/*');
        directiveType = directiveType.replace('_tree', '');
    }

    if (directiveType.indexOf('_directory') !== -1) {
        relativeFilePath = relativeFilePath.concat('/*');
        directiveType = directiveType.replace('_directory', '');
    }

    if (directiveType === 'require' || directiveType === 'include') {
        if (relativeFilePath.charAt(0) === '[') {
            relativeFilePath = eval(relativeFilePath);
            for (var i = 0; i < relativeFilePath.length; i++) {
                if (relativeFilePath[i].charAt(0) === '!') {
                    negations.push(relativeFilePath[i].slice(1))
                } else {
                    globs.push(relativeFilePath[i]);
                }
            }
        } else {
            globs.push(relativeFilePath);
        }

        for (var i = 0; i < globs.length; i++) {
            var globFiles = _internalGlob(globs[i], filePath);
            files = union(files, globFiles);
        }

        for (var i = 0; i < negations.length; i++) {
            var negationFiles = _internalGlob(negations[i].substring(1), filePath);
            files = difference(files, negationFiles);
        }
    }

    return files;
}

function _internalGlob(thisGlob, filePath) {
    var folderPath = path.dirname(filePath),
        fullPath = path.join(folderPath, thisGlob.replace(/['"]/g, '')),
        files;

    files = glob.sync(fullPath, {
        mark: true
    });

    files = files.filter(function (fileName) {
        var slashSplit = fileName.split(/[\\\/]/),
            thisExtension = fileName.split('.').pop();

        //Ignore directories
        if (slashSplit.pop() === '')
            return false;

        //Check for allowable extensions if specified, otherwise allow all extensions
        if (extensions.length > 0 && extensions.indexOf(thisExtension) === -1) {
            return false;
        }

        return true;

    });

    return files;
}

function replaceStringByIndices(string, start, end, replacement) {
    return string.substring(0, start) + replacement + string.substring(end);
}

//We can't use lo-dash's union function because it wouldn't support this: ["*.js", "app.js"], which requires app.js to come last
function union(arr1, arr2) {
    if (arr1.length == 0) {
        return arr2;
    }

    var index;
    for (var i = 0; i < arr2.length; i++) {
        if ((index = arr1.indexOf(arr2[i])) !== -1) {
            arr1.splice(index, 1);
        }
    }
    return arr1.concat(arr2);
}

function difference(arr1, arr2) {
    var index;
    for (var i = 0; i < arr2.length; i++) {
        while ((index = arr1.indexOf(arr2[i])) !== -1) {
            arr1.splice(index, 1);
        }
    }
    return arr1;
}<|endoftext|>


<commit_before>'use strict';
require('dotenv').config();

const bot = require('./lib/bot.js');

// seperate skills into individual functions
const welcome = require('./skills/welcome.js');
const welcomeme = require('./skills/welcomeme.js');
const uptime = require('./skills/uptime.js');

// consolidate ways for the bot to be mentioned
const mention = ['direct_message', 'direct_mention', 'mention'];

// define when each skill is called
bot.on('team_join', welcome);
bot.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'], mention, uptime);
bot.hears(['welcome', 'welcome me', 'help'], mention, welcomeme);
bot.hears('', mention, (bot, message) => {
  bot.reply(message, 'I only understand a few things.  You can say "welcome" or "uptime"');
});
<commit_msg>minor punctuation change.<commit_after>'use strict';
require('dotenv').config();

const bot = require('./lib/bot.js');

// seperate skills into individual functions
const welcome = require('./skills/welcome.js');
const welcomeme = require('./skills/welcomeme.js');
const uptime = require('./skills/uptime.js');

// consolidate ways for the bot to be mentioned
const mention = ['direct_message', 'direct_mention', 'mention'];

// define when each skill is called
bot.on('team_join', welcome);
bot.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'], mention, uptime);
bot.hears(['welcome', 'welcome me', 'help'], mention, welcomeme);
bot.hears('', mention, (bot, message) => {
  bot.reply(message, 'I only understand a few things.  You can say "welcome" or "uptime".');
});
<|endoftext|>


<commit_before>const ALLOWED_MAGIC_NUMBERS  = [-1, 0, 1, 2, 3, 10, 100, 1000];
const MAX_ALLOWED_COMPLEXITY = 5;
const MAX_LINE_LENGTH        = 150;
/*
 fix --> indicates that rule can be "auto-fixed" by ESLint
*/
module.exports = {
    env: {
        // node: true,
        // es6: true,
        browser: true
    },
    globals: {
        Promise: true,
        module: true,
        exports: true
    },
    plugins: [
        'compat',
        'promise'
    ],
    rules: {
        'compat/compat': ['error'],
        'promise/param-names': ['warn'],
        'promise/always-return': ['error'],
        'promise/catch-or-return': ['error'],
        'promise/no-return-in-finally': ['warn'],
 /*fix*/'arrow-body-style': ['error', 'as-needed'],
 /*fix*/'arrow-parens': ['error', 'as-needed'],
 /*fix*/'array-bracket-spacing': ['warn'],
        'block-scoped-var': ['error'],
        'brace-style': ['warn', '1tbs', {allowSingleLine: true}],
        'camelcase': ['warn'],
        'comma-dangle': ['warn', 'never'],
 /*fix*/'comma-spacing': ['warn'],
        'comma-style': ['warn'],
        'complexity': ['warn', MAX_ALLOWED_COMPLEXITY],
 /*fix*/'curly': ['error'],
        'default-case': ['error'],
 /*fix*/'dot-location': ['error', 'property'],
 /*fix*/'dot-notation': ['warn'],
        'eqeqeq': ['error'],
        'guard-for-in': ['error'],
 /*fix*/'indent': ['warn', 4, {SwitchCase: 1}],
 /*fix*/'key-spacing': ['warn', {beforeColon: false, afterColon: true, mode: 'minimum'}],
 /*fix*/'keyword-spacing': ['warn'],
 /*fix*/'linebreak-style': ['warn', 'unix'],
        'max-depth': ['warn', 3],
        'max-len': ['warn', {code: MAX_LINE_LENGTH, comments: 200}],
        'max-nested-callbacks': ['warn', 4],
        'max-params': ['warn', 5],
        'new-cap': ['warn'],
        'no-alert': ['warn'],
        'no-array-constructor': ['warn'],
        'no-console': ['warn'],
        'no-constant-condition': ['error'],
        'no-const-assign': ['error'],
 /*fix*/'no-debugger': ['error'],
        'no-dupe-keys': ['error'],
 /*fix*/'no-extra-semi': ['error'],
        'no-empty': ['warn'],
        'no-empty-pattern': ['error'],
        'no-eval': ['error'],
        'no-fallthrough': ['error'],
        'no-floating-decimal': ['warn'],
        'no-implied-eval': ['error'],
        'no-irregular-whitespace': ['error'],
        'no-magic-numbers': ['warn', {ignore: ALLOWED_MAGIC_NUMBERS}],
        'no-multiple-empty-lines': ['warn', {max: 1}],
 /*fix*/'no-multi-spaces': ['warn', {exceptions: {VariableDeclarator: true, Property: true}}],
        'no-redeclare': ['error'],
 /*fix*/'no-spaced-func': ['warn'],
 /*fix*/'no-trailing-spaces': ['warn'],
        'no-undef': ['error', {typeof: true}],
        'no-unexpected-multiline': ['error'],
        'no-unreachable': ['error'],
        'no-unused-vars': ['error'],
        'no-use-before-define': ['error', {functions: false}],
 /*fix*/'no-var': ['error'],
        'no-with': ['error'],
 /*fix*/'object-shorthand': ['error', 'properties'],
        'one-var': ['warn', 'never'],
        'one-var-declaration-per-line': ['warn'],
 /*fix*/'prefer-const': ['error'],
        'prefer-destructuring': ['error'],
        'prefer-rest-params': ['warn'],
 /*fix*/'prefer-spread': ['error'],
 /*fix*/'prefer-template': ['error'],
 /*fix*/'quote-props': ['warn', 'as-needed'],
 /*fix*/'quotes': ['warn', 'single'],
        'radix': ['warn'],
 /*fix*/'rest-spread-spacing': ['error', 'never'],
 /*fix*/'semi': ['error', 'always'],
 /*fix*/'space-before-blocks': ['warn'],
 /*fix*/'space-before-function-paren': ['warn', 'never'],
 /*fix*/'space-in-parens': ['warn'],
 /*fix*/'space-infix-ops': ['warn'],
 /*fix*/'space-unary-ops': ['warn'],
        'strict': ['error'],
        'valid-jsdoc': ['error'],
        'valid-typeof': ['error'],
 /*fix*/'wrap-iife': ['warn'],
        'yoda': ['warn']
    }
};
<commit_msg>Add fix annotation to strict rule<commit_after>const ALLOWED_MAGIC_NUMBERS  = [-1, 0, 1, 2, 3, 10, 100, 1000];
const MAX_ALLOWED_COMPLEXITY = 5;
const MAX_LINE_LENGTH        = 150;
/*
 fix --> indicates that rule can be "auto-fixed" by ESLint
*/
module.exports = {
    env: {
        // node: true,
        // es6: true,
        browser: true
    },
    globals: {
        Promise: true,
        module: true,
        exports: true
    },
    plugins: [
        'compat',
        'promise'
    ],
    rules: {
        'compat/compat': ['error'],
        'promise/param-names': ['warn'],
        'promise/always-return': ['error'],
        'promise/catch-or-return': ['error'],
        'promise/no-return-in-finally': ['warn'],
 /*fix*/'arrow-body-style': ['error', 'as-needed'],
 /*fix*/'arrow-parens': ['error', 'as-needed'],
 /*fix*/'array-bracket-spacing': ['warn'],
        'block-scoped-var': ['error'],
        'brace-style': ['warn', '1tbs', {allowSingleLine: true}],
        'camelcase': ['warn'],
        'comma-dangle': ['warn', 'never'],
 /*fix*/'comma-spacing': ['warn'],
        'comma-style': ['warn'],
        'complexity': ['warn', MAX_ALLOWED_COMPLEXITY],
 /*fix*/'curly': ['error'],
        'default-case': ['error'],
 /*fix*/'dot-location': ['error', 'property'],
 /*fix*/'dot-notation': ['warn'],
        'eqeqeq': ['error'],
        'guard-for-in': ['error'],
 /*fix*/'indent': ['warn', 4, {SwitchCase: 1}],
 /*fix*/'key-spacing': ['warn', {beforeColon: false, afterColon: true, mode: 'minimum'}],
 /*fix*/'keyword-spacing': ['warn'],
 /*fix*/'linebreak-style': ['warn', 'unix'],
        'max-depth': ['warn', 3],
        'max-len': ['warn', {code: MAX_LINE_LENGTH, comments: 200}],
        'max-nested-callbacks': ['warn', 4],
        'max-params': ['warn', 5],
        'new-cap': ['warn'],
        'no-alert': ['warn'],
        'no-array-constructor': ['warn'],
        'no-console': ['warn'],
        'no-constant-condition': ['error'],
        'no-const-assign': ['error'],
 /*fix*/'no-debugger': ['error'],
        'no-dupe-keys': ['error'],
 /*fix*/'no-extra-semi': ['error'],
        'no-empty': ['warn'],
        'no-empty-pattern': ['error'],
        'no-eval': ['error'],
        'no-fallthrough': ['error'],
        'no-floating-decimal': ['warn'],
        'no-implied-eval': ['error'],
        'no-irregular-whitespace': ['error'],
        'no-magic-numbers': ['warn', {ignore: ALLOWED_MAGIC_NUMBERS}],
        'no-multiple-empty-lines': ['warn', {max: 1}],
 /*fix*/'no-multi-spaces': ['warn', {exceptions: {VariableDeclarator: true, Property: true}}],
        'no-redeclare': ['error'],
 /*fix*/'no-spaced-func': ['warn'],
 /*fix*/'no-trailing-spaces': ['warn'],
        'no-undef': ['error', {typeof: true}],
        'no-unexpected-multiline': ['error'],
        'no-unreachable': ['error'],
        'no-unused-vars': ['error'],
        'no-use-before-define': ['error', {functions: false}],
 /*fix*/'no-var': ['error'],
        'no-with': ['error'],
 /*fix*/'object-shorthand': ['error', 'properties'],
        'one-var': ['warn', 'never'],
        'one-var-declaration-per-line': ['warn'],
 /*fix*/'prefer-const': ['error'],
        'prefer-destructuring': ['error'],
        'prefer-rest-params': ['warn'],
 /*fix*/'prefer-spread': ['error'],
 /*fix*/'prefer-template': ['error'],
 /*fix*/'quote-props': ['warn', 'as-needed'],
 /*fix*/'quotes': ['warn', 'single'],
        'radix': ['warn'],
 /*fix*/'rest-spread-spacing': ['error', 'never'],
 /*fix*/'semi': ['error', 'always'],
 /*fix*/'space-before-blocks': ['warn'],
 /*fix*/'space-before-function-paren': ['warn', 'never'],
 /*fix*/'space-in-parens': ['warn'],
 /*fix*/'space-infix-ops': ['warn'],
 /*fix*/'space-unary-ops': ['warn'],
 /*fix*/'strict': ['error'],
        'valid-jsdoc': ['error'],
        'valid-typeof': ['error'],
 /*fix*/'wrap-iife': ['warn'],
        'yoda': ['warn']
    }
};
<|endoftext|>


<commit_before>/**
 * @license shallow-diff https://github.com/cosmosio/shallow-diff
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2015 Olivier Scherrer <pode.fr@gmail.com>
 */
"use strict";

var loop = require("simple-loop");

/**
 * Make a diff between two objects
 * @param {Array/Object} base the base object
 * @param {Array/Object} compared the object to compare the base with
 * @example:
 *  With objects:
 *
 *  base = {a:1, b:2, c:3, d:4, f:6}
 *  compared = {a:1, b:20, d: 4, e: 5}
 *  will return :
 *  {
 *      unchanged: ["a", "d"],
 *      updated: ["b"],
 *      deleted: ["f"],
 *      added: ["e"]
 *  }
 *
 * It also works with Arrays:
 *
 *  base = [10, 20, 30]
 *  compared = [15, 20]
 *  will return :
 *  {
 *      unchanged: [1],
 *      updated: [0],
 *      deleted: [2],
 *      added: []
 *  }
 *
 * @returns object
 */
module.exports = function shallowDiff(base, compared) {
    if (typeof base != "object") throw new TypeError("shallow-diff: " +
      "the first object to compare with shallowDiff needs to be an object"
    );
    if (typeof compared != "object") throw new TypeError("shallow-diff: " +
      "the second object to compare with shallowDiff needs to be an object"
    );

    var unchanged = [],
        updated = [],
        deleted = [],
        added = [];

    // Loop through the compared object
    loop(compared, function(value, idx) {
        // To get the added items
        if (!(idx in base)) {
            added.push(idx);

        // The updated items
        } else if (value !== base[idx]) {
            updated.push(idx);

        // And the unchanged
        } else if (value === base[idx]) {
            unchanged.push(idx);
        }
    });

    // Loop through the before object
    loop(base, function(value, idx) {
        // To get the deleted items
        if (!(idx in compared)) {
            deleted.push(idx);
        }
    });

    return {
        updated: updated,
        unchanged: unchanged,
        added: added,
        deleted: deleted
    };
};
<commit_msg>Re introduce an assert function<commit_after>/**
 * @license shallow-diff https://github.com/cosmosio/shallow-diff
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2015 Olivier Scherrer <pode.fr@gmail.com>
 */
"use strict";

function assert(assertion, error) {
    if (assertion) {
        throw new TypeError("simple-loop: " + error);
    }
}

var loop = require("simple-loop");

/**
 * Make a diff between two objects
 * @param {Array/Object} base the base object
 * @param {Array/Object} compared the object to compare the base with
 * @example:
 *  With objects:
 *
 *  base = {a:1, b:2, c:3, d:4, f:6}
 *  compared = {a:1, b:20, d: 4, e: 5}
 *  will return :
 *  {
 *      unchanged: ["a", "d"],
 *      updated: ["b"],
 *      deleted: ["f"],
 *      added: ["e"]
 *  }
 *
 * It also works with Arrays:
 *
 *  base = [10, 20, 30]
 *  compared = [15, 20]
 *  will return :
 *  {
 *      unchanged: [1],
 *      updated: [0],
 *      deleted: [2],
 *      added: []
 *  }
 *
 * @returns object
 */
module.exports = function shallowDiff(base, compared) {
    assert(typeof base != "object", "the first object to compare with shallowDiff needs to be an object");
    assert(typeof compared != "object", "the second object to compare with shallowDiff needs to be an object");

    var unchanged = [],
        updated = [],
        deleted = [],
        added = [];

    // Loop through the compared object
    loop(compared, function(value, idx) {
        // To get the added items
        if (!(idx in base)) {
            added.push(idx);

        // The updated items
        } else if (value !== base[idx]) {
            updated.push(idx);

        // And the unchanged
        } else if (value === base[idx]) {
            unchanged.push(idx);
        }
    });

    // Loop through the before object
    loop(base, function(value, idx) {
        // To get the deleted items
        if (!(idx in compared)) {
            deleted.push(idx);
        }
    });

    return {
        updated: updated,
        unchanged: unchanged,
        added: added,
        deleted: deleted
    };
};
<|endoftext|>


<commit_before>'use strict';

var count    = require('es5-ext/lib/Object/count');
var validate = require('es5-ext/lib/Object/valid-value');
var parse    = require('url').parse;
var webmake  = require('webmake');
var encode   = require('entities').encodeXML;

var stringify = JSON.stringify;

module.exports = function (config/*, options*/) {
  var options = Object(arguments[1]);
  var log = (options.log == null) ? true : options.log;
  delete options.log;
  config = Object(validate(config));

  if (options.cache == null) options.cache = true;
  return function webmakeMiddleware(req, res, next) {
    var path = parse(req.url).pathname;
    var promise;
    if (config[path] == null) {
      next();
      return;
    }

    promise = webmake(config[path], options, function (err, src) {
      var msg, modulesSize, packagesSize;
      if (err) {
        // fail loudly on the cli and in the browser
        console.error("Webmake error: " + err.message);
        res.writeHead(500);
        res.end('document.write(\'

Could not generate '
          + path + '

'
          + stringify(encode(err.message)).slice(1, -1).replace(/'/g, '\\\'')
          + '

\');');
        return;
      }

      res.writeHead(200, {
        'Content-Type': 'text/javascript; charset=utf-8',
        'Cache-Control': 'no-cache'
      });

      res.end(src);
      if (log) {
        modulesSize = promise.parser.modulesFiles.length;
        packagesSize = count(promise.parser.packages);
        msg = "Webmake OK [" +  modulesSize + " module";
        if (modulesSize > 1) msg += "s";
        msg += " from " + packagesSize + " package";
        if (packagesSize > 1) msg += "s";
        console.log(msg + " in " + (promise.time / 1000).toFixed(2) + "s] -> " + req.url);
      }
    });
  };
};
<commit_msg>Pass error message generator with 200 status<commit_after>'use strict';

var count    = require('es5-ext/lib/Object/count');
var validate = require('es5-ext/lib/Object/valid-value');
var parse    = require('url').parse;
var webmake  = require('webmake');
var encode   = require('entities').encodeXML;

var stringify = JSON.stringify;

module.exports = function (config/*, options*/) {
  var options = Object(arguments[1]);
  var log = (options.log == null) ? true : options.log;
  delete options.log;
  config = Object(validate(config));

  if (options.cache == null) options.cache = true;
  return function webmakeMiddleware(req, res, next) {
    var path = parse(req.url).pathname;
    var promise;
    if (config[path] == null) {
      next();
      return;
    }

    promise = webmake(config[path], options, function (err, src) {
      var msg, modulesSize, packagesSize;
      if (err) {
        // fail loudly on the cli and in the browser
        console.error("Webmake error: " + err.message);
        res.writeHead(200);
        res.end('document.write(\'

Could not generate '
          + path + '

'
          + stringify(encode(err.message)).slice(1, -1).replace(/'/g, '\\\'')
          + '

\');');
        return;
      }

      res.writeHead(200, {
        'Content-Type': 'text/javascript; charset=utf-8',
        'Cache-Control': 'no-cache'
      });

      res.end(src);
      if (log) {
        modulesSize = promise.parser.modulesFiles.length;
        packagesSize = count(promise.parser.packages);
        msg = "Webmake OK [" +  modulesSize + " module";
        if (modulesSize > 1) msg += "s";
        msg += " from " + packagesSize + " package";
        if (packagesSize > 1) msg += "s";
        console.log(msg + " in " + (promise.time / 1000).toFixed(2) + "s] -> " + req.url);
      }
    });
  };
};
<|endoftext|>


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

var jsdom = require('jsdom');
var _ = require('underscore');

var b = function(opts, tests) {
    if (arguments.length == 1) {
        tests = opts;
        opts = {
            syntaxCheck: true
        }
    }

    var setUp = tests.setUp || function(cb) { cb() };
    var tearDown = tests.tearDown || function(cb) { cb() };

    // allow setting html per test object
    if (tests.html) {
        b.html(tests.html);
    }
    var html = b._html;

    // allow extra reqs for this test object
    var additionalReqs = tests.requires || [];
    var reqs = b._reqs;

    // allow setting of provides when setting up test obj
    if (tests.provide) {
        b.provide(tests.provide);
    }

    // clean up nodeunit-b properties
    ['requires', 'provide', 'html'].forEach(function(p) { delete tests[p] });

    // preprocess local reqs to check for syntax errors
    if (opts.syntaxCheck) {
        _(reqs).each(function(filename) {
            var code = fs.readFileSync(filename).toString();

            try {
                vm.createScript(code);
            } catch (e) {
                throw 'Syntax error in local file: ' + filename + ': ' + e;
            }
        });
    }

    tests.setUp = function(cb) {
        var testcase = this;
        jsdom.env(html, _(reqs).union(additionalReqs), function(err, window) {
            testcase.window = window;
            setUp.call(testcase, cb, window, b);
        });
    };

    tests.tearDown = function(cb) {
        var wrapped_cb = function() {
            // clear provides each time through so they're clear after the last
            // run.
            b.setProvides([]);
            cb();
        };
        tearDown.call(this, wrapped_cb, this.window, b);
    };

    // set up test methods
    _(tests).chain()
        .functions()
        .filter(function(funcName) {
            return funcName.match(/^test/i);
        })
        .each(function(funcName) {
            var func = tests[funcName];
            tests[funcName] = function(test) {
                var w = this.window;
                var args = [test, w];
                var provide_args = b.getProvides().map(function(p) { return w[p] });
                return func.apply(this, args.concat(provide_args));
            };
        });

    return tests;
};

b.provide = function() {
    var props = _(arguments).toArray();
    b._provides = _(b._provides).union(props);

    return b;
};
b.getProvides = function() {
    return b._provides;
};
b.setProvides = function(propertyList) {
    b._provides = propertyList;
};
b._provides = [];

b._root = './';
b.setRequireRoot = function() {
    var args = _.toArray(arguments);
    b._root = path.join.apply(path, args);

    return b;
};

b._html = '';
b.html = function(html) {
    b._html = html;

    return b;
};

b._reqs = [];
b.require = function(reqs) {
    if (_(reqs).isString()) {
        reqs = [reqs];
    }
    _(reqs).each(function(req) {
        if (!req.match(new RegExp('^'+path.sep))) {
            req = path.join(b._root, req);
        }
        b._reqs.push(req);
    });

    return b;
};

module.exports = b;
<commit_msg>use extend<commit_after>var path = require('path');
var fs = require('fs');
var vm = require('vm');

var jsdom = require('jsdom');
var _ = require('underscore');

var b = function(opts, tests) {
    if (arguments.length == 1) {
        tests = opts;
        opts = {
            syntaxCheck: true
        }
    }

    var setUp = tests.setUp || function(cb) { cb() };
    var tearDown = tests.tearDown || function(cb) { cb() };

    // allow setting html per test object
    if (tests.html) {
        b.html(tests.html);
    }
    var html = b._html;

    // allow extra reqs for this test object
    var additionalReqs = tests.requires || [];
    var reqs = b._reqs;

    // allow setting of provides when setting up test obj
    if (tests.provide) {
        b.provide(tests.provide);
    }

    // clean up nodeunit-b properties
    ['requires', 'provide', 'html'].forEach(function(p) { delete tests[p] });

    // preprocess local reqs to check for syntax errors
    if (opts.syntaxCheck) {
        _(reqs).each(function(filename) {
            var code = fs.readFileSync(filename).toString();

            try {
                vm.createScript(code);
            } catch (e) {
                throw 'Syntax error in local file: ' + filename + ': ' + e;
            }
        });
    }

    tests.setUp = function(cb) {
        var testcase = this;
        jsdom.env(html, _(reqs).union(additionalReqs), function(err, window) {
            testcase.window = window;
            setUp.call(testcase, cb, window, b);
        });
    };

    tests.tearDown = function(cb) {
        var wrapped_cb = function() {
            // clear provides each time through so they're clear after the last
            // run.
            b.setProvides([]);
            cb();
        };
        tearDown.call(this, wrapped_cb, this.window, b);
    };

    // set up test methods
    _(tests).chain()
        .functions()
        .filter(function(funcName) {
            return funcName.match(/^test/i);
        })
        .each(function(funcName) {
            var func = tests[funcName];
            tests[funcName] = function(test) {
                var w = this.window;
                var args = [test, w];
                var provide_args = b.getProvides().map(function(p) { return w[p] });
                return func.apply(this, args.concat(provide_args));
            };
        });

    return tests;
};

_(b).extend({
    provides: [],
    provide: function() {
        b.provides = _(b.provides).union( _(arguments).toArray() );
        return b;
    },

    root: './',
    setRequireRoot: function() {
        b.root = path.join.apply(path, _(arguments).toArray());
        return b;
    },
    reqs: [],
    require: function(reqs) {
        if (_(reqs).isString()) { reqs = [reqs]; }
        _(reqs).each(function(req) {
            if (!req.match(new RegExp('^'+path.sep))) {
                req = path.join(b.root, req);
            }
            b._reqs.push(req);
        });

        return b;
    },
    _html = '',
});

Object.defineProperty(b, 'html', {
    get: function() { return this._html },
    set: function(html) { this._html = html; return b }
});

module.exports = b;
<|endoftext|>


<commit_before>'use strict';

var MONTH_NAMES = ["january", "february", "march",
                   "april",   "may",      "june",
                   "july",    "august",   "september",
                   "october", "november", "december"];

var DAY_NAMES = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

exports = module.exports = function parse(str, usa) {
  var now = new Date();

  str = str.trim().toLowerCase();

  return parseNearbyDays(str, now) ||
         parseLastThisNext(str, now) ||
         parseNumberDate(str, usa) ||
         parseNumberDateShortYear(str, usa, 80) ||
         parseWordyDate(str, now) ||
         parseIso8601Date(str);
};

var NUMBER              = /^[0-9]+$/;
var NUMBER_WITH_ORDINAL = /^([0-9]+)(st|nd|rd|th)?$/;
var NUMBER_DATE         = /^(3[0-1]|[1-2][0-9]|0?[1-9])[,\|\\\/\-\. ]+(1[0-2]|0?[1-9])[,\|\\\/\-\. ]+([0-9]{4})$/;
var NUMBER_DATE_USA     = /^(1[0-2]|0?[1-9])[,\|\\\/\-\. ]+(3[0-1]|[1-2][0-9]|0?[1-9])[,\|\\\/\-\. ]+([0-9]{4})$/;
var NUMBER_DATE_SHORT_YEAR         = /^(3[0-1]|[1-2][0-9]|0?[1-9])[,\|\\\/\-\. ]+(1[0-2]|0?[1-9])[,\|\\\/\-\. ]+([0-9]{2})$/;
var NUMBER_DATE_SHORT_YEAR_USA     = /^(1[0-2]|0?[1-9])[,\|\\\/\-\. ]+(3[0-1]|[1-2][0-9]|0?[1-9])[,\|\\\/\-\. ]+([0-9]{2})$/;
var ISO_8601_DATE       = /^([0-9]{4})-?(1[0-2]|0?[1-9])-?(3[0-1]|[1-2][0-9]|0?[1-9])$/;

function addDays(now, numberOfDays) {
  var result = new Date(now * 1 + numberOfDays * 60 * 60 * 24 * 1000);
  return date(result.getFullYear(), result.getMonth(), result.getDate());
}

exports.parseNearbyDays = parseNearbyDays;
function parseNearbyDays(string, now) {
  if (string == 'today') {
    return date(now.getFullYear(), now.getMonth(), now.getDate());;
  } else if (string == 'yesterday') {
    return addDays(now, -1);
  } else if (string == 'tomorrow') {
    return addDays(now, +1);
  } else {
    return null;
  }
}

exports.parseLastThisNext = parseLastThisNext;
function parseLastThisNext(string, now) {
  var tokens = string.split(/[,\s]+/);

  if (['last', 'this', 'next'].indexOf(tokens[0]) >= 0 &&
      DAY_NAMES.indexOf(tokens[1]) >= 0 &&
      tokens.length === 2) {
    var dayDiff = DAY_NAMES.indexOf(tokens[1]) - now.getDay();
    if (dayDiff < 0) dayDiff += 7;

    if (tokens[0] === 'last') return addDays(now, dayDiff - 7);
    if (tokens[0] === 'this') return addDays(now, dayDiff);
    if (tokens[0] === 'next') return addDays(now, dayDiff + 7);
  } else {
    return null;
  }
}

exports.parseNumberDate = parseNumberDate;
function parseNumberDate(str, usa) {
  var match = usa ? NUMBER_DATE_USA.exec(str) : NUMBER_DATE.exec(str);
  if (match) {
    return usa ? date(+match[3], match[1] - 1, +match[2]) : date(+match[3], match[2] - 1, +match[1]);
  } else {
    return null;
  }
}

exports.parseNumberDateShortYear = parseNumberDateShortYear;
function parseNumberDateShortYear(str, usa, cutoff) {
  var match = usa ? NUMBER_DATE_SHORT_YEAR_USA.exec(str) : NUMBER_DATE_SHORT_YEAR.exec(str);
  if (match) {
    var year = (+match[3]);
    if (year > cutoff) year += 1900;
    else year += 2000;
    return usa ? date(year, match[1] - 1, +match[2]) : date(year, match[2] - 1, +match[1]);
  } else {
    return null;
  }
}

exports.parseWordyDate = parseWordyDate;
function parseWordyDate(string, today) {
  var tokens = string.split(/[,\s]+/);
  if (tokens.length >= 2) {
    var match;
    if (match = tokens[0].match(NUMBER_WITH_ORDINAL)) {
      return parseWordyDateParts(match[1], tokens[1], tokens[2], today);
    } else if (match = tokens[1].match(NUMBER_WITH_ORDINAL)) {
      return parseWordyDateParts(match[1], tokens[0], tokens[2], today);
    } else {
      return null;
    }
  }
}

function parseWordyDateParts(rawDay, rawMonth, rawYear, today) {
  var day = +rawDay;
  var month = monthFromName(rawMonth);
  var year;

  if (rawYear)
    year = rawYear.match(NUMBER) ? rawYear * 1 : null;
  else
    year = today.getFullYear();

  if (year < 100 && year >= 80) year += 1900;
  if (year < 100) year += 2000;

  if (!(day && month !== null && year))
    return null;

  return date(year, month, day);
}

function parseIso8601Date(string) {
  var match;
  if (match = ISO_8601_DATE.exec(string)) {
    return date(+match[1], match[2] - 1, +match[3]);
  } else {
    return null;
  }
}

var monthAbreviations = MONTH_NAMES.map(function (name) { return name.substr(0, 3); });
exports.monthFromName = monthFromName;
function monthFromName(month) {
  var monthIndex = month.length === 3 ? monthAbreviations.indexOf(month) : MONTH_NAMES.indexOf(month);
  return monthIndex >= 0 ? monthIndex : null;
}

exports.date = date;
function date(year, month, day) {
  month++;
  if (month > 11 || month < 0) return null;
  if (day > 31 || day < 1) return null;
  if (month < 10) month = '0' + month;
  if (day < 10) day = '0' + day;

  return year + '-' + month + '-' + day;
}
function getISOString(year, month, day) {
  month++;
  if (month < 10) month = '0' + month;
  if (day < 10) day = '0' + day;
  return year + '-' + month + '-' + day + 'T00:00:00.000Z';
}
<commit_msg>Fix for dates in december<commit_after>'use strict';

var MONTH_NAMES = ["january", "february", "march",
                   "april",   "may",      "june",
                   "july",    "august",   "september",
                   "october", "november", "december"];

var DAY_NAMES = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

exports = module.exports = function parse(str, usa) {
  var now = new Date();

  str = str.trim().toLowerCase();

  return parseNearbyDays(str, now) ||
         parseLastThisNext(str, now) ||
         parseNumberDate(str, usa) ||
         parseNumberDateShortYear(str, usa, 80) ||
         parseWordyDate(str, now) ||
         parseIso8601Date(str);
};

var NUMBER              = /^[0-9]+$/;
var NUMBER_WITH_ORDINAL = /^([0-9]+)(st|nd|rd|th)?$/;
var NUMBER_DATE         = /^(3[0-1]|[1-2][0-9]|0?[1-9])[,\|\\\/\-\. ]+(1[0-2]|0?[1-9])[,\|\\\/\-\. ]+([0-9]{4})$/;
var NUMBER_DATE_USA     = /^(1[0-2]|0?[1-9])[,\|\\\/\-\. ]+(3[0-1]|[1-2][0-9]|0?[1-9])[,\|\\\/\-\. ]+([0-9]{4})$/;
var NUMBER_DATE_SHORT_YEAR         = /^(3[0-1]|[1-2][0-9]|0?[1-9])[,\|\\\/\-\. ]+(1[0-2]|0?[1-9])[,\|\\\/\-\. ]+([0-9]{2})$/;
var NUMBER_DATE_SHORT_YEAR_USA     = /^(1[0-2]|0?[1-9])[,\|\\\/\-\. ]+(3[0-1]|[1-2][0-9]|0?[1-9])[,\|\\\/\-\. ]+([0-9]{2})$/;
var ISO_8601_DATE       = /^([0-9]{4})-?(1[0-2]|0?[1-9])-?(3[0-1]|[1-2][0-9]|0?[1-9])$/;

function addDays(now, numberOfDays) {
  var result = new Date(now * 1 + numberOfDays * 60 * 60 * 24 * 1000);
  return date(result.getFullYear(), result.getMonth(), result.getDate());
}

exports.parseNearbyDays = parseNearbyDays;
function parseNearbyDays(string, now) {
  if (string == 'today') {
    return date(now.getFullYear(), now.getMonth(), now.getDate());;
  } else if (string == 'yesterday') {
    return addDays(now, -1);
  } else if (string == 'tomorrow') {
    return addDays(now, +1);
  } else {
    return null;
  }
}

exports.parseLastThisNext = parseLastThisNext;
function parseLastThisNext(string, now) {
  var tokens = string.split(/[,\s]+/);

  if (['last', 'this', 'next'].indexOf(tokens[0]) >= 0 &&
      DAY_NAMES.indexOf(tokens[1]) >= 0 &&
      tokens.length === 2) {
    var dayDiff = DAY_NAMES.indexOf(tokens[1]) - now.getDay();
    if (dayDiff < 0) dayDiff += 7;

    if (tokens[0] === 'last') return addDays(now, dayDiff - 7);
    if (tokens[0] === 'this') return addDays(now, dayDiff);
    if (tokens[0] === 'next') return addDays(now, dayDiff + 7);
  } else {
    return null;
  }
}

exports.parseNumberDate = parseNumberDate;
function parseNumberDate(str, usa) {
  var match = usa ? NUMBER_DATE_USA.exec(str) : NUMBER_DATE.exec(str);
  if (match) {
    return usa ? date(+match[3], match[1] - 1, +match[2]) : date(+match[3], match[2] - 1, +match[1]);
  } else {
    return null;
  }
}

exports.parseNumberDateShortYear = parseNumberDateShortYear;
function parseNumberDateShortYear(str, usa, cutoff) {
  var match = usa ? NUMBER_DATE_SHORT_YEAR_USA.exec(str) : NUMBER_DATE_SHORT_YEAR.exec(str);
  if (match) {
    var year = (+match[3]);
    if (year > cutoff) year += 1900;
    else year += 2000;
    return usa ? date(year, match[1] - 1, +match[2]) : date(year, match[2] - 1, +match[1]);
  } else {
    return null;
  }
}

exports.parseWordyDate = parseWordyDate;
function parseWordyDate(string, today) {
  var tokens = string.split(/[,\s]+/);
  if (tokens.length >= 2) {
    var match;
    if (match = tokens[0].match(NUMBER_WITH_ORDINAL)) {
      return parseWordyDateParts(match[1], tokens[1], tokens[2], today);
    } else if (match = tokens[1].match(NUMBER_WITH_ORDINAL)) {
      return parseWordyDateParts(match[1], tokens[0], tokens[2], today);
    } else {
      return null;
    }
  }
}

function parseWordyDateParts(rawDay, rawMonth, rawYear, today) {
  var day = +rawDay;
  var month = monthFromName(rawMonth);
  var year;

  if (rawYear)
    year = rawYear.match(NUMBER) ? rawYear * 1 : null;
  else
    year = today.getFullYear();

  if (year < 100 && year >= 80) year += 1900;
  if (year < 100) year += 2000;

  if (!(day && month !== null && year))
    return null;

  return date(year, month, day);
}

function parseIso8601Date(string) {
  var match;
  if (match = ISO_8601_DATE.exec(string)) {
    return date(+match[1], match[2] - 1, +match[3]);
  } else {
    return null;
  }
}

var monthAbreviations = MONTH_NAMES.map(function (name) { return name.substr(0, 3); });
exports.monthFromName = monthFromName;
function monthFromName(month) {
  var monthIndex = month.length === 3 ? monthAbreviations.indexOf(month) : MONTH_NAMES.indexOf(month);
  return monthIndex >= 0 ? monthIndex : null;
}

exports.date = date;
function date(year, month, day) {
  month++;
  if (month > 12 || month < 0) return null;
  if (day > 31 || day < 1) return null;
  if (month < 10) month = '0' + month;
  if (day < 10) day = '0' + day;

  return year + '-' + month + '-' + day;
}
function getISOString(year, month, day) {
  month++;
  if (month < 10) month = '0' + month;
  if (day < 10) day = '0' + day;
  return year + '-' + month + '-' + day + 'T00:00:00.000Z';
}
<|endoftext|>


<commit_before>'use strict'

const secret = require('./_secret.json')

if (!secret.token) {
    console.log('Error: Specify token in json file _secret')
    process.exit(1)
}

const Botkit = require('botkit')
const os = require('os')

const controller = Botkit.slackbot({
    debug: true,
    stats_optout: true
})

const bot = controller.spawn({
    token: secret.token
}).startRTM()

controller.hears(['hello', 'hi'], 'direct_message,direct_mention,mention', (bot, message) => {
    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    }, (err, res) => {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(', err)
        }
    })

    controller.storage.users.get(message.user, (err, user) => {
        if (user && user.name) {
            bot.reply(message, 'Hello ' + user.name + '!!')
            bot.reply(message, 'Would you like me to nag someone or follow up on your existing nags? (nag/list)')
        } else {
            bot.reply(message, 'Hello. Would you like me to nag someone or follow up on your existing nags? (nag/list)')
        }
    })
})

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', (bot, message) => {

        let hostname = os.hostname()
        let uptime = formatUptime(process.uptime())

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.')

    })

controller.hears(['nag'], 'direct_message,direct_mention,mention', (bot, message) => {
    bot.reply(message, 'Great! I can\'t wait to get started.')
    bot.startConversation(message, askUsersToNag)
})

const messages = {
    askUsersToNag: 'Who would you like me to nag? Tag them and separate by commas (i.e. @Superman,@Batman)',
    askMessageToNagAbout: 'What would you like me to nag them about?',
    askDeadline: 'Do you have a deadline? (DD/MM/YY | No)',
    recapOptions: 'Does this information look right to you? (Y/n)'
}

function askUsersToNag(response, convo) {
    convo.ask(messages.askUsersToNag, (response, convo) => {
        convo.say('Noted.');
        askMessageToNagAbout(response, convo);
        convo.next();
    });
}

function askMessageToNagAbout(response, convo) {
    convo.ask(messages.askMessageToNagAbout, function(response, convo) {
        convo.say('Noted.')
        askDeadline(response, convo);
        convo.next();
    });
}

function askDeadline(response, convo) {
    convo.ask(messages.askDeadline, (response, convo) => {
        let dateResponse = convo.extractResponse(messages.askDeadline)

        if (bot.utterances.no || validDate(dateResponse)) {
            recapOptions(response, convo)
        } else {
            askDeadline(response, convo)
        }
        convo.next()
    })
}

function validDate(date) {
    return false
}

function recapOptions(response, convo) {
    let values = convo.extractResponses()

    // Values are extracted with the questions as keys
    convo.say('I should nag: ' + values[messages.askUsersToNag])
    convo.say('I should ask them about: ' + values[messages.askMessageToNagAbout])
    if (values[messages.askDeadline].toLowerCase() == 'no') {
        convo.say('There is no deadline')
    } else {
        convo.say('The deadline is: ' + values[messages.askDeadline])
    }
    convo.ask(messages.recapOptions, (response, convo) => {
        convo.say('Alright! For now, please remind them yourself. I haven\'t learned to initiate nagging yet.')
        convo.say('I\'m sure I\'ll learn soon enough. Thanks for trying me out!')
        convo.next()
    })
}

function formatUptime(uptime) {
    var unit = 'second'
    if (uptime > 60) {
        uptime = uptime / 60
        unit = 'minute'
    }
    if (uptime > 60) {
        uptime = uptime / 60
        unit = 'hour'
    }
    if (uptime != 1) {
        unit = unit + 's'
    }

    uptime = uptime + ' ' + unit
    return uptime
}
<commit_msg>Match negative responses<commit_after>'use strict'

const secret = require('./_secret.json')

if (!secret.token) {
    console.log('Error: Specify token in json file _secret')
    process.exit(1)
}

const Botkit = require('botkit')
const os = require('os')

const controller = Botkit.slackbot({
    debug: true,
    stats_optout: true
})

const bot = controller.spawn({
    token: secret.token
}).startRTM()

controller.hears(['hello', 'hi'], 'direct_message,direct_mention,mention', (bot, message) => {
    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    }, (err, res) => {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(', err)
        }
    })

    controller.storage.users.get(message.user, (err, user) => {
        if (user && user.name) {
            bot.reply(message, 'Hello ' + user.name + '!!')
            bot.reply(message, 'Would you like me to nag someone or follow up on your existing nags? (nag/list)')
        } else {
            bot.reply(message, 'Hello. Would you like me to nag someone or follow up on your existing nags? (nag/list)')
        }
    })
})

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', (bot, message) => {

        let hostname = os.hostname()
        let uptime = formatUptime(process.uptime())

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.')

    })

controller.hears(['nag'], 'direct_message,direct_mention,mention', (bot, message) => {
    bot.reply(message, 'Great! I can\'t wait to get started.')
    bot.startConversation(message, askUsersToNag)
})

const messages = {
    askUsersToNag: 'Who would you like me to nag? Tag them and separate by commas (i.e. @Superman,@Batman)',
    askMessageToNagAbout: 'What would you like me to nag them about?',
    askDeadline: 'Do you have a deadline? (DD/MM/YY | No)',
    recapOptions: 'Does this information look right to you? (Y/n)'
}

function askUsersToNag(response, convo) {
    convo.ask(messages.askUsersToNag, (response, convo) => {
        convo.say('Noted.');
        askMessageToNagAbout(response, convo);
        convo.next();
    });
}

function askMessageToNagAbout(response, convo) {
    convo.ask(messages.askMessageToNagAbout, function(response, convo) {
        convo.say('Noted.')
        askDeadline(response, convo);
        convo.next();
    });
}

function askDeadline(response, convo) {
    convo.ask(messages.askDeadline, (response, convo) => {
        let dateResponse = convo.extractResponse(messages.askDeadline)
        if (dateResponse.match(bot.utterances.no) || validDate(dateResponse)) {
            recapOptions(response, convo)
        } else {
            askDeadline(response, convo)
        }
        convo.next()
    })
}

function validDate(date) {
    return false
}

function recapOptions(response, convo) {
    let values = convo.extractResponses()

    // Values are extracted with the questions as keys
    convo.say('I should nag: ' + values[messages.askUsersToNag])
    convo.say('I should ask them about: ' + values[messages.askMessageToNagAbout])
    if (values[messages.askDeadline].toLowerCase() == 'no') {
        convo.say('There is no deadline')
    } else {
        convo.say('The deadline is: ' + values[messages.askDeadline])
    }
    convo.ask(messages.recapOptions, (response, convo) => {
        convo.say('Alright! For now, please remind them yourself. I haven\'t learned to initiate nagging yet.')
        convo.say('I\'m sure I\'ll learn soon enough. Thanks for trying me out!')
        convo.next()
    })
}

function formatUptime(uptime) {
    var unit = 'second'
    if (uptime > 60) {
        uptime = uptime / 60
        unit = 'minute'
    }
    if (uptime > 60) {
        uptime = uptime / 60
        unit = 'hour'
    }
    if (uptime != 1) {
        unit = unit + 's'
    }

    uptime = uptime + ' ' + unit
    return uptime
}
<|endoftext|>


<commit_before>var through2 = require('through2'),
  File = require('vinyl'),
  documentation = require('documentation');

/**
 * Documentation stream intended for use within the gulp system.
 *
 * @name documentation
 * @param {Object} options output options
 * @param {string} options.format either 'html', 'md', 'json', or 'docset'
 * @param {string} options.filename custom filename for md or json output
 * @returns {stream.Transform}
 * @example
 * var documentation = require('./'),
 *     gulp = require('gulp');
 *
 * gulp.task('documentation', function () {
 *   gulp.src('./index.js')
 *     .pipe(documentation({
 *       format: 'html'
 *     }))
 *     .pipe(gulp.dest('documentation'));
 * });
 *
 * // documentation with JSON output, default filename API.md
 * gulp.task('documentation-json', function () {
 *   gulp.src('./index.js')
 *     .pipe(documentation({
 *       format: 'json'
 *     }))
 *     .pipe(gulp.dest('documentation'));
 * });
 *
 * // documentation with markdown output, default filename API.md
 * gulp.task('documentation-md', function () {
 *   gulp.src('./index.js')
 *     .pipe(documentation({
 *       format: 'md'
 *     }))
 *     .pipe(gulp.dest('documentation'));
 * });
 */
module.exports = function (options) {
  options = options || {};
  var docOptions = {
    github : !!(options.github || options.g),
    shallow: options.shallow || false
  };
  var files = [];
  options.format = options.format || 'html';
  var formatter = documentation.formats[options.format];
  if (!formatter) {
    throw new Error('invalid format given: valid options are ' + Object.keys(documentation.formats).join(', '));
  }
  return through2.obj(function document(file, enc, cb) {
    files.push(file);
    cb();
  }, function (cb) {
    documentation(files.map(function(file) {
      return file.path;
    }), docOptions, function(err, comments) {
      formatter(comments, {}, function (err, output) {
        if (options.format === 'json' || options.format === 'md') {
          this.push(new File({
            path: options.filename || 'API.' + options.format,
            contents: new Buffer(output)
          }));
        } else if (options.format === 'html') {
          output.forEach(function(file) {
            this.push(file);
          }.bind(this));
        }
        cb();
      }.bind(this));
    }.bind(this));
  });
};
<commit_msg>allow usage of custom instance<commit_after>var through2 = require('through2'),
  File = require('vinyl');

/**
 * Documentation stream intended for use within the gulp system.
 *
 * @name documentation
 * @param {Object} options output options
 * @param {string} options.format either 'html', 'md', 'json', or 'docset'
 * @param {string} options.filename custom filename for md or json output
 * @returns {stream.Transform}
 * @example
 * var documentation = require('./'),
 *     gulp = require('gulp');
 *
 * gulp.task('documentation', function () {
 *   gulp.src('./index.js')
 *     .pipe(documentation({
 *       format: 'html'
 *     }))
 *     .pipe(gulp.dest('documentation'));
 * });
 *
 * // documentation with JSON output, default filename API.md
 * gulp.task('documentation-json', function () {
 *   gulp.src('./index.js')
 *     .pipe(documentation({
 *       format: 'json'
 *     }))
 *     .pipe(gulp.dest('documentation'));
 * });
 *
 * // documentation with markdown output, default filename API.md
 * gulp.task('documentation-md', function () {
 *   gulp.src('./index.js')
 *     .pipe(documentation({
 *       format: 'md'
 *     }))
 *     .pipe(gulp.dest('documentation'));
 * });
 *
 *
 * // documentation with JSON output, default filename API.md and custom Documentation instance
 * var documentation = require('gulp-documentation'),
 *     $documentation = require('documentation');
 *
 *
 * gulp.task('documentation-json', function () {
 *   gulp.src('./index.js')
 *     .pipe(documentation({
 *       format: 'json'
 *     }, $documentation))
 *     .pipe(gulp.dest('documentation'));
 * });
 *
 */
module.exports = function (options, documentation) {
  options = options || {};
  documentation = documentation || require('documentation');

  var docOptions = {
    github : !!(options.github || options.g),
    shallow: options.shallow || false
  };
  var files = [];
  options.format = options.format || 'html';
  var formatter = documentation.formats[options.format];
  if (!formatter) {
    throw new Error('invalid format given: valid options are ' + Object.keys(documentation.formats).join(', '));
  }
  return through2.obj(function document(file, enc, cb) {
    files.push(file);
    cb();
  }, function (cb) {
    documentation(files.map(function(file) {
      return file.path;
    }), docOptions, function(err, comments) {
      formatter(comments, {}, function (err, output) {
        if (options.format === 'json' || options.format === 'md') {
          this.push(new File({
            path: options.filename || 'API.' + options.format,
            contents: new Buffer(output)
          }));
        } else if (options.format === 'html') {
          output.forEach(function(file) {
            this.push(file);
          }.bind(this));
        }
        cb();
      }.bind(this));
    }.bind(this));
  });
};
<|endoftext|>


<commit_before>//var request = require('request-promise');
var Promise = require('bluebird');
var request = require('request');
var limiter = require('limiter');
var debug = require('debug')('node-sdk');
var Agent = require('agentkeepalive');

var keepaliveAgent = new Agent({
  maxSockets: 100,
  maxFreeSockets: 10,
  timeout: 60000,
  keepAliveTimeout: 30000 // free socket keepalive for 30 seconds
});

var timeout = 60000;
var mag3llanURI;
var api_key;

var rate = 300;

function isURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
  '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+ // domain name
  '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
  '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
  '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
  '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return pattern.test(str);
}

if (process.env.MAG3LLAN_RATE_LIMIT) {
	rate = parseInt(process.env.MAG3LLAN_RATE_LIMIT);
}

var rateLimiter = Promise.promisifyAll(new limiter.RateLimiter(rate, 'second'));

function Mag3llan(uri, key) {
	if (!isURL(uri))
		throw new Error('Invalid Mag3llan host URI');
	if (!key)
		throw new Error('Mag3llan API key is required');

	api_key = key;
	mag3llanURI = uri + '/api/';

	debug(mag3llanURI)
}

Mag3llan.prototype.setPreference = function(userId, itemId, score) {
	var preference = {
		uid: parseInt(userId),
		iid: parseInt(itemId),
		value: parseFloat(score)
	};

	return put('preference/' + userId + '/' + itemId, preference);
}

Mag3llan.prototype.delPreference = function(userId, itemId) {
	return del('preference/' + userId + '/' + itemId);
}

Mag3llan.prototype.deleteUser = function(userId) {
	return del('user/' + userId);
}

Mag3llan.prototype.plu = function(userId, threshold) {
	var params = threshold ? '?threshold=' + threshold : '';
	return get('plu/' + userId + params);
}

Mag3llan.prototype.pluItemRating = function(userId, itemId, threshold) {
	var params = threshold ? '?threshold=' + threshold : '';
	return get('plu/' + userId + '/rating/' + itemId + params);
}

Mag3llan.prototype.overlaps = function(userId, otherUserId) {

	return get('overlaps/' + userId + '/' + otherUserId);
}

Mag3llan.prototype.recommendations = function(userId) {
	return get('recommendation/' + userId);
}

Mag3llan.prototype.groupRecommendations = function(userId, otherUserId) {
	return get('recommendation/' + userId + '/' + otherUserId);
}

Mag3llan.prototype.similarity = function(userId, otherUserId) {
	return get('similarity/' + userId + '/' + otherUserId);
}

function get(resourceURI) {
	var getOpts = {

		uri: encodeURI(mag3llanURI + resourceURI),
		timeout: timeout,
		resolveWithFullResponse: true,
		headers: {
			'Accept': 'application/json',
			'Access_Token': api_key
		}
	};

	return execute(getOpts)
		.then(function(response) {
			return JSON.parse(response.body);
		})
}

function post(resourceURI, resource) {
	var postOpts = {
		uri: encodeURI(mag3llanURI + resourceURI),
		method: 'POST',
		timeout: timeout,
		json: true,
		body: resource,
		resolveWithFullResponse: true,
		headers: {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			'Access_Token': api_key
		}
	};

	return execute(postOpts);
}

function del(resourceURI) {
	var delOpts = {
		uri: encodeURI(mag3llanURI + resourceURI),
		method: 'DELETE',
		timeout: timeout,
		resolveWithFullResponse: true,
		headers: {
			'Accept': 'application/json',
			'Access_Token': api_key
		}
	};

	return execute(delOpts)
		.then(function(response) {
			if (response.statusCode != 204)
				return Promise.reject('Unable to delete: ' + resourceURI);

			return response.body;
		});
}

function put(resourceURI, resource) {
	var putOpts = {
		uri: encodeURI(mag3llanURI + resourceURI),
		method: 'PUT',
		agent: keepaliveAgent,
		timeout: timeout,
		json: true,
		body: resource,
		resolveWithFullResponse: true,
		headers: {
			'Connection': 'keep-alive',
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			'Access_Token': api_key
		}
	}

	return execute(putOpts);
}

function execute(options) {
	return rateLimiter.removeTokensAsync(1)
		.then(function() {
			return new Promise(function(resolve, reject) {
				debug(options);
				request(options, function(error, response, body) {
					if (error) {
						debug(err)
						reject(error);
					} else {
						if (response.statusCode >= 200 && response.statusCode < 300) {
							var result = {
								body: body,
								statusCode: response.statusCode
							};
							console.log(result)
							resolve(result);
						} else {
							var customError = new Error(body);
							customError.statusCode = response.statusCode;
							reject(customError);
						}
					}

				});
			});
		});
}

exports = module.exports = Mag3llan;<commit_msg>- Fixed err reference. - Removed console logs. - Update release number.<commit_after>//var request = require('request-promise');
var Promise = require('bluebird');
var request = require('request');
var limiter = require('limiter');
var debug = require('debug')('node-sdk');
var Agent = require('agentkeepalive');

var keepaliveAgent = new Agent({
  maxSockets: 100,
  maxFreeSockets: 10,
  timeout: 60000,
  keepAliveTimeout: 30000 // free socket keepalive for 30 seconds
});

var timeout = 60000;
var mag3llanURI;
var api_key;

var rate = 300;

function isURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
  '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+ // domain name
  '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
  '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
  '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
  '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return pattern.test(str);
}

if (process.env.MAG3LLAN_RATE_LIMIT) {
	rate = parseInt(process.env.MAG3LLAN_RATE_LIMIT);
}

var rateLimiter = Promise.promisifyAll(new limiter.RateLimiter(rate, 'second'));

function Mag3llan(uri, key) {
	if (!isURL(uri))
		throw new Error('Invalid Mag3llan host URI');
	if (!key)
		throw new Error('Mag3llan API key is required');

	api_key = key;
	mag3llanURI = uri + '/api/';

	debug(mag3llanURI)
}

Mag3llan.prototype.setPreference = function(userId, itemId, score) {
	var preference = {
		uid: parseInt(userId),
		iid: parseInt(itemId),
		value: parseFloat(score)
	};

	return put('preference/' + userId + '/' + itemId, preference);
}

Mag3llan.prototype.delPreference = function(userId, itemId) {
	return del('preference/' + userId + '/' + itemId);
}

Mag3llan.prototype.deleteUser = function(userId) {
	return del('user/' + userId);
}

Mag3llan.prototype.plu = function(userId, threshold) {
	var params = threshold ? '?threshold=' + threshold : '';
	return get('plu/' + userId + params);
}

Mag3llan.prototype.pluItemRating = function(userId, itemId, threshold) {
	var params = threshold ? '?threshold=' + threshold : '';
	return get('plu/' + userId + '/rating/' + itemId + params);
}

Mag3llan.prototype.overlaps = function(userId, otherUserId) {

	return get('overlaps/' + userId + '/' + otherUserId);
}

Mag3llan.prototype.recommendations = function(userId) {
	return get('recommendation/' + userId);
}

Mag3llan.prototype.groupRecommendations = function(userId, otherUserId) {
	return get('recommendation/' + userId + '/' + otherUserId);
}

Mag3llan.prototype.similarity = function(userId, otherUserId) {
	return get('similarity/' + userId + '/' + otherUserId);
}

function get(resourceURI) {
	var getOpts = {

		uri: encodeURI(mag3llanURI + resourceURI),
		timeout: timeout,
		resolveWithFullResponse: true,
		headers: {
			'Accept': 'application/json',
			'Access_Token': api_key
		}
	};

	return execute(getOpts)
		.then(function(response) {
			return JSON.parse(response.body);
		})
}

function post(resourceURI, resource) {
	var postOpts = {
		uri: encodeURI(mag3llanURI + resourceURI),
		method: 'POST',
		timeout: timeout,
		json: true,
		body: resource,
		resolveWithFullResponse: true,
		headers: {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			'Access_Token': api_key
		}
	};

	return execute(postOpts);
}

function del(resourceURI) {
	var delOpts = {
		uri: encodeURI(mag3llanURI + resourceURI),
		method: 'DELETE',
		timeout: timeout,
		resolveWithFullResponse: true,
		headers: {
			'Accept': 'application/json',
			'Access_Token': api_key
		}
	};

	return execute(delOpts)
		.then(function(response) {
			if (response.statusCode != 204)
				return Promise.reject('Unable to delete: ' + resourceURI);

			return response.body;
		});
}

function put(resourceURI, resource) {
	var putOpts = {
		uri: encodeURI(mag3llanURI + resourceURI),
		method: 'PUT',
		agent: keepaliveAgent,
		timeout: timeout,
		json: true,
		body: resource,
		resolveWithFullResponse: true,
		headers: {
			'Connection': 'keep-alive',
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			'Access_Token': api_key
		}
	}

	return execute(putOpts);
}

function execute(options) {
	return rateLimiter.removeTokensAsync(1)
		.then(function() {
			return new Promise(function(resolve, reject) {
				debug(options);
				request(options, function(error, response, body) {
					if (error) {
						debug(error)
						reject(error);
					} else {
						if (response.statusCode >= 200 && response.statusCode < 300) {
							var result = {
								body: body,
								statusCode: response.statusCode
							};
							debug(result)
							resolve(result);
						} else {
							var customError = new Error(body);
							customError.statusCode = response.statusCode;
							reject(customError);
						}
					}

				});
			});
		});
}

exports = module.exports = Mag3llan;<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

module.exports = {
  name: 'ember-power-select',

  included(appOrAddon) {
    let app = this._lookupApp(appOrAddon);
    if (!app.__emberPowerSelectIncludedInvoked) {
      app.__emberPowerSelectIncludedInvoked = true;

      let options = typeof app.options === 'object' ? app.options : {};
      let addonConfig = options['ember-power-select'] || {};

      // Since ember-power-select styles already `@import` styles of ember-basic-dropdown,
      // this flag tells to ember-basic-dropdown to skip importing its styles provided
      // we're using a theme (or the default styles)
      if (addonConfig.theme !== false) {
        app.__skipEmberBasicDropdownStyles = true;
      }

      this._super.included.apply(this, arguments);

      let hasSass = !!app.registry.availablePlugins['ember-cli-sass'];
      let hasLess = !!app.registry.availablePlugins['ember-cli-less'];

      // Don't include the precompiled css file if the user uses a supported CSS preprocessor
      if (!hasSass && !hasLess) {
        if (addonConfig.theme) {
          app.import(`vendor/ember-power-select-${addonConfig.theme}.css`);
        } else if (addonConfig.theme !== false) {
          app.import('vendor/ember-power-select.css');
        }
      }
    }
  },

  contentFor(type, config) {
    let emberBasicDropdown = this.addons.find((a) => a.name === 'ember-basic-dropdown');
    return emberBasicDropdown.contentFor(type, config);
  },

  _lookupApp: function(appOrAddon) {
    let app = appOrAddon || appOrAddon.app;
    while (appOrAddon.parent) {
      app = appOrAddon.parent.app;
    }
    return app;
  }
};
<commit_msg>Use findHost method to find correct parent app<commit_after>/* eslint-env node */
'use strict';

// For ember-cli < 2.7 findHost doesnt exist so we backport from that version
// for earlier version of ember-cli.
//https://github.com/ember-cli/ember-cli/blame/16e4492c9ebf3348eb0f31df17215810674dbdf6/lib/models/addon.js#L533
  function findHostShim() {
    let current = this;
    let app;
    do {
      app = current.app || app;
    } while (current.parent.parent && (current = current.parent));
    return app;
  }

module.exports = {
  name: 'ember-power-select',

  included(appOrAddon) {
    let findHost = this._findHost || findHostShim;
    let app = findHost.call(this);
    if (!app.__emberPowerSelectIncludedInvoked) {
      app.__emberPowerSelectIncludedInvoked = true;

      let options = typeof app.options === 'object' ? app.options : {};
      let addonConfig = options['ember-power-select'] || {};

      // Since ember-power-select styles already `@import` styles of ember-basic-dropdown,
      // this flag tells to ember-basic-dropdown to skip importing its styles provided
      // we're using a theme (or the default styles)
      if (addonConfig.theme !== false) {
        app.__skipEmberBasicDropdownStyles = true;
      }

      this._super.included.apply(this, arguments);

      let hasSass = !!app.registry.availablePlugins['ember-cli-sass'];
      let hasLess = !!app.registry.availablePlugins['ember-cli-less'];

      // Don't include the precompiled css file if the user uses a supported CSS preprocessor
      if (!hasSass && !hasLess) {
        if (addonConfig.theme) {
          app.import(`vendor/ember-power-select-${addonConfig.theme}.css`);
        } else if (addonConfig.theme !== false) {
          app.import('vendor/ember-power-select.css');
        }
      }
    }
  },

  contentFor(type, config) {
    let emberBasicDropdown = this.addons.find((a) => a.name === 'ember-basic-dropdown');
    return emberBasicDropdown.contentFor(type, config);
  }
};
<|endoftext|>


<commit_before>'use strict';

function first(arr) {
  return arr[0];
}

function rest(arr) {
  return arr.slice(1);
}

/**
 * Returns an array of successive items from coll while pred(item) returnsssssssssssssssssssssssssssssss true.
 *
 *
 * @param {Array} coll -
 * @param {Function} pred -
 * @param {Object} [ctx] -
 *
 * @returns {Array} -
 */
module.exports = function takeWhile(coll, pred, ctx) {
  if (pred(first(coll))) {
    return [first(coll)].concat(takeWhile(rest(coll), pred, ctx));
  }
  return [];
};
<commit_msg>chore: update jsdoc<commit_after>'use strict';

function first(arr) {
  return arr[0];
}

function rest(arr) {
  return arr.slice(1);
}

/**
 * Returns an array of successive items from coll while pred(item) returnsssssssssssssssssssssssssssssss true.
 *
 *
 * @param {Array} coll -
 * @param {Function} pred -
 * @param {object} [ctx] -
 *
 * @returns {Array} -
 */
module.exports = function takeWhile(coll, pred, ctx) {
  if (pred(first(coll))) {
    return [first(coll)].concat(takeWhile(rest(coll), pred, ctx));
  }
  return [];
};
<|endoftext|>


<commit_before>/*
 * Random plugin
 *   - choose: Choose between one of n options
 *   - dice: Roll n dice with x sides
 *   - roll: Roll between 1 and n(n defaults to 100)
 */
var Random = function() {
  this.commands = ['choose', 'dice', 'roll'];
  this.usage = {
    choose: 'ex: !choose code, sleep. Chooses randomly between a list of choices.',
    dice: 'ex: !dice <n>d<x>. Rolls n x-sided dices.',
    roll: 'ex: !roll <num>. Rolls between 1 and num. num defaults to 100.'
  };
};

/*
 * Helper function that returns a random number between min and max(inclusive)
 */
var getRandom = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

/*
 * Choose command
 */
Random.prototype.choose = function(bot, to, from, msg, callback) {
  var choices = msg.split(','),
      winningChoice;

  if (choices.length === 1 && choices[0] === '') {
    bot.say(to, 'I need something to choose from.');
    callback();
    return;
  }

  // Trim leading and trailing whitespace
  winningChoice = choices[getRandom(0, choices.length - 1)].replace(/^\s\s*/, '').replace(/\s\s*$/, '');

  bot.say(to, 'I choose ' + winningChoice);
  callback();
};

/*
 * Dice command
 */
Random.prototype.dice = function(bot, to, from, msg, callback) {
  var ii,
      roll = 0,
      dice = msg.split('d');

  if (dice.length === 1 && dice[0] === '') {
    // default to a single six-sided die
    dice = [1, 6];
  } else if (dice.length !== 2 || isNaN(parseInt(dice[0])) || isNaN(parseInt(dice[1]))) {
    bot.say(to, "Woops! I'm expecting <number of dice>d<number of sides>.");
    callback();
    return;
  }

  for (ii = 0; ii < dice[0]; ii++) {
    roll += getRandom(1, dice[1]);
  }

  bot.say(to, from + " rolled a " + roll);
  callback();
};

/*
 * Roll command
 */
Random.prototype.roll = function(bot, to, from, msg, callback) {
  var max = parseInt(msg);

  if (isNaN(max)) {
    max = 100;
  }

  bot.say(to, from + " rolled a " + getRandom(1, max));
  callback();
};

exports.Plugin = Random;
<commit_msg>fix(dice): Add some limits to dice rolling.<commit_after>/*
 * Random plugin
 *   - choose: Choose between one of n options
 *   - dice: Roll n dice with x sides
 *   - roll: Roll between 1 and n(n defaults to 100)
 */
var Random = function() {
  this.commands = ['choose', 'dice', 'roll'];
  this.usage = {
    choose: 'ex: !choose code, sleep. Chooses randomly between a list of choices.',
    dice: 'ex: !dice <n>d<x>. Rolls n x-sided dices.',
    roll: 'ex: !roll <num>. Rolls between 1 and num. num defaults to 100.'
  };
};

/*
 * Helper function that returns a random number between min and max(inclusive)
 */
var getRandom = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

/*
 * Choose command
 */
Random.prototype.choose = function(bot, to, from, msg, callback) {
  var choices = msg.split(','),
      winningChoice;

  if (choices.length === 1 && choices[0] === '') {
    bot.say(to, 'I need something to choose from.');
    callback();
    return;
  }

  // Trim leading and trailing whitespace
  winningChoice = choices[getRandom(0, choices.length - 1)].replace(/^\s\s*/, '').replace(/\s\s*$/, '');

  bot.say(to, 'I choose ' + winningChoice);
  callback();
};

/*
 * Dice command
 */
Random.prototype.dice = function(bot, to, from, msg, callback) {
  var ii,
      roll = 0,
      dice = msg.split('d');

  if (dice.length === 1 && dice[0] === '') {
    // default to a single six-sided die
    dice = [1, 6];
  } else if (dice.length !== 2 || isNaN(parseInt(dice[0])) || isNaN(parseInt(dice[1]))) {
    bot.say(to, "Woops! I'm expecting <number of dice>d<number of sides>.");
    callback();
    return;
  }

  if (dice[1] > 1000) {
    bot.say(to, 'Whoops! I can only roll 1000 dice at a time.');
    callback();
    return;
  }

  if (dice[0] > 1000) {
    bot.say(to, 'Whoops! A die with more than 1000 sides is to hard to read.');
    callback();
    return;
  }

  for (ii = 0; ii < dice[0]; ii++) {
    roll += getRandom(1, dice[1]);
  }

  bot.say(to, from + " rolled a " + roll);
  callback();
};

/*
 * Roll command
 */
Random.prototype.roll = function(bot, to, from, msg, callback) {
  var max = parseInt(msg);

  if (isNaN(max)) {
    max = 100;
  }

  bot.say(to, from + " rolled a " + getRandom(1, max));
  callback();
};

exports.Plugin = Random;
<|endoftext|>


<commit_before>'use strict'

var noop = function() { }
  , Emitter = require('emitter')

function GMap(element) {
  this.element = element
  this.markers = []
  this.markerOptions = {}
}

GMap.prototype.addMarkers = function(pairs) {
  var i; for (i = 0; i < pairs.length; i++) {
    this.markers.push(pairs[i])
  }
}

GMap.prototype.init = function(done) {
  done = done || noop

  if (this._initialized) done()
  else {
    var jsonp = require('jsonp')
      , gmap = this

    jsonp('http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false', {}, function() {
      gmap._initialized = true
      gmap._initMap()
      gmap._initMarkers()
      done()
    })
  }
}

GMap.prototype._initMap = function() {
  this.map = new google.maps.Map(this.element, {
    mapTypeId: 'roadmap',
    streetViewControl: false
  })

  this.map.fitBounds(this.getBounds())
}

GMap.prototype._initMarkers = function() {
  var gmap = this

  var i; for (i = 0; i < this.markers.length; i++) {
    var pair = this.markers[i]
      , options = {}

    for (var key in this.markerOptions) {
      if (this.markerOptions.hasOwnProperty(key)) options[key] = this.markerOptions[key]
    }

    options.position = new google.maps.LatLng(pair[0], pair[1])
    options.map = this.map

    var marker = new google.maps.Marker(options)

    google.maps.event.addListener(marker, 'click', (function(i) {
      return function() { gmap.emit('marker.click', i) }
    })(i))
  }
}

GMap.prototype.getBounds = function() {
  var bounds = new google.maps.LatLngBounds()

  var i; for (i = 0; i < this.markers.length; i++) {
    var pair = this.markers[i]

    bounds.extend(new google.maps.LatLng(pair[0], pair[1]))
  }

  return bounds
}

Emitter(GMap.prototype)

module.exports = GMap
<commit_msg>Support Info Windows.<commit_after>'use strict'

var noop = function() { }
  , Emitter = require('emitter')

function GMap(element) {
  this.element = element
  this.markers = []
  this.markerOptions = {}
  this.tooltips = null
}

GMap.prototype.addMarkers = function(pairs) {
  var i; for (i = 0; i < pairs.length; i++) {
    this.markers.push(pairs[i])
  }
}

GMap.prototype.init = function(done) {
  done = done || noop

  if (this._initialized) done()
  else {
    var jsonp = require('jsonp')
      , gmap = this

    jsonp('http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false', {}, function() {
      gmap._initialized = true
      gmap._initMap()
      gmap._initMarkers()
      done()
    })
  }
}

GMap.prototype._initMap = function() {
  this.map = new google.maps.Map(this.element, {
    mapTypeId: 'roadmap',
    streetViewControl: false
  })

  this.map.fitBounds(this.getBounds())
}

GMap.prototype._initMarkers = function() {
  var gmap = this

  var i; for (i = 0; i < this.markers.length; i++) {
    var pair = this.markers[i]
      , options = {}

    for (var key in this.markerOptions) {
      if (this.markerOptions.hasOwnProperty(key)) options[key] = this.markerOptions[key]
    }

    options.position = new google.maps.LatLng(pair[0], pair[1])
    options.map = this.map

    var marker = new google.maps.Marker(options)

    google.maps.event.addListener(marker, 'click', (function(i, marker) {
      return function() {
        gmap._showInfoWindow(i, marker)
        gmap.emit('marker.click', i, marker)
      }
    })(i, marker))
  }
}

GMap.prototype.getBounds = function() {
  var bounds = new google.maps.LatLngBounds()

  var i; for (i = 0; i < this.markers.length; i++) {
    var pair = this.markers[i]

    bounds.extend(new google.maps.LatLng(pair[0], pair[1]))
  }

  return bounds
}

GMap.prototype._showInfoWindow = function(index, marker) {
  if (this.tooltips === null) return

  var html = this.tooltips(index)

  this._infoWindow = this._infoWindow || new google.maps.InfoWindow()

  this._infoWindow.setContent(html)
  this._infoWindow.open(this.map, marker)
}

Emitter(GMap.prototype)

module.exports = GMap
<|endoftext|>