<commit_before>module.exports = (function () {
  var options
    , browserColors = []
    , browserStyle  = require('./browser-style')

  function getType (value) {
    var map = {
        '[object Number]'   : 'num'
      , '[object String]'   : 'str'
      , '[object Boolean]'  : 'bool'
      , '[object RegExp]'   : 'regex'
      , '[object Function]' : 'func'
      , 'null'              : 'null'
      , 'undefined'         : 'undef'
    }

    return map[toString.call(value)] || map[''+value];
  }

  function isBrowser () {
    return !!window;
  }

  function repeat (str, times) {
    return Array(times ? (times+1) : 0).join(str);
  }

  function cleanObject (obj) {
    var lastKey = '';
    for (var key in obj) {
      (getType(obj[key])==='func') && delete obj[key] || (lastKey = key);
    }
    return lastKey;
  }

  function cleanArray (arr) {
    return arr.filter(function (item) {
      return getType(item) !== 'func';
    });
  }

  function generateLevel (level) {
    var levelStr  = repeat(' ', options.level.spaces)
      , opts      = options.level;

    if (options.level.show && levelStr.length) {
      levelStr = levelStr.replace(' ', useColorProvider(opts.char, opts.color))
    }

    return repeat(levelStr, level);
  }

  function hasChild (obj) {
    for (var key in obj) {
      if (isArray(obj[key]) || isObject(obj[key])) return true;
    }
  }

  function isArray (arr) {
    return toString.call(arr).match(/^\[object Array\]$/);
  }

  function isObject (obj) {
    return toString.call(obj).match(/^\[object Object\]$/);
  }

  function colorify (value, level) {
    var color = options.colors[getType(value)];
    return generateLevel(level)
      + (getType(value) === 'str' ? colorifySpec('"', 'quot') : '')
      + useColorProvider('' + value, color)
      + (getType(value) === 'str' ? colorifySpec('"', 'quot') : '');
  }

  function colorifySpec (char, type, level) {
    return generateLevel(level) + useColorProvider('' + char, options.colors[type]);
  }

  function useColorProvider (str, color) {
    if(isBrowser()) {
      var style = (isArray(color) ? color : [color]).map(function (item) {
        return browserStyle[item]
      }).join(';');
      browserColors.push(style);
      return "%c" + str;
    } else {
      if (options.params.colored) {
        var chalk = require('chalk');
        if (isArray(color) && color.length) {
          return useColorProvider(chalk[color[0]](str), color.slice(1))
        } else {
          return chalk[isArray(color) ? color[0] : color](str);
        }
      }
    }

    return str;
  }

  return {
    gen : function (json, level, isChild) {
      var colored = [];
          level   = level || 0;

      if (isObject(json)) {

        var lastKey = cleanObject(json);
        colored.push(colorifySpec('{', 'brack', isChild ? 0 : level));
        level++;

        for(var key in json) {
          var result = colorifySpec(key, 'attr', level)
             + colorifySpec(': ', 'punc')
             + this.gen(json[key], level, true)
             + (key !== lastKey ? colorifySpec(',', 'punc') : '');
          colored.push(result);
        }

        colored.push(colorifySpec('}', 'brack', --level));

      } else if (isArray(json)) {
        json = cleanArray(json);

        if (hasChild(json)) {

          var result = json.map(function(item) {
            return this.gen(item, level+1);
          }.bind(this));

          colored.push(colorifySpec('[', 'brack', isChild ? 0 : level));;
          colored.push(result.join(colorifySpec(', ', 'punc') + '\n' ));
          colored.push(colorifySpec(']', 'brack', level));

        } else {

          var coloredArray = colorifySpec('[', 'brack', isChild ? 0 : level);
          for (var key in json) {
            coloredArray += colorify(json[key]) + (json.length-1>key ? colorifySpec(', ', 'punc') : '');
          }
          colored.push(coloredArray + colorifySpec(']', 'brack'));

        }

      } else {
        return generateLevel(isChild ? 0 : level) + colorify(json);
      }

      return isBrowser() ? [colored.join('\n')].concat(browserColors) : colored.join('\n');
    },
    setOptions : function (opts) {
      options = opts;
      return this;
    }
  }

})();<commit_msg>incorrect test<commit_after>module.exports = (function () {
  var options
    , browserColors = []
    , browserStyle  = require('./browser-style')

  function getType (value) {
    var map = {
        '[object Number]'   : 'num'
      , '[object String]'   : 'str'
      , '[object Boolean]'  : 'bool'
      , '[object RegExp]'   : 'regex'
      , '[object Function]' : 'func'
      , 'null'              : 'null'
      , 'undefined'         : 'undef'
    }

    return map[toString.call(value)] || map[''+value];
  }

  function isBrowser () {
    return typeof window == 'object';
  }

  function repeat (str, times) {
    return Array(times ? (times+1) : 0).join(str);
  }

  function cleanObject (obj) {
    var lastKey = '';
    for (var key in obj) {
      (getType(obj[key])==='func') && delete obj[key] || (lastKey = key);
    }
    return lastKey;
  }

  function cleanArray (arr) {
    return arr.filter(function (item) {
      return getType(item) !== 'func';
    });
  }

  function generateLevel (level) {
    var levelStr  = repeat(' ', options.level.spaces)
      , opts      = options.level;

    if (options.level.show && levelStr.length) {
      levelStr = levelStr.replace(' ', useColorProvider(opts.char, opts.color))
    }

    return repeat(levelStr, level);
  }

  function hasChild (obj) {
    for (var key in obj) {
      if (isArray(obj[key]) || isObject(obj[key])) return true;
    }
  }

  function isArray (arr) {
    return toString.call(arr).match(/^\[object Array\]$/);
  }

  function isObject (obj) {
    return toString.call(obj).match(/^\[object Object\]$/);
  }

  function colorify (value, level) {
    var color = options.colors[getType(value)];
    return generateLevel(level)
      + (getType(value) === 'str' ? colorifySpec('"', 'quot') : '')
      + useColorProvider('' + value, color)
      + (getType(value) === 'str' ? colorifySpec('"', 'quot') : '');
  }

  function colorifySpec (char, type, level) {
    return generateLevel(level) + useColorProvider('' + char, options.colors[type]);
  }

  function useColorProvider (str, color) {
    if(isBrowser()) {
      var style = (isArray(color) ? color : [color]).map(function (item) {
        return browserStyle[item]
      }).join(';');
      browserColors.push(style);
      return "%c" + str;
    } else {
      if (options.params.colored) {
        var chalk = require('chalk');
        if (isArray(color) && color.length) {
          return useColorProvider(chalk[color[0]](str), color.slice(1))
        } else {
          return chalk[isArray(color) ? color[0] : color](str);
        }
      }
    }

    return str;
  }

  return {
    gen : function (json, level, isChild) {
      var colored = [];
          level   = level || 0;

      if (isObject(json)) {

        var lastKey = cleanObject(json);
        colored.push(colorifySpec('{', 'brack', isChild ? 0 : level));
        level++;

        for(var key in json) {
          var result = colorifySpec(key, 'attr', level)
             + colorifySpec(': ', 'punc')
             + this.gen(json[key], level, true)
             + (key !== lastKey ? colorifySpec(',', 'punc') : '');
          colored.push(result);
        }

        colored.push(colorifySpec('}', 'brack', --level));

      } else if (isArray(json)) {
        json = cleanArray(json);

        if (hasChild(json)) {

          var result = json.map(function(item) {
            return this.gen(item, level+1);
          }.bind(this));

          colored.push(colorifySpec('[', 'brack', isChild ? 0 : level));;
          colored.push(result.join(colorifySpec(', ', 'punc') + '\n' ));
          colored.push(colorifySpec(']', 'brack', level));

        } else {

          var coloredArray = colorifySpec('[', 'brack', isChild ? 0 : level);
          for (var key in json) {
            coloredArray += colorify(json[key]) + (json.length-1>key ? colorifySpec(', ', 'punc') : '');
          }
          colored.push(coloredArray + colorifySpec(']', 'brack'));

        }

      } else {
        return generateLevel(isChild ? 0 : level) + colorify(json);
      }

      return isBrowser() ? [colored.join('\n')].concat(browserColors) : colored.join('\n');
    },
    setOptions : function (opts) {
      options = opts;
      return this;
    }
  }

})();<|endoftext|>


<commit_before>var store;

function generate(name, config) {

  store = config.store;

  if (config.list) {
    testList.call(this, name);
  }
  if (config.create) {
    testCreate.call(this, name, config.create.data);
  }
  if (config.read) {
    testGet.call(this, name, config.read.source);
  }
  if (config.update) {
    testUpdate.call(this, name, config.update.source, config.update.data);
  }
  if (config.delete) {
    testDelete.call(this, name, config.delete.source);
  }
}

function getList(name) {
  return store.find(name);
}
function getRandomFromList(name) {
  return getList(name)
    .then(function(list) {
      var length = list.get('length'),
          rand = Math.floor(Math.random() * length),
          item = list.objectAt(rand);

      return item.reload();
    });
}

function createItem(name, data) {
  if (typeof data === 'function') {
    return createItem.bind(this)().save(); // TODO - detect if promise
  }

  var newObject = store.createRecord(name),
      key, val;

  for (key in data) {
    if (data.hasOwnProperty(key)) {
      val = data[key];

      if (typeof val === 'function') {
        val = val.call(this, newObject.get(key));
      }

      if (typeof val !== 'undefined') {
        newObject.set(key, val);
      }
    }
  }

  return newObject.save();
}

function fetchItem(name, source) {
  var fetchFn;

  if (source === 'listRandom') {
    fetchFn = getRandomFromList.bind(this, name);
  } else if (source === 'listFilter') {
    // TODO - handle listFilter
  } else if (source === 'create') {
    // TODO - handle create
  } else if (typeof source === 'number' || typeof source === 'string') {
    fetchFn = store.find.bind(store, name, source);
  } else if (typeof source === 'function') {
    fetchFn = source.bind(this);
  } else {
    Ember.assert("Improper source specified");
    return;
  }

  return fetchFn(); // TODO - promise wrap
}

function updateItem(item, data) {
  debugger;
}

function createAllowedTest(promise, successMessage, failureMessage) {
  async();
  return promise
    .then(handleSuccess(successMessage), handleFailure(failureMessage))
    .finally(asyncDone);
}

function createForbidTest(promise, successMessage, failureMessage) {
  async();
  return promise
    .then(handleFailure(failureMessage), handleSuccess(successMessage))
    .finally(asyncDone);
}

function testUpdate(name, source, data) {
  return createAllowedTest(
    fetchItem.call(this, name, source)
      .then(function(item) {
        return updateItem(item, data);
      }),
    name + " is updatable",
    name + " failed to be updated"
  );
}

function forbidUpdate(name, source, data) {
  return createForbidTest(
    fetchItem.call(this, name, source)
      .then(function(item) {
        return updateItem(item, data);
      }),
    name + " cannot be updated",
    name + " should NOT be updatable"
  );
}

function testDelete(name, source) {
  return createAllowedTest(
    fetchItem.call(this, name, source)
      .then(function(item) {
        return item.destroyRecord();
      }),
    name + " is deletable",
    name + " failed to be deleted"
  );
}

function forbidDelete(name, source) {
  return createForbidTest(
    fetchItem.call(this, name, source)
      .then(function(item) {
        return item.destroyRecord();
      }),
    name + " cannot be deleted",
    name + " should NOT be deletable"
  );
}

function testCreate(name, data) {
  return createAllowedTest(
    createItem.call(this, name, data),
    name + " is creatable",
    name + " failed to be created"
  );
}

function forbidCreate(name, data) {
  return createForbidTest(
    createItem.call(this, name, data),
    name + " cannot be created",
    name + " should NOT be creatable"
  );
}

function testList(name) {
  return createAllowedTest(
    getList.call(this, name),
    name + " is listable",
    name + " failed to be listed"
  );
}

function forbidList(name) {
  return createForbidTest(
    getList.call(this, name),
    name + " is not listable",
    name + " should NOT be listable"
  );
}

function testGet(name, source) {
  return createAllowedTest(
    fetchItem.call(this, name, source),
    name + " is readable",
    name + " failed to be fetched"
  );
}

function forbidGet(name, source) {
  return createForbidTest(
    fetchItem.call(this, name, source),
    name + " is not readable",
    name + " should NOT be readable"
  );
}

function handleSuccess(message) {
  return function(arg) {
    ok(true, message || "Promise resolved successfully");
    return arg;
  };
}
function handleFailure(message) {
  return function(arg) {
    ok(false, message || "Promise was rejected");
    return arg;
  };
}
function async() {
  QUnit.stop();
}
function asyncDone(arg) {
  QUnit.start();
  return arg;
}

export { generate };
<commit_msg>Change syntax for aquiring DS.Store instance<commit_after>var store;

function getStore(App, name) {
  return App.__container__.lookup('store:' + (name || 'main'));
}

function generate(test, name, config) {

  if (config.list) {
    testList.call(this, name);
  }
  if (config.create) {
    testCreate.call(this, name, config.create.data);
  }
  if (config.read) {
    testGet.call(this, name, config.read.source);
  }
  if (config.update) {
    testUpdate.call(this, name, config.update.source, config.update.data);
  }
  if (config.delete) {
    testDelete.call(this, name, config.delete.source);
  }
}

function getList(name) {
  return getStore(this.App).find(name);
}
function getRandomFromList(name) {
  return getList(name)
    .then(function(list) {
      var length = list.get('length'),
          rand = Math.floor(Math.random() * length),
          item = list.objectAt(rand);

      return item.reload();
    });
}

function createItem(name, data) {
  if (typeof data === 'function') {
    return createItem.bind(this)().save(); // TODO - detect if promise
  }

  var newObject = getStore(this.App).createRecord(name),
      key, val;

  for (key in data) {
    if (data.hasOwnProperty(key)) {
      val = data[key];

      if (typeof val === 'function') {
        val = val.call(this, newObject.get(key));
      }

      if (typeof val !== 'undefined') {
        newObject.set(key, val);
      }
    }
  }

  return newObject.save();
}

function fetchItem(name, source) {
  var fetchFn;

  if (source === 'listRandom') {
    fetchFn = getRandomFromList.bind(this, name);
  } else if (source === 'listFilter') {
    // TODO - handle listFilter
  } else if (source === 'create') {
    // TODO - handle create
  } else if (typeof source === 'number' || typeof source === 'string') {
    var store = getStore(this.App);
    fetchFn = store.find.bind(store, name, source);
  } else if (typeof source === 'function') {
    fetchFn = source.bind(this);
  } else {
    Ember.assert("Improper source specified");
    return;
  }

  return fetchFn(); // TODO - promise wrap
}

function updateItem(item, data) {
  debugger;
}

function createAllowedTest(promise, successMessage, failureMessage) {
  async();
  return promise
    .then(handleSuccess(successMessage), handleFailure(failureMessage))
    .finally(asyncDone);
}

function createForbidTest(promise, successMessage, failureMessage) {
  async();
  return promise
    .then(handleFailure(failureMessage), handleSuccess(successMessage))
    .finally(asyncDone);
}

function testUpdate(name, source, data) {
  return createAllowedTest(
    fetchItem.call(this, name, source)
      .then(function(item) {
        return updateItem(item, data);
      }),
    name + " is updatable",
    name + " failed to be updated"
  );
}

function forbidUpdate(name, source, data) {
  return createForbidTest(
    fetchItem.call(this, name, source)
      .then(function(item) {
        return updateItem(item, data);
      }),
    name + " cannot be updated",
    name + " should NOT be updatable"
  );
}

function testDelete(name, source) {
  return createAllowedTest(
    fetchItem.call(this, name, source)
      .then(function(item) {
        return item.destroyRecord();
      }),
    name + " is deletable",
    name + " failed to be deleted"
  );
}

function forbidDelete(name, source) {
  return createForbidTest(
    fetchItem.call(this, name, source)
      .then(function(item) {
        return item.destroyRecord();
      }),
    name + " cannot be deleted",
    name + " should NOT be deletable"
  );
}

function testCreate(name, data) {
  return createAllowedTest(
    createItem.call(this, name, data),
    name + " is creatable",
    name + " failed to be created"
  );
}

function forbidCreate(name, data) {
  return createForbidTest(
    createItem.call(this, name, data),
    name + " cannot be created",
    name + " should NOT be creatable"
  );
}

function testList(name) {
  return createAllowedTest(
    getList.call(this, name),
    name + " is listable",
    name + " failed to be listed"
  );
}

function forbidList(name) {
  return createForbidTest(
    getList.call(this, name),
    name + " is not listable",
    name + " should NOT be listable"
  );
}

function testGet(name, source) {
  return createAllowedTest(
    fetchItem.call(this, name, source),
    name + " is readable",
    name + " failed to be fetched"
  );
}

function forbidGet(name, source) {
  return createForbidTest(
    fetchItem.call(this, name, source),
    name + " is not readable",
    name + " should NOT be readable"
  );
}

function handleSuccess(message) {
  return function(arg) {
    ok(true, message || "Promise resolved successfully");
    return arg;
  };
}
function handleFailure(message) {
  return function(arg) {
    ok(false, message || "Promise was rejected");
    return arg;
  };
}
function async() {
  QUnit.stop();
}
function asyncDone(arg) {
  QUnit.start();
  return arg;
}

export { generate };
<|endoftext|>


<commit_before>(function () {
  "use strict";

  var _ = require("lodash"),
    chordFactory = require("./chords"),
    rhythmFactory = require("./rhythm"),
    melodyFactory = require("./melody"),
    abc = require("./abc");

  var SONG_STRUCTURE = "VVRVRVRR";
  /**

    @lyrics {Array[Array[[String]]} All the lyrics. lyrics[2][3] is the 3rd line of the 2nd verse (0-index natch)
    @inspiration {String} the one good line
    @voicePart {String} "B" for bass
  */
  var generateMusic = function (inputLyrics, inspiration, voicePart) {
    var key = "G";
    voicePart = "B"; // obviously it's a cheat that we secretly change this to bass

    var chords = [];
    var lyrics = [];
    var rhythm = [];
    var melody = [];

    var refrainChords = chordFactory.getChords();
    var refrainLyrics = inputLyrics[0];
    var lyricIndex = 1;
    var refrainRhythm = rhythmFactory.getRhythm(refrainLyrics);
    var refrainMelody = melodyFactory.getMelody(key, voicePart, refrainRhythm, refrainChords);
    var verseChords = chordFactory.getChords();

    _.each(SONG_STRUCTURE, function (stanzaType) {
      var verseLyrics,
        verseRhythm;

      if (stanzaType === 'R') {
        chords.push(refrainChords);
        lyrics.push(refrainLyrics);
        rhythm.push(refrainRhythm);
        melody.push(refrainMelody);
      } else if (stanzaType === 'V') {
        chords.push(verseChords);
        verseLyrics = inputLyrics[lyricIndex++];
        lyrics.push(verseLyrics);
        // TODO: really the rhythm and the melody should be pretty much the same
        // for all verses, with minor tweaks for varying syllable count
        verseRhythm = rhythmFactory.getRhythm(verseLyrics);
        rhythm.push(verseRhythm);
        melody.push(melodyFactory.getMelody(key, voicePart, verseRhythm, verseChords));

      } else {
          // one day a bridge?
      }

    });
    return abc.getAbc(_.flatten(lyrics), _.flatten(chords), _.flatten(melody, true), _.flatten(rhythm, true), inspiration);
  };
  exports.generateMusic = generateMusic;

}());
<commit_msg>use adaptor to make verses similar<commit_after>(function () {
  "use strict";

  var _ = require("lodash"),
    adaptor = require("./adaptor"),
    chordFactory = require("./chords"),
    rhythmFactory = require("./rhythm"),
    melodyFactory = require("./melody"),
    abc = require("./abc");

  var SONG_STRUCTURE = "VVRVRVRR";
  /**

    @lyrics {Array[Array[[String]]} All the lyrics. lyrics[2][3] is the 3rd line of the 2nd verse (0-index natch)
    @inspiration {String} the one good line
    @voicePart {String} "B" for bass
  */
  var generateMusic = function (inputLyrics, inspiration, voicePart) {
    var key = "G";
    voicePart = "B"; // obviously it's a cheat that we secretly change this to bass

    var chords = [];
    var lyrics = [];
    var rhythm = [];
    var melody = [];

    var lyricIndex = 0;

    var refrainChords = chordFactory.getChords();
    var refrainLyrics = inputLyrics[lyricIndex++];
    var refrainRhythm = rhythmFactory.getRhythm(refrainLyrics);
    var refrainMelody = melodyFactory.getMelody(key, voicePart, refrainRhythm, refrainChords);

    var verseChords = chordFactory.getChords();
    var firstVerseRhythm;
    var firstVerseMelody;

    _.each(SONG_STRUCTURE, function (stanzaType) {
      var verseLyrics;

      if (stanzaType === 'R') {
        chords.push(refrainChords);
        lyrics.push(refrainLyrics);
        rhythm.push(refrainRhythm);
        melody.push(refrainMelody);
      } else if (stanzaType === 'V') {
        chords.push(verseChords);
        verseLyrics = inputLyrics[lyricIndex++];
        lyrics.push(verseLyrics);
        if (!firstVerseRhythm) {
          firstVerseRhythm = rhythmFactory.getRhythm(verseLyrics);
          firstVerseMelody = melodyFactory.getMelody(key, voicePart, firstVerseRhythm, verseChords);
          rhythm.push(firstVerseRhythm);
          melody.push(firstVerseMelody);

        } else {
          // really the rhythm and the melody of any subsequent verse should be pretty much the same
          // for all verses, with minor tweaks for varying syllable count
          var adaptedVerse = adaptor.getAdaptedVerse(verseLyrics, firstVerseRhythm, firstVerseMelody);
          rhythm.push(adaptedVerse.rhythm);
          melody.push(adaptedVerse.melody);
        }

      } else {
          // one day a bridge?
      }

    });
    return abc.getAbc(_.flatten(lyrics), _.flatten(chords), _.flatten(melody, true), _.flatten(rhythm, true), inspiration);
  };
  exports.generateMusic = generateMusic;

}());
<|endoftext|>


<commit_before>'use strict';

var arrayify = require('arrayify'),
    events = require('events'),
    gulpConflict = require('gulp-conflict'),
    gulpTemplate = require('gulp-template'),
    gulpUtil = require('gulp-util'),
    chalk = gulpUtil.colors,
    inquirer = require('inquirer'),
    minimist = require('minimist'),
    path = require('path'),
    util = require('util');

var Config = require('./config.js'),
    TemplateSet = require('./templateset.js');

/**
 * Generator constructor
 *
 * @param {gulp} gulp  gulp instance
 */
function Generator(gulp) {
    events.EventEmitter.call(this);
    this.gulp = gulp;
    this.inquirer = inquirer;
    this.util = gulpUtil;
    this.chalk = chalk;
    this.cwd = process.cwd();
    this.pkgDir = path.dirname(module.parent.parent.filename);
    this.templatesDir = path.join(this.pkgDir, 'templates');
    this.templateSets = [];
    this.config = new Config();
    this.parseParams()
        .addGulpTask();
}

/**
 * inherit from EventEmitter to use events
 */
util.inherits(Generator, events.EventEmitter);

/**
 * add a gulp task to generators gulp instance
 *
 * @param {String} taskName   task name
 * @param {Function} taskFn   task function
 */
Generator.prototype.addGulpTask = function(taskName, taskFn) {
    taskName = typeof taskName === 'string' && taskName.length > 0 ? taskName : 'default';
    taskFn = typeof taskName === 'function' ? taskFn : this.gulpTask.bind(this);
    this.gulp.task(taskName, taskFn);
    return this;
};

/**
 * default gulp task
 *
 * @param  {Function} done  async done()
 * @return {void}
 */
Generator.prototype.gulpTask = function(done) {
    this.done = done;
    this.emit('startingGulpTask', this);
    this.on('afterAskingQuestions', this.scaffold.bind(this));
    this.askQuestions();
};

/**
 * parse cli params
 */
Generator.prototype.parseParams = function() {
    var args = minimist(process.argv.slice(3));
    this.params = {
        nonInteractive: args['non-interactive'] || args.n ? true : false
    };
    return this;
};

/**
 * add one or more templates, with or without condition
 *
 * @param {mixed} sets  template path, template object, array of template paths or template objects
 */
Generator.prototype.addTemplates = function(sets) {
    arrayify(sets).forEach(function(set) {
        var templateSet = new TemplateSet(set);
        if (templateSet.isTemplateSet()) {
            this.templateSets.push(templateSet);
        }
    }.bind(this));
    return this;
};

/**
 * retrieve template sources
 *
 * @return {Array} template paths
 */
Generator.prototype.getTemplateSources = function() {
    return this.templateSets.reduce(function(sources, templateSet) {
        sources = sources.concat(templateSet.getConditionalSources(this.config).map(function(source) {
            return path.join(this.templatesDir, source);
        }.bind(this)));
        return sources;
    }.bind(this), []);
};

/**
 * ask questions
 */
Generator.prototype.askQuestions = function() {
    if (this.params.nonInteractive === false) {
        this.emit('askingQuestions', this);
        this.inquirer.prompt(this.config.getQuestions(), function(answers) {
            this.parseAnswers(answers);
            this.emit('afterAskingQuestions', this);
        }.bind(this));
    } else {
        this.emit('afterAskingQuestions', this);
    }
    return this;
};

/**
 * change config options depending on question answers
 *
 * @param {Object} answers  answer keys and values
 */
Generator.prototype.parseAnswers = function(answers) {
    Object.keys(answers).forEach(function(key) {
        if (this.config.hasOption(key)) {
            this.config.getOption(key).setValue(answers[key]);
        }
    }.bind(this));
    return this;
};

/**
 * run scaffolding
 */
Generator.prototype.scaffold = function() {
    this.emit('scaffolding', this);
    this.gulp.src(this.getTemplateSources(), {dot: true})
        .pipe(gulpTemplate(this.config.getOptionValues()))
        .pipe(gulpConflict(this.cwd + '/'))
        .pipe(this.gulp.dest(this.cwd + '/'))
        .on('end', function() {
            this.emit('afterScaffolding', this);
            this.done();
        }.bind(this));
    return this;
};

/**
 * export Generator
 *
 * @type {Class}
 */
module.exports = Generator;
<commit_msg>add Generator.addOptions as shorthand for Generator.config.addOptions<commit_after>'use strict';

var arrayify = require('arrayify'),
    events = require('events'),
    gulpConflict = require('gulp-conflict'),
    gulpTemplate = require('gulp-template'),
    gulpUtil = require('gulp-util'),
    chalk = gulpUtil.colors,
    inquirer = require('inquirer'),
    minimist = require('minimist'),
    path = require('path'),
    util = require('util');

var Config = require('./config.js'),
    TemplateSet = require('./templateset.js');

/**
 * Generator constructor
 *
 * @param {gulp} gulp  gulp instance
 */
function Generator(gulp) {
    events.EventEmitter.call(this);
    this.gulp = gulp;
    this.inquirer = inquirer;
    this.util = gulpUtil;
    this.chalk = chalk;
    this.cwd = process.cwd();
    this.pkgDir = path.dirname(module.parent.parent.filename);
    this.templatesDir = path.join(this.pkgDir, 'templates');
    this.templateSets = [];
    this.config = new Config();
    this.parseParams()
        .addGulpTask();
}

/**
 * inherit from EventEmitter to use events
 */
util.inherits(Generator, events.EventEmitter);

/**
 * add a gulp task to generators gulp instance
 *
 * @param {String} taskName   task name
 * @param {Function} taskFn   task function
 */
Generator.prototype.addGulpTask = function(taskName, taskFn) {
    taskName = typeof taskName === 'string' && taskName.length > 0 ? taskName : 'default';
    taskFn = typeof taskName === 'function' ? taskFn : this.gulpTask.bind(this);
    this.gulp.task(taskName, taskFn);
    return this;
};

/**
 * default gulp task
 *
 * @param  {Function} done  async done()
 * @return {void}
 */
Generator.prototype.gulpTask = function(done) {
    this.done = done;
    this.emit('startingGulpTask', this);
    this.on('afterAskingQuestions', this.scaffold.bind(this));
    this.askQuestions();
};

/**
 * parse cli params
 */
Generator.prototype.parseParams = function() {
    var args = minimist(process.argv.slice(3));
    this.params = {
        nonInteractive: args['non-interactive'] || args.n ? true : false
    };
    return this;
};

Generator.prototype.addOptions = function(options) {
    this.config.addOptions(options);
    return this;
};

/**
 * add one or more templates, with or without condition
 *
 * @param {mixed} sets  template path, template object, array of template paths or template objects
 */
Generator.prototype.addTemplates = function(sets) {
    arrayify(sets).forEach(function(set) {
        var templateSet = new TemplateSet(set);
        if (templateSet.isTemplateSet()) {
            this.templateSets.push(templateSet);
        }
    }.bind(this));
    return this;
};

/**
 * retrieve template sources
 *
 * @return {Array} template paths
 */
Generator.prototype.getTemplateSources = function() {
    return this.templateSets.reduce(function(sources, templateSet) {
        sources = sources.concat(templateSet.getConditionalSources(this.config).map(function(source) {
            return path.join(this.templatesDir, source);
        }.bind(this)));
        return sources;
    }.bind(this), []);
};

/**
 * ask questions
 */
Generator.prototype.askQuestions = function() {
    if (this.params.nonInteractive === false) {
        this.emit('askingQuestions', this);
        this.inquirer.prompt(this.config.getQuestions(), function(answers) {
            this.parseAnswers(answers);
            this.emit('afterAskingQuestions', this);
        }.bind(this));
    } else {
        this.emit('afterAskingQuestions', this);
    }
    return this;
};

/**
 * change config options depending on question answers
 *
 * @param {Object} answers  answer keys and values
 */
Generator.prototype.parseAnswers = function(answers) {
    Object.keys(answers).forEach(function(key) {
        if (this.config.hasOption(key)) {
            this.config.getOption(key).setValue(answers[key]);
        }
    }.bind(this));
    return this;
};

/**
 * run scaffolding
 */
Generator.prototype.scaffold = function() {
    this.emit('scaffolding', this);
    this.gulp.src(this.getTemplateSources(), {dot: true})
        .pipe(gulpTemplate(this.config.getOptionValues()))
        .pipe(gulpConflict(this.cwd + '/'))
        .pipe(this.gulp.dest(this.cwd + '/'))
        .on('end', function() {
            this.emit('afterScaffolding', this);
            this.done();
        }.bind(this));
    return this;
};

/**
 * export Generator
 *
 * @type {Class}
 */
module.exports = Generator;
<|endoftext|>


<commit_before>var config = require("../config/config.js");
var DataModel = require("../model/datamodel.js");

var googleapis = require("googleapis");
var OAuth2Client = googleapis.OAuth2Client;
var moment = require("moment");

//Class Declaration

function GoogleCal(){
    this.clientID = config.gcal.clientID;
    this.clientSecret = config.gcal.clientSecret;
    this.account = config.gcal.account;

    this.oauth2Client = new OAuth2Client(this.clientID,this.clientSecret)
    this.oauth2Client.credentials = {
        access_token:  config.gcal.access_token,
        refresh_token: config.gcal.refresh_token
    };

    this.hostname = config.gcal.hostname;
    this.path = config.gcal.path;

    this.startDate = moment().startOf("day").toISOString();
	this.endDate = moment().endOf("day").toISOString();
    this.dateWords = ["mon","tue","tues","wed","thur","thurs","fri","sat","sun","monday","tuesday","wednesday","thursday","friday","saturday","yesterday","today","tonight","tomorrow"];

    this.output = [];
    this.outputCount = 0;
    this.outputLimit = 0;

    this.ircCallback = function(){};
};

module.exports = function(data){
    return new GoogleCal().set(data);
};

//Class Methods

GoogleCal.prototype = DataModel();

//IRC Methods

GoogleCal.prototype.ircRequest = function(Input){
    this.set({
        ircCallback: Input.callback,
        outputLimit: this.setOutputLimit(Input)
    });
    this.ircRouteRequest(Input);
};

GoogleCal.prototype.ircRouteRequest = function(Input){
    var keyword = Input.method == "onduty" ? "on-call" : Input.method;
    var date = Input.targetDate !== "" ? Input.targetDate : false;
    var range = (Input.range === 0 ? 1 : Input.range);
    var callback = this.ircHandleResult.bind(this);
    var name = Input.users.length > 0 ? Input.users[0].name : "";
    var next = Input.contains("options","next");

    this.getEventsByDate(keyword,date,range,callback,name,next);
};

GoogleCal.prototype.ircHandleResult = function(err,events){
    if (err){
        this.ircHandleError(err);
    }else{
        var l = events.length
        if (l < 1){
            this.setOne("output","Hm, I couldn't find anything for that. Sorry :(");
        }else{
            this.ircEventsFromResult(events);
        }
    }
};

GoogleCal.prototype.ircEventsFromResult = function(events){
    events.forEach(assembleLine.bind(this));

    function assembleLine(elem,ind,arr){
        if (ind < this.outputLimit){
            if (elem.start.date && elem.start.date !== moment(elem.end.date).subtract("days",1).format("YYYY-MM-DD")){
                this.setOne("output","["+moment(elem.start.date).format("ddd MM/DD")+" to "+moment(elem.end.date).subtract("days",1).format("ddd MM/DD")+" | "+elem.summary+"]");
            }else{
                this.setOne("output","["+moment(elem.start.dateTime ? elem.start.dateTime : elem.start.date).format("ddd MM/DD")+" | "+elem.summary+"]");
            }
        }
    }
        this.ircOutputResult();
};

GoogleCal.prototype.ircNamesFromResult = function(err,events){
    if (err){
        this.ircHandleError(err);
    }else{
        for (u in config.users){
            var user = config.users[u];
            if (events[0].summary.indexOf(user.name) > -1){
                this.ircCallback(user.name);
            }
        }
    }
};

GoogleCal.prototype.ircHandleError = function(err){
    console.log(err,"Google Calendar API Request Error");
    this.setOne("output","Bad Google API Response :(");
    this.ircOutputResult();
};

GoogleCal.prototype.ircOutputResult = function(){
    this.ircCallback(this.output);
    this.output = [];
};

//IRC Helper Methods

GoogleCal.prototype.setOutputLimit = function(Input){
    return Input.range > 0 ? Input.range : (Input.method === "ooo" && Input.users.length < 1 ? 99 : 1);
}

//API Methods

GoogleCal.prototype.getEventsByDate = function(keyword,date,range,callback,name,next){
    if (keyword === "on-call"){
        if (name){
            this.getOnDutyByName(date,range,name,next,callback);
        }else{
            this.getOnDuty(date,range,next,callback);
        }
    }else if (keyword === "ooo"){
        if (name){
            this.getOOOByName(date,range,name,next,callback);
        }else{
            this.getOOO(date,range,next,callback);
        }
    }else if (keyword === "wfh"){
        if (name){
            this.getWFHByName(date,range,name,next,callback);
        }else{
            this.getWFH(date,range,next,callback);
        }
    }
};

GoogleCal.prototype.getOnDuty = function(date,range,next,callback){
    var r = this.getDateRange(date,range,"day",next);
    var apiCallback = this.filterResults.bind(this,"on-call","",r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getOOO = function(date,range,next,callback){
    var r = this.getDateRange(date,range,"day",next);
    var apiCallback = this.filterResults.bind(this,"ooo","",r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getWFH = function(date,range,next,callback){
    var r = this.getDateRange(date,range,"day",next);
    var apiCallback = this.filterResults.bind(this,"wfh","",r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getOnDutyByName = function(date,range,name,next,callback){
    var r = this.getDateRange(date,range,"month",next);
    var apiCallback = this.filterResults.bind(this,"on-call",name,r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getOOOByName = function(date,range,name,next,callback){
    var r = this.getDateRange(date,range,"month",next);
    var apiCallback = this.filterResults.bind(this,"ooo",name,r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getWFHByName = function(date,range,name,next,callback){
    var r = this.getDateRange(date,range,"month",next);
    var apiCallback = this.filterResults.bind(this,"wfh",name,r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getEventsByRange = function(startDate,endDate,apiCallback){
    var query = {
        calendarId: this.account,
        timeMin: startDate,
        timeMax: endDate,
        orderBy: "startTime",
        singleEvents: true
    };
    this.calendarQuery(query,apiCallback);
};

GoogleCal.prototype.calendarQuery = function(query,apiCallback){
    googleapis.discover("calendar","v3").execute(connect.bind(this));

    function connect(err,client){
        if (err){
            apiCallback(err);
        }else{
            client.calendar.events.list(query).withAuthClient(this.oauth2Client).execute(apiCallback);
        }
    }
};

//API Helper Methods

GoogleCal.prototype.getDateRange = function(date,range,rangeUnit,next){
    var startDate =  moment().startOf("day").toISOString();
    var endDate = moment().endOf("day").toISOString();

    switch (date)
        {
        case "yesterday":
            startDate = this.changeDate("subtract",1,"days",startDate);
            break;
        case "today":
        case "tonight":
            break;
        case "tomorrow":
            startDate = this.changeDate("add",1,"days",startDate);
            break;
        default:
            if (moment(date,"MM/DD")._pf.charsLeftOver == 0){
                startDate = moment(date,"MM/DD").startOf("day").toISOString();
                //If Target Month is Before This Month, Advance to Next Year
                if (moment(startDate).isBefore(moment(),"month")){
                    startDate = moment(startDate).add("year",1).toISOString();
                }
            }else if (moment(date,["MM/DD/YY","MM/DD/YYYY"])._pf.charsLeftOver == 0){
                startDate = moment(date,["MM/DD","MM/DD/YY","MM/DD/YYYY"]).startOf("day").toISOString();
            }else if (this.contains("dateWords",date)){
                startDate = this.toWeekday(date,next);
            }
            break;
        }
        endDate = moment(startDate).endOf(rangeUnit).add(rangeUnit,range-1).toISOString();

    return {"startDate":startDate,"endDate":endDate};
};

GoogleCal.prototype.changeDate = function(mode,amt,unit,target){
    return moment(target)[mode](unit,amt).toISOString();
};

GoogleCal.prototype.toWeekday = function(date,next){
    var weekday = moment().day(date).startOf("day").toISOString();
    var dayIsPast = moment(weekday).isBefore(moment(),"day");

    return (dayIsPast || !dayIsPast && next) ? moment(weekday).add("week",1).toISOString() : weekday;
};

GoogleCal.prototype.filterResults = function(keyword,user,startDate,endDate,callback,error,results){
    if (error){
        callback(error);
    }else{
        var events = [];
        results.items.forEach(filterForKeyword);

        function filterForKeyword(elem,index,arr){
            if (elem.summary.toLowerCase().indexOf(keyword) > -1){
                events.push(elem);
            }
        }
        for (i = events.length - 1; i>=0; i--){
            var e = events[i];
            //If Getting Cases for a Specific User, Remove all Events Not for that User
            if (user !== "" && e.summary.indexOf(user) == -1){
                events.splice(events.indexOf(e),1);
            //Multi-Day Event Filtering Fix... Future Events Get Incorrectly Returned by API
            }else if (e.start.date && moment(e.start.date).isAfter(endDate)){
                events.splice(events.indexOf(e),1);
            }
        }
        callback(null,events);
    }
};
<commit_msg>Speak When No Calendar Results Found<commit_after>var config = require("../config/config.js");
var DataModel = require("../model/datamodel.js");

var googleapis = require("googleapis");
var OAuth2Client = googleapis.OAuth2Client;
var moment = require("moment");

//Class Declaration

function GoogleCal(){
    this.clientID = config.gcal.clientID;
    this.clientSecret = config.gcal.clientSecret;
    this.account = config.gcal.account;

    this.oauth2Client = new OAuth2Client(this.clientID,this.clientSecret)
    this.oauth2Client.credentials = {
        access_token:  config.gcal.access_token,
        refresh_token: config.gcal.refresh_token
    };

    this.hostname = config.gcal.hostname;
    this.path = config.gcal.path;

    this.startDate = moment().startOf("day").toISOString();
	this.endDate = moment().endOf("day").toISOString();
    this.dateWords = ["mon","tue","tues","wed","thur","thurs","fri","sat","sun","monday","tuesday","wednesday","thursday","friday","saturday","yesterday","today","tonight","tomorrow"];

    this.output = [];
    this.outputCount = 0;
    this.outputLimit = 0;

    this.ircCallback = function(){};
};

module.exports = function(data){
    return new GoogleCal().set(data);
};

//Class Methods

GoogleCal.prototype = DataModel();

//IRC Methods

GoogleCal.prototype.ircRequest = function(Input){
    this.set({
        ircCallback: Input.callback,
        outputLimit: this.setOutputLimit(Input)
    });
    this.ircRouteRequest(Input);
};

GoogleCal.prototype.ircRouteRequest = function(Input){
    var keyword = Input.method == "onduty" ? "on-call" : Input.method;
    var date = Input.targetDate !== "" ? Input.targetDate : false;
    var range = (Input.range === 0 ? 1 : Input.range);
    var callback = this.ircHandleResult.bind(this);
    var name = Input.users.length > 0 ? Input.users[0].name : "";
    var next = Input.contains("options","next");

    this.getEventsByDate(keyword,date,range,callback,name,next);
};

GoogleCal.prototype.ircHandleResult = function(err,events){
    if (err){
        this.ircHandleError(err);
    }else{
        var l = events.length
        if (l < 1){
            this.setOne("output","Hm, I couldn't find anything for that. Sorry :(");
            this.ircOutputResult();
        }else{
            this.ircEventsFromResult(events);
        }
    }
};

GoogleCal.prototype.ircEventsFromResult = function(events){
    events.forEach(assembleLine.bind(this));

    function assembleLine(elem,ind,arr){
        if (ind < this.outputLimit){
            if (elem.start.date && elem.start.date !== moment(elem.end.date).subtract("days",1).format("YYYY-MM-DD")){
                this.setOne("output","["+moment(elem.start.date).format("ddd MM/DD")+" to "+moment(elem.end.date).subtract("days",1).format("ddd MM/DD")+" | "+elem.summary+"]");
            }else{
                this.setOne("output","["+moment(elem.start.dateTime ? elem.start.dateTime : elem.start.date).format("ddd MM/DD")+" | "+elem.summary+"]");
            }
        }
    }
        this.ircOutputResult();
};

GoogleCal.prototype.ircNamesFromResult = function(err,events){
    if (err){
        this.ircHandleError(err);
    }else{
        for (u in config.users){
            var user = config.users[u];
            if (events[0].summary.indexOf(user.name) > -1){
                this.ircCallback(user.name);
            }
        }
    }
};

GoogleCal.prototype.ircHandleError = function(err){
    console.log(err,"Google Calendar API Request Error");
    this.setOne("output","Bad Google API Response :(");
    this.ircOutputResult();
};

GoogleCal.prototype.ircOutputResult = function(){
    this.ircCallback(this.output);
    this.output = [];
};

//IRC Helper Methods

GoogleCal.prototype.setOutputLimit = function(Input){
    return Input.range > 0 ? Input.range : (Input.method === "ooo" && Input.users.length < 1 ? 99 : 1);
}

//API Methods

GoogleCal.prototype.getEventsByDate = function(keyword,date,range,callback,name,next){
    if (keyword === "on-call"){
        if (name){
            this.getOnDutyByName(date,range,name,next,callback);
        }else{
            this.getOnDuty(date,range,next,callback);
        }
    }else if (keyword === "ooo"){
        if (name){
            this.getOOOByName(date,range,name,next,callback);
        }else{
            this.getOOO(date,range,next,callback);
        }
    }else if (keyword === "wfh"){
        if (name){
            this.getWFHByName(date,range,name,next,callback);
        }else{
            this.getWFH(date,range,next,callback);
        }
    }
};

GoogleCal.prototype.getOnDuty = function(date,range,next,callback){
    var r = this.getDateRange(date,range,"day",next);
    var apiCallback = this.filterResults.bind(this,"on-call","",r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getOOO = function(date,range,next,callback){
    var r = this.getDateRange(date,range,"day",next);
    var apiCallback = this.filterResults.bind(this,"ooo","",r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getWFH = function(date,range,next,callback){
    var r = this.getDateRange(date,range,"day",next);
    var apiCallback = this.filterResults.bind(this,"wfh","",r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getOnDutyByName = function(date,range,name,next,callback){
    var r = this.getDateRange(date,range,"month",next);
    var apiCallback = this.filterResults.bind(this,"on-call",name,r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getOOOByName = function(date,range,name,next,callback){
    var r = this.getDateRange(date,range,"month",next);
    var apiCallback = this.filterResults.bind(this,"ooo",name,r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getWFHByName = function(date,range,name,next,callback){
    var r = this.getDateRange(date,range,"month",next);
    var apiCallback = this.filterResults.bind(this,"wfh",name,r.startDate,r.endDate,callback)
    this.getEventsByRange(r.startDate,r.endDate,apiCallback)
};

GoogleCal.prototype.getEventsByRange = function(startDate,endDate,apiCallback){
    var query = {
        calendarId: this.account,
        timeMin: startDate,
        timeMax: endDate,
        orderBy: "startTime",
        singleEvents: true
    };
    this.calendarQuery(query,apiCallback);
};

GoogleCal.prototype.calendarQuery = function(query,apiCallback){
    googleapis.discover("calendar","v3").execute(connect.bind(this));

    function connect(err,client){
        if (err){
            apiCallback(err);
        }else{
            client.calendar.events.list(query).withAuthClient(this.oauth2Client).execute(apiCallback);
        }
    }
};

//API Helper Methods

GoogleCal.prototype.getDateRange = function(date,range,rangeUnit,next){
    var startDate =  moment().startOf("day").toISOString();
    var endDate = moment().endOf("day").toISOString();

    switch (date)
        {
        case "yesterday":
            startDate = this.changeDate("subtract",1,"days",startDate);
            break;
        case "today":
        case "tonight":
            break;
        case "tomorrow":
            startDate = this.changeDate("add",1,"days",startDate);
            break;
        default:
            if (moment(date,"MM/DD")._pf.charsLeftOver == 0){
                startDate = moment(date,"MM/DD").startOf("day").toISOString();
                //If Target Month is Before This Month, Advance to Next Year
                if (moment(startDate).isBefore(moment(),"month")){
                    startDate = moment(startDate).add("year",1).toISOString();
                }
            }else if (moment(date,["MM/DD/YY","MM/DD/YYYY"])._pf.charsLeftOver == 0){
                startDate = moment(date,["MM/DD","MM/DD/YY","MM/DD/YYYY"]).startOf("day").toISOString();
            }else if (this.contains("dateWords",date)){
                startDate = this.toWeekday(date,next);
            }
            break;
        }
        endDate = moment(startDate).endOf(rangeUnit).add(rangeUnit,range-1).toISOString();

    return {"startDate":startDate,"endDate":endDate};
};

GoogleCal.prototype.changeDate = function(mode,amt,unit,target){
    return moment(target)[mode](unit,amt).toISOString();
};

GoogleCal.prototype.toWeekday = function(date,next){
    var weekday = moment().day(date).startOf("day").toISOString();
    var dayIsPast = moment(weekday).isBefore(moment(),"day");

    return (dayIsPast || !dayIsPast && next) ? moment(weekday).add("week",1).toISOString() : weekday;
};

GoogleCal.prototype.filterResults = function(keyword,user,startDate,endDate,callback,error,results){
    if (error){
        callback(error);
    }else{
        var events = [];
        results.items.forEach(filterForKeyword);

        function filterForKeyword(elem,index,arr){
            if (elem.summary.toLowerCase().indexOf(keyword) > -1){
                events.push(elem);
            }
        }
        for (i = events.length - 1; i>=0; i--){
            var e = events[i];
            //If Getting Cases for a Specific User, Remove all Events Not for that User
            if (user !== "" && e.summary.indexOf(user) == -1){
                events.splice(events.indexOf(e),1);
            //Multi-Day Event Filtering Fix... Future Events Get Incorrectly Returned by API
            }else if (e.start.date && moment(e.start.date).isAfter(endDate)){
                events.splice(events.indexOf(e),1);
            }
        }
        callback(null,events);
    }
};
<|endoftext|>


<commit_before>// Deps
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;

// Const
const PLUGIN_NAME = 'gulp-void';

// Plugin level function (dealing with files)
function gulpVoid(options) {

    // Creating a stream through which each file will pass
    return through.obj(function(file, enc, cb) {

        if (file.isNull()) return cb(null, file);

        if (file.isBuffer()) {
            // Do something
        }

        if (file.isStream()) {
            // Do something
        }

        cb(null, file);

    });

}

// Export for use
module.exports = gulpVoid;<commit_msg>Working on reduce pattern<commit_after>// Deps
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;

// Const
const PLUGIN_NAME = 'gulp-void';

// Plugin level function (dealing with files)
function gulpVoid(fn, done, memo) {
    if (!fn instanceof Function) throw new PluginError('gulp-reduce-file', 'Missing iterator callback for gulp-reduce-file');
    if (!done instanceof Function) throw new PluginError('gulp-reduce-file', 'Missing done callback for gulp-reduce-file');

    result = result || '';

    function iterate(file) {
        result = fn(file, memo);
    }

    function end() {
        var content = done(memo),
            target = new File();

        if (typeof content === 'string') content = new Buffer(content);
        if (!(content instanceof Buffer)) content = new Buffer(JSON.stringify(content, null, 2));

        target.path = filename;
        target.contents = content;

        this.emit('data', target);
        this.emit('end');
    }

    return through(iterate, end);

}

// Export for use
module.exports = gulpVoid;<|endoftext|>


<commit_before>'use strict'

const Readable = require('stream').Readable
const { clone, times, once, pick } = require('lodash')
const debug = require('debug')('csw-client:harvester')

class Harvester extends Readable {

  constructor(client, options = {}) {
    const concurrency = options.concurrency || 2
    const step = options.step || 20
    super({ objectMode: true, highWaterMark: options.highWaterMark || step * concurrency })
    this.client = client
    this.options = options
    this.step = step
    this.concurrency = concurrency
    this.returned = 0
    this.duplicate = 0
    this.recordErrors = 0
    this.progression = 0
    this.typesCount = {}
    this.returnedPages = 0
    this.erroredPages = 0
    this.recordIds = new Set()
    this.activityTimeout = options.activityTimeout || 20000
    debug('new harvester (concurrency=%d, step=%d)', concurrency, step)
  }

  renewActivityTimeout() {
    if (this.finished) return
    this.clearActivityTimeout()
    this._activityTimeout = setTimeout(() => {
      this.finish(new Error('Harvesting timeout'))
    }, this.activityTimeout)
  }

  clearActivityTimeout() {
    if (this._activityTimeout) {
      clearTimeout(this._activityTimeout)
    }
  }

  progress(count) {
    this.progression = this.progression + count
    this.emit('progress', count)
  }

  _read() {
    if (this.finished) return

    if (!this.started) {
      this.init()
    } else {
      this.fetchMoreRecords()
    }
  }

  async init() {
    const startDate = new Date()

    try {
      const count = await this.client.count(clone(this.options))
      this.started = startDate
      this.renewActivityTimeout()
      debug('found %d records', count)

      this.matched = count
      this.offset = 0
      this.pendingRequests = 0
      this.emit('started')

      if (count === 0) {
        this.finish()
      } else {
        this.fetchMoreRecords()
      }
    } catch (err) {
      debug('error in count operation: %s', err)
      const newError =  new Error('Error in count operation')
      newError.err = err
      this.finish(newError)
    }
  }

  increaseTypeCount(type) {
    if (!(type in this.typesCount)) {
      this.typesCount[type] = 1
    } else {
      this.typesCount[type]++
    }
  }

  processRecord(record) {
    if (this.finished) return

    if (!record.id) {
      this.recordErrors++
      this.emit('record:error', record)
    } else if (this.recordIds.has(record.id)) {
      this.duplicate++
      this.emit('record:duplicate', record)
    } else {
      this.returned++
      this.recordIds.add(record.id)
      this.increaseTypeCount(record.type)
      this.emit('record', record)
      this.push(record)
    }
  }

  async fetchRecords() {
    if (!this.hasMoreRecords()) return

    const expected = Math.min(this.matched - this.offset, this.step)

    const query = Object.assign({}, this.options, {
      maxRecords: this.step,
      startPosition: this.offset + 1,
    })

    this.offset = this.offset + this.step

    this.pendingRequests++
    debug('fetching records from %d', query.startPosition)

    const decreasePendingRequests = once(() => this.pendingRequests--)

    try {
      const result = await this.client.records(query)
      decreasePendingRequests()

      this.returnedPages++
      const returned = result.records.length

      debug('returned %d records', returned)
      if (returned < expected) {
        debug('missed %d records (not returned by service). Expected: %d - Returned: %d', expected - returned, expected, returned)
        this.fetchMoreRecords()
      }
      if (returned > expected) {
        this.finish(new Error('Fatal: more records returned than expected'))
      }
      result.records.forEach(record => this.processRecord(record))
    } catch (err) {
      decreasePendingRequests()
      this.erroredPages++
      debug('error while fetching records from %d: %s', query.startPosition, err)
      debug('missed %d records (request failed)', expected)
      const newError = new Error('Error in fetch operation')
      newError.err = err
      this.emit('pageError', newError)
      this.fetchMoreRecords()
    }

    this.renewActivityTimeout()
    this.progress(expected)

    if (!this.hasMoreRecords() && this.pendingRequests === 0) {
      this.finish()
    }
  }

  fetchMoreRecords() {
    if (!this.hasMoreRecords()) return
    if (this.pendingRequests >= this.concurrency) return
    times(this.concurrency - this.pendingRequests, () => this.fetchRecords())
  }

  hasMoreRecords() {
    if (this._hasMoreRecords === false) return false
    if (this.offset < this.matched) return true
    this._hasMoreRecords = false
    debug('no more records: finishing %d pending requests', this.pendingRequests)
    return false
  }

  computeFinishedMetrics() {
    this.exhaustive = this.matched === this.recordIds.size
    this.duration = (this.finished - this.started) / 1000
    this.speed = Number((this.returned / this.duration).toFixed(2))
  }

  setFinished(status) {
    if (this.finished) return

    this.finished = new Date()
    this.status = status
    this.computeFinishedMetrics()
    this.emit('finished')
    debug('finished with the following status: %s', status)
  }

  finish(err) {
    if (this.finished) return
    this.clearActivityTimeout()

    if (err) {
      this.setFinished('failed')
      debug('finished with following error: %s', err.message)
      this.destroy(err)
    } else {
      this.setFinished('successful')
      this.push(null)
    }
  }

  toJSON() {
    const obj = pick(
      this,
      'finished',
      'started',
      'duration',
      'speed',
      'status',
      'matched',
      'returned',
      'duplicate',
      'exhaustive',
      'recordErrors',
      'typesCount',
      'erroredPages',
      'returnedPages',
    )
    obj.compatOptions = [...this.client.compatOptions]
    obj.originalServiceURL = this.client.originalServiceURL
    obj.redirections = [...this.client.redirections]
    obj.serviceURL = this.client.serviceURL.href
    return obj
  }

}

module.exports = Harvester
<commit_msg>Add missed counter to Harvester<commit_after>'use strict'

const Readable = require('stream').Readable
const { clone, times, once, pick } = require('lodash')
const debug = require('debug')('csw-client:harvester')

class Harvester extends Readable {

  constructor(client, options = {}) {
    const concurrency = options.concurrency || 2
    const step = options.step || 20
    super({ objectMode: true, highWaterMark: options.highWaterMark || step * concurrency })
    this.client = client
    this.options = options
    this.step = step
    this.concurrency = concurrency
    this.returned = 0
    this.duplicate = 0
    this.missed = 0
    this.recordErrors = 0
    this.progression = 0
    this.typesCount = {}
    this.returnedPages = 0
    this.erroredPages = 0
    this.recordIds = new Set()
    this.activityTimeout = options.activityTimeout || 20000
    debug('new harvester (concurrency=%d, step=%d)', concurrency, step)
  }

  renewActivityTimeout() {
    if (this.finished) return
    this.clearActivityTimeout()
    this._activityTimeout = setTimeout(() => {
      this.finish(new Error('Harvesting timeout'))
    }, this.activityTimeout)
  }

  clearActivityTimeout() {
    if (this._activityTimeout) {
      clearTimeout(this._activityTimeout)
    }
  }

  progress(count) {
    this.progression = this.progression + count
    this.emit('progress', count)
  }

  _read() {
    if (this.finished) return

    if (!this.started) {
      this.init()
    } else {
      this.fetchMoreRecords()
    }
  }

  async init() {
    const startDate = new Date()

    try {
      const count = await this.client.count(clone(this.options))
      this.started = startDate
      this.renewActivityTimeout()
      debug('found %d records', count)

      this.matched = count
      this.offset = 0
      this.pendingRequests = 0
      this.emit('started')

      if (count === 0) {
        this.finish()
      } else {
        this.fetchMoreRecords()
      }
    } catch (err) {
      debug('error in count operation: %s', err)
      const newError =  new Error('Error in count operation')
      newError.err = err
      this.finish(newError)
    }
  }

  increaseTypeCount(type) {
    if (!(type in this.typesCount)) {
      this.typesCount[type] = 1
    } else {
      this.typesCount[type]++
    }
  }

  processRecord(record) {
    if (this.finished) return

    if (!record.id) {
      this.recordErrors++
      this.emit('record:error', record)
    } else if (this.recordIds.has(record.id)) {
      this.duplicate++
      this.emit('record:duplicate', record)
    } else {
      this.returned++
      this.recordIds.add(record.id)
      this.increaseTypeCount(record.type)
      this.emit('record', record)
      this.push(record)
    }
  }

  async fetchRecords() {
    if (!this.hasMoreRecords()) return

    const expected = Math.min(this.matched - this.offset, this.step)

    const query = Object.assign({}, this.options, {
      maxRecords: this.step,
      startPosition: this.offset + 1,
    })

    this.offset = this.offset + this.step

    this.pendingRequests++
    debug('fetching records from %d', query.startPosition)

    const decreasePendingRequests = once(() => this.pendingRequests--)

    try {
      const result = await this.client.records(query)
      decreasePendingRequests()

      this.returnedPages++
      const returned = result.records.length

      debug('returned %d records', returned)
      if (returned < expected) {
        const missed = expected - returned
        this.missed = this.missed + missed
        debug('missed %d records (not returned by service). Expected: %d - Returned: %d', missed, expected, returned)
        this.fetchMoreRecords()
      }
      if (returned > expected) {
        this.finish(new Error('Fatal: more records returned than expected'))
      }
      result.records.forEach(record => this.processRecord(record))
    } catch (err) {
      decreasePendingRequests()
      this.erroredPages++
      debug('error while fetching records from %d: %s', query.startPosition, err)
      debug('missed %d records (request failed)', expected)
      const newError = new Error('Error in fetch operation')
      newError.err = err
      this.emit('pageError', newError)
      this.fetchMoreRecords()
    }

    this.renewActivityTimeout()
    this.progress(expected)

    if (!this.hasMoreRecords() && this.pendingRequests === 0) {
      this.finish()
    }
  }

  fetchMoreRecords() {
    if (!this.hasMoreRecords()) return
    if (this.pendingRequests >= this.concurrency) return
    times(this.concurrency - this.pendingRequests, () => this.fetchRecords())
  }

  hasMoreRecords() {
    if (this._hasMoreRecords === false) return false
    if (this.offset < this.matched) return true
    this._hasMoreRecords = false
    debug('no more records: finishing %d pending requests', this.pendingRequests)
    return false
  }

  computeFinishedMetrics() {
    this.exhaustive = this.matched === this.recordIds.size
    this.duration = (this.finished - this.started) / 1000
    this.speed = Number((this.returned / this.duration).toFixed(2))
  }

  setFinished(status) {
    if (this.finished) return

    this.finished = new Date()
    this.status = status
    this.computeFinishedMetrics()
    this.emit('finished')
    debug('finished with the following status: %s', status)
  }

  finish(err) {
    if (this.finished) return
    this.clearActivityTimeout()

    if (err) {
      this.setFinished('failed')
      debug('finished with following error: %s', err.message)
      this.destroy(err)
    } else {
      this.setFinished('successful')
      this.push(null)
    }
  }

  toJSON() {
    const obj = pick(
      this,
      'finished',
      'started',
      'duration',
      'speed',
      'status',
      'matched',
      'returned',
      'missed',
      'duplicate',
      'exhaustive',
      'recordErrors',
      'typesCount',
      'erroredPages',
      'returnedPages',
    )
    obj.compatOptions = [...this.client.compatOptions]
    obj.originalServiceURL = this.client.originalServiceURL
    obj.redirections = [...this.client.redirections]
    obj.serviceURL = this.client.serviceURL.href
    return obj
  }

}

module.exports = Harvester
<|endoftext|>


<commit_before><commit_msg>fixing links<commit_after><|endoftext|>


<commit_before>var type = require('type');

/**
 * Expose `Index`.
 */

module.exports = Index;

/**
 * Initialize new `Index`.
 *
 * @param {Store} store
 * @param {String} name
 * @param {String} field
 * @param {Object} opts { unique: false, multi: false }
 */

function Index(store, name, field, opts) {
  this.store = store;
  this.name = name;
  this.field = field;
  this.multi = opts.multi || false;
  this.unique = opts.unique || false;
}

/**
 * Get `key`.
 *
 * @param {String|IDBKeyRange} key
 * @param {Function} cb
 */

Index.prototype.get = function(key, cb) {
  var result = [];
  var isUnique = this.unique && type(key) == 'string';
  var opts = { range: key, iterator: iterator };

  this.cursor(opts, function(err) {
    if (err) return cb(err);
    isUnique ? cb(null, result[0]) : cb(null, result);
  });

  function iterator(cursor) {
    result.push(cursor.value);
    cursor.continue();
  }
};

/**
 * Count records by `key`.
 *
 * @param {String|IDBKeyRange} key
 * @param {Function} cb
 */

Index.prototype.count = function(key, cb) {
  var name = this.store.name;
  var indexName = this.name;

  this.store.db.transaction('readonly', [name], function(err, tr) {
    if (err) return cb(err);
    var index = tr.objectStore(name).index(indexName);
    var req = index.count(key);
    req.onerror = cb;
    req.onsuccess = function onsuccess(e) { cb(null, e.target.result) };
  });
};

/**
 * Create cursor.
 * Proxy to `this.store` for convinience.
 *
 * @param {Object} opts
 * @param {Function} cb
 */

Index.prototype.cursor = function(opts, cb) {
  opts.index = this.name;
  this.store.cursor(opts, cb);
};
<commit_msg>parseRange in index.count<commit_after>var type = require('type');
var parseRange = require('./range');

/**
 * Expose `Index`.
 */

module.exports = Index;

/**
 * Initialize new `Index`.
 *
 * @param {Store} store
 * @param {String} name
 * @param {String} field
 * @param {Object} opts { unique: false, multi: false }
 */

function Index(store, name, field, opts) {
  this.store = store;
  this.name = name;
  this.field = field;
  this.multi = opts.multi || false;
  this.unique = opts.unique || false;
}

/**
 * Get `key`.
 *
 * @param {String|IDBKeyRange} key
 * @param {Function} cb
 */

Index.prototype.get = function(key, cb) {
  var result = [];
  var isUnique = this.unique && type(key) == 'string';
  var opts = { range: key, iterator: iterator };

  this.cursor(opts, function(err) {
    if (err) return cb(err);
    isUnique ? cb(null, result[0]) : cb(null, result);
  });

  function iterator(cursor) {
    result.push(cursor.value);
    cursor.continue();
  }
};

/**
 * Count records by `key`.
 *
 * @param {String|IDBKeyRange} key
 * @param {Function} cb
 */

Index.prototype.count = function(key, cb) {
  var name = this.store.name;
  var indexName = this.name;

  this.store.db.transaction('readonly', [name], function(err, tr) {
    if (err) return cb(err);
    var index = tr.objectStore(name).index(indexName);
    var req = index.count(parseRange(key));
    req.onerror = cb;
    req.onsuccess = function onsuccess(e) { cb(null, e.target.result) };
  });
};

/**
 * Create cursor.
 * Proxy to `this.store` for convinience.
 *
 * @param {Object} opts
 * @param {Function} cb
 */

Index.prototype.cursor = function(opts, cb) {
  opts.index = this.name;
  this.store.cursor(opts, cb);
};
<|endoftext|>


<commit_before>var type = require('component-type');
var parseRange = require('./range');

/**
 * Expose `Index`.
 */

module.exports = Index;

/**
 * Initialize new `Index`.
 *
 * @param {Store} store
 * @param {String} name
 * @param {String} field
 * @param {Object} opts { unique: false, multi: false }
 */

function Index(store, name, field, opts) {
  this.store = store;
  this.name = name;
  this.field = field;
  this.multi = opts.multi || opts.multiEntry || false;
  this.unique = opts.unique || false;
}

/**
 * Get `key`.
 *
 * @param {String|IDBKeyRange} key
 * @param {Function} cb
 */

Index.prototype.get = function(key, cb) {
  var result = [];
  var isUnique = this.unique && type(key) == 'string';
  var opts = { range: key, iterator: iterator };

  this.cursor(opts, function(err) {
    if (err) return cb(err);
    isUnique ? cb(null, result[0]) : cb(null, result);
  });

  function iterator(cursor) {
    result.push(cursor.value);
    cursor.continue();
  }
};

/**
 * Count records by `key`.
 *
 * @param {String|IDBKeyRange} key
 * @param {Function} cb
 */

Index.prototype.count = function(key, cb) {
  var name = this.store.name;
  var indexName = this.name;

  this.store.db.transaction('readonly', [name], function(err, tr) {
    if (err) return cb(err);
    var index = tr.objectStore(name).index(indexName);
    var req = index.count(type(key) == 'object' ? parseRange(key) : key);
    req.onerror = cb;
    req.onsuccess = function onsuccess(e) { cb(null, e.target.result) };
  });
};

/**
 * Create cursor.
 * Proxy to `this.store` for convinience.
 *
 * @param {Object} opts
 * @param {Function} cb
 */

Index.prototype.cursor = function(opts, cb) {
  opts.index = this.name;
  this.store.cursor(opts, cb);
};
<commit_msg>simplified index range manipulations<commit_after>var parseRange = require('./range');

/**
 * Expose `Index`.
 */

module.exports = Index;

/**
 * Initialize new `Index`.
 *
 * @param {Store} store
 * @param {String} name
 * @param {String} field
 * @param {Object} opts { unique: false, multi: false }
 */

function Index(store, name, field, opts) {
  this.store = store;
  this.name = name;
  this.field = field;
  this.multi = opts.multi || opts.multiEntry || false;
  this.unique = opts.unique || false;
}

/**
 * Get `key`.
 *
 * @param {String|IDBKeyRange} key
 * @param {Function} cb
 */

Index.prototype.get = function(key, cb) {
  var result = [];
  var isUnique = this.unique;
  var opts = { range: key, iterator: iterator };

  this.cursor(opts, function(err) {
    if (err) return cb(err);
    isUnique ? cb(null, result[0]) : cb(null, result);
  });

  function iterator(cursor) {
    result.push(cursor.value);
    cursor.continue();
  }
};

/**
 * Count records by `key`.
 *
 * @param {String|IDBKeyRange} key
 * @param {Function} cb
 */

Index.prototype.count = function(key, cb) {
  var name = this.store.name;
  var indexName = this.name;

  this.store.db.transaction('readonly', [name], function(err, tr) {
    if (err) return cb(err);
    var index = tr.objectStore(name).index(indexName);
    var req = index.count(parseRange(key));
    req.onerror = cb;
    req.onsuccess = function onsuccess(e) { cb(null, e.target.result) };
  });
};

/**
 * Create cursor.
 * Proxy to `this.store` for convinience.
 *
 * @param {Object} opts
 * @param {Function} cb
 */

Index.prototype.cursor = function(opts, cb) {
  opts.index = this.name;
  this.store.cursor(opts, cb);
};
<|endoftext|>


<commit_before>'use babel';

import { MessagePanelView, PlainMessageView } from 'atom-message-panel';
import * as transformime from 'transformime';

const transform = transformime.createTransform();

export default class Inspector {
  constructor(kernelManager, codeManager) {
    this.kernelManager = kernelManager;
    this.codeManager = codeManager;
    this._lastInspectionResult = '';
  }

  toggle() {
    const editor = atom.workspace.getActiveTextEditor();
    const grammar = editor.getGrammar();
    const language = this.kernelManager.getLanguageFor(grammar);
    const kernel = this.kernelManager.getRunningKernelFor(language);
    if (!kernel) {
      atom.notifications.addInfo('No kernel running!');
      if (this.view) this.view.close();
      return;
    }

    if (!this.view) {
      this.view = new MessagePanelView({
        title: 'Hydrogen Inspector',
        closeMethod: 'destroy',
      });
    }

    const [code, cursorPos] = this.codeManager.getCodeToInspect();
    if (cursorPos === 0) {
      return;
    }

    kernel.inspect(code, cursorPos, result =>
      // TODO: handle case when inspect request returns an error
      this.showInspectionResult(result));
  }

  showInspectionResult(result) {
    console.log('Inspector: Result:', result);

    if (!result.found) {
      atom.notifications.addInfo('No introspection available!');
      if (this.view) this.view.close();
      return;
    }

    const onInspectResult = ({ mimetype, el }) => {
      if (mimetype === 'text/plain') {
        const lines = el.innerHTML.split('\n');
        const firstline = lines[0];
        lines.splice(0, 1);
        const message = lines.join('\n');

        if (this._lastInspectionResult === message && this.view.panel) {
          if (this.view) this.view.close();
          return;
        }

        this.view.clear();
        this.view.attach();
        this.view.add(new PlainMessageView({
          message: firstline,
          className: 'inspect-message',
          raw: true,
        }));
        this.view.add(new PlainMessageView({
          message,
          className: 'inspect-message',
          raw: true,
        }));

        this._lastInspectionResult = message;
        return;
      } else if (mimetype === 'text/html') {
        const container = document.createElement('div');
        container.appendChild(el);
        const message = container.innerHTML;
        if (this._lastInspectionResult === message && this.view.panel) {
          if (this.view) this.view.close();
          return;
        }

        this.view.clear();
        this.view.attach();
        this.view.add(new PlainMessageView({
          message,
          className: 'inspect-message',
          raw: true,
        }));

        this._lastInspectionResult = message;
        return;
      }

      console.error('Inspector: Rendering error:', mimetype, el);
      atom.notifications.addInfo('Cannot render introspection result!');
      if (this.view) this.view.close();
    };

    const onError = (error) => {
      console.error('Inspector: Rendering error:', error);
      atom.notifications.addInfo('Cannot render introspection result!');
      if (this.view) this.view.close();
    };

    transform(result.data).then(onInspectResult, onError);
  }
}
<commit_msg>Allow text/markdown code inspect results<commit_after>'use babel';

import { MessagePanelView, PlainMessageView } from 'atom-message-panel';
import * as transformime from 'transformime';

const transform = transformime.createTransform();

export default class Inspector {
  constructor(kernelManager, codeManager) {
    this.kernelManager = kernelManager;
    this.codeManager = codeManager;
    this._lastInspectionResult = '';
  }

  toggle() {
    const editor = atom.workspace.getActiveTextEditor();
    const grammar = editor.getGrammar();
    const language = this.kernelManager.getLanguageFor(grammar);
    const kernel = this.kernelManager.getRunningKernelFor(language);
    if (!kernel) {
      atom.notifications.addInfo('No kernel running!');
      if (this.view) this.view.close();
      return;
    }

    if (!this.view) {
      this.view = new MessagePanelView({
        title: 'Hydrogen Inspector',
        closeMethod: 'destroy',
      });
    }

    const [code, cursorPos] = this.codeManager.getCodeToInspect();
    if (cursorPos === 0) {
      return;
    }

    kernel.inspect(code, cursorPos, result =>
      // TODO: handle case when inspect request returns an error
      this.showInspectionResult(result));
  }

  showInspectionResult(result) {
    console.log('Inspector: Result:', result);

    if (!result.found) {
      atom.notifications.addInfo('No introspection available!');
      if (this.view) this.view.close();
      return;
    }

    const onInspectResult = ({ mimetype, el }) => {
      if (mimetype === 'text/plain') {
        const lines = el.innerHTML.split('\n');
        const firstline = lines[0];
        lines.splice(0, 1);
        const message = lines.join('\n');

        if (this._lastInspectionResult === message && this.view.panel) {
          if (this.view) this.view.close();
          return;
        }

        this.view.clear();
        this.view.attach();
        this.view.add(new PlainMessageView({
          message: firstline,
          className: 'inspect-message',
          raw: true,
        }));
        this.view.add(new PlainMessageView({
          message,
          className: 'inspect-message',
          raw: true,
        }));

        this._lastInspectionResult = message;
        return;
      } else if (mimetype === 'text/html' || mimetype === 'text/markdown') {
        const container = document.createElement('div');
        container.appendChild(el);
        const message = container.innerHTML;
        if (this._lastInspectionResult === message && this.view.panel) {
          if (this.view) this.view.close();
          return;
        }

        this.view.clear();
        this.view.attach();
        this.view.add(new PlainMessageView({
          message,
          className: 'inspect-message',
          raw: true,
        }));

        this._lastInspectionResult = message;
        return;
      }

      console.error('Inspector: Rendering error:', mimetype, el);
      atom.notifications.addInfo('Cannot render introspection result!');
      if (this.view) this.view.close();
    };

    const onError = (error) => {
      console.error('Inspector: Rendering error:', error);
      atom.notifications.addInfo('Cannot render introspection result!');
      if (this.view) this.view.close();
    };

    transform(result.data).then(onInspectResult, onError);
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2014 Facebook, Inc.
 *
 * 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.
 *
 * @providesModule invariant
 */

"use strict";

/**
 * Use invariant() to assert state which your program assumes to be true.
 *
 * Provide sprintf-style format (only %s is supported) and arguments
 * to provide information about what broke and what you were
 * expecting.
 *
 * The invariant message will be stripped in production, but the invariant
 * will remain to ensure logic does not differ in production.
 */

var invariant = function(condition) {
  if (!condition) {
    var error = new Error(
      'Minified exception occured; use the non-minified dev environment for ' +
      'the full error message and additional helpful warnings.'
    );
    error.framesToPop = 1;
    throw error;
  }
};

if (process.env.NODE_ENV !== 'production') {
  invariant = function(condition, format, a, b, c, d, e, f) {
    if (format === undefined) {
      throw new Error('invariant requires an error message argument');
    }

    if (!condition) {
      var args = [a, b, c, d, e, f];
      var argIndex = 0;
      var error = new Error(
        'Invariant Violation: ' +
        format.replace(/%s/g, function() { return args[argIndex++]; })
      );
      error.framesToPop = 1; // we don't care about invariant's own frame
      throw error;
    }
  };
}

module.exports = invariant;<commit_msg>delete invariant (will use the one from React)<commit_after><|endoftext|>


<commit_before>'use strict';
var http = require('http');
var dispatcher = require('httpdispatcher');

function keepAlive(logger) {
  // Create HTTP service to let bot stay alive
  dispatcher.onGet('/', function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/json' });
    res.end('Awoo. :3');
    logger('info', 'Serving keepAlive page.');
  });

  dispatcher.onGet('/restart', function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/json' });
    res.end('Visit /restart/bot to reboot WolfBot. Make sure you really want to do this! ;w;');
    logger('info', 'Serving restart page.');
  });
  dispatcher.onGet('/restart/bot', function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/json' });
    res.end('Restarting WolfBot. Back in a moment~! >w<');
    logger('info', 'Serving restart page.');
    logger('warn', 'Restarting bot.');
    process.exit(0);
  });
  http.createServer(function(req, res) {
    logger('info', 'Starting keepAlive server.');
    dispatcher.dispatch(req, res);
  }).listen(process.env.PORT || 3000);
}

module.exports = {
  start: keepAlive
};
<commit_msg>Change logging for keepalive page<commit_after>'use strict';
var http = require('http');
var dispatcher = require('httpdispatcher');

function keepAlive(logger) {
  // Create HTTP service to let bot stay alive
  logger('info', 'Starting keepAlive server.');
  dispatcher.onGet('/', function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/json' });
    res.end('Awoo. :3');
    logger('info', 'Serving keepAlive page.');
  });

  dispatcher.onGet('/restart', function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/json' });
    res.end('Visit /restart/bot to reboot WolfBot. Make sure you really want to do this! ;w;');
    logger('info', 'Serving blocking restart page.');
  });
  dispatcher.onGet('/restart/bot', function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/json' });
    res.end('Restarting WolfBot. Back in a moment~! >w<');
    logger('info', 'Serving restart page.');
    logger('warn', 'Restarting bot.');
    process.exit(0);
  });
  http.createServer(function(req, res) {
    dispatcher.dispatch(req, res);
  }).listen(process.env.PORT || 3000);
}

module.exports = {
  start: keepAlive
};
<|endoftext|>


<commit_before>Package.describe({
    name: 'frenchbread:elastic-rest',
    version: '2.0.1',
    // Brief, one-line summary of the package.
    summary: "Wrapper for Elastic REST API.",
    // URL to the Git repository containing the source code for this package.
    git: 'https://github.com/frenchbread/meteor-elastic-rest',
    // By default, Meteor will default to using README.md for documentation.
    // To avoid submitting documentation, set this field to null.
    documentation: 'README.md'
});

Package.onUse(function(api) {
    api.versionsFrom('1.2.1');
    api.use(['ecmascript'])
    api.addFiles('server/elastic-rest.js');
    api.export("ElasticRest", ['server']);
});

// Package.onTest(function(api) {
//     api.use('tinytest');
//     api.use('frenchbread:elastic-rest');
//     api.addFiles('tests/elastic-rest-tests.js');
// });
<commit_msg>Revert "version ++"<commit_after>Package.describe({
    name: 'frenchbread:elastic-rest',
    version: '2.0.0',
    // Brief, one-line summary of the package.
    summary: "Wrapper for Elastic REST API.",
    // URL to the Git repository containing the source code for this package.
    git: 'https://github.com/frenchbread/meteor-elastic-rest',
    // By default, Meteor will default to using README.md for documentation.
    // To avoid submitting documentation, set this field to null.
    documentation: 'README.md'
});

Package.onUse(function(api) {
    api.versionsFrom('1.2.1');
    api.use(['ecmascript'])
    api.addFiles('server/elastic-rest.js');
    api.export("ElasticRest", ['server']);
});

// Package.onTest(function(api) {
//     api.use('tinytest');
//     api.use('frenchbread:elastic-rest');
//     api.addFiles('tests/elastic-rest-tests.js');
// });
<|endoftext|>


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

var mineflayer = require('mineflayer');
var navigatePlugin = require('mineflayer-navigate')(mineflayer);

// Okay, phew, let's uh pick a random name
var names = JSON.parse(fs.readFileSync('gismu.json', 'utf8'));

// Stolen (borrowed) off the internet.
function shuffle(a,b) {
    // Get a random number between 0 and 10
    var temp = parseInt( Math.random()*10 );

    // Get 1 or 0, whether temp is odd or even
    var isOddOrEven = temp%2;

    // Get +1 or -1, whether temp greater or smaller than 5
    var isPosOrNeg = temp>5 ? 1 : -1;

    // Return -1, 0, or +1
    return( isOddOrEven*isPosOrNeg );
}

names.sort(shuffle);
var my_name = names[0];

var bot = mineflayer.createBot({
    username: my_name,
    host: '192.9.206.136',
});

// Inject navigation plugin
navigatePlugin(bot);

function von_neumann(point) {
    var points = [];

    points.push(point.clone().translate(1,0,0));
    points.push(point.clone().translate(-1,0,0));
    points.push(point.clone().translate(0,1,0));
    points.push(point.clone().translate(0,-1,0));
    points.push(point.clone().translate(0,0,1));
    points.push(point.clone().translate(0,0,-1));

    return points;
}

function moore(point) {
    var points = [];

    for (var i=-1; i <= 1; i++) {
        for (var j=-1; j <= 1; j++) {
            for (var k=-1; k <= 1; k++) {
                var other = point.clone().translate(i,j,k);
                if (other != point) {
                    points.push(other);
                }
            }
        }
    }
    // End massive for loop.

    return points;
}

function tree_search(logs) {
    // Given an Array of blocks (which have .position properties), return a
    // list of "trees", where a tree is a horizontally and/or diagonally
    // contigious set of log blocks. A tree cannot be a subset of another
    // tree, that's just one big tree.
    var trees = [];
    logs.forEach(function(block, index, arr) {
        already_in = false;
        for (var i=0;i < trees.length; i++) {
            if (trees[i].indexOf(block) != -1) {
                already_in = true;
                break;
            }
        }
        if (!already_in) {
            var tree = {};

            var todo = {};
            todo[block] = true;

            while (

        }
    });

}

bot.on("spawn", function() {
    bot.chat("Hello world!");
    // Search for log blocks in a 16x16x16 box.
    var logs = [];

    for (var i=-8; i <= 8; i++) {
        for (var j=-8; j <= 8; j++) {
            for (var k=-8; k <= 8; k++) {
                var pos = bot.entity.position.clone();
                pos.translate(i,j,k).floor();

                var block = bot.blockAt(pos);
                if (block != null && block.type == 17) {
                    console.log("Log at " + pos.toString());
                    logs.push(block);
                }
    }}}
});

bot.on("entityMoved", function(entity) {
    if (entity != bot.entity && entity.type == "player") {

        var pos = entity.position.clone();
        // Look at the player's head, not their feet.
        pos.translate(0, 1.62, 0);

        bot.lookAt(pos);
    }
});
<commit_msg>Tree search?<commit_after>var fs = require('fs');

var mineflayer = require('mineflayer');
var navigatePlugin = require('mineflayer-navigate')(mineflayer);

// Okay, phew, let's uh pick a random name
var names = JSON.parse(fs.readFileSync('gismu.json', 'utf8'));

// Stolen (borrowed) off the internet.
function shuffle(a,b) {
    // Get a random number between 0 and 10
    var temp = parseInt( Math.random()*10 );

    // Get 1 or 0, whether temp is odd or even
    var isOddOrEven = temp%2;

    // Get +1 or -1, whether temp greater or smaller than 5
    var isPosOrNeg = temp>5 ? 1 : -1;

    // Return -1, 0, or +1
    return( isOddOrEven*isPosOrNeg );
}

names.sort(shuffle);
var my_name = names[0];

var bot = mineflayer.createBot({
    username: my_name,
    host: '192.9.206.136',
});

// Inject navigation plugin
navigatePlugin(bot);

function von_neumann(point) {
    var points = [];

    points.push(point.clone().translate(1,0,0));
    points.push(point.clone().translate(-1,0,0));
    points.push(point.clone().translate(0,1,0));
    points.push(point.clone().translate(0,-1,0));
    points.push(point.clone().translate(0,0,1));
    points.push(point.clone().translate(0,0,-1));

    return points;
}

function moore(point) {
    var points = [];

    for (var i=-1; i <= 1; i++) {
        for (var j=-1; j <= 1; j++) {
            for (var k=-1; k <= 1; k++) {
                var other = point.clone().translate(i,j,k);
                if (other != point) {
                    points.push(other);
                }
            }
        }
    }
    // End massive for loop.

    return points;
}

function tree_search(logs) {
    // Given an Array of blocks (which have .position properties), return a
    // list of "trees", where a tree is a horizontally and/or diagonally
    // contigious set of log blocks. A tree cannot be a subset of another
    // tree, that's just one big tree.
    console.log("Searching for trees.");
    var trees = [];
    logs.forEach(function(block, index, arr) {
        already_in = false;
        for (var i=0;i < trees.length; i++) {
            if (trees[i].indexOf(block) != -1) {
                already_in = true;
                break;
            }
        }
        if (!already_in) {
            var done = [];

            var todo = [];
            todo.push(block);

            while (todo.length != 0) {
                var target_block = todo.pop();

                var neighbours = moore(target_block.position);
                neighbours.forEach(function(point, index, arr) {
                    var block = bot.blockAt(point);
                    if (block != null && block.type == 17) {
                        todo.push(block);
                    }
                });

                done.push(target_block);
            }

            trees.push(done);
        }
    });
    console.log("DONE");
}

bot.on("spawn", function() {
    bot.chat("Hello world!");
    // Search for log blocks in a 16x16x16 box.
    var logs = [];

    for (var i=-8; i <= 8; i++) {
        for (var j=-8; j <= 8; j++) {
            for (var k=-8; k <= 8; k++) {
                var pos = bot.entity.position.clone();
                pos.translate(i,j,k).floor();

                var block = bot.blockAt(pos);
                if (block != null && block.type == 17) {
                    logs.push(block);
                }
    }}}

    tree_search(logs);
});

bot.on("entityMoved", function(entity) {
    if (entity != bot.entity && entity.type == "player") {

        var pos = entity.position.clone();
        // Look at the player's head, not their feet.
        pos.translate(0, 1.62, 0);

        bot.lookAt(pos);
    }
});
<|endoftext|>


<commit_before>Package.describe({
    summary: "Accounts Templates styled for Ratchet.",
    version: "1.8.0",
    name: "useraccounts:ratchet",
    git: "https://github.com/meteor-useraccounts/ratchet.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.8.0",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_reCaptcha.html",
        "lib/at_reCaptcha.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_ratchet.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:ratchet",
        "useraccounts:core@1.8.0",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<commit_msg>patch release - Bump to version 1.8.1<commit_after>Package.describe({
    summary: "Accounts Templates styled for Ratchet.",
    version: "1.8.1",
    name: "useraccounts:ratchet",
    git: "https://github.com/meteor-useraccounts/ratchet.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.8.1",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_reCaptcha.html",
        "lib/at_reCaptcha.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_ratchet.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:ratchet",
        "useraccounts:core@1.8.1",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<|endoftext|>


<commit_before>var glob = require('glob');

module.exports = function (conf) {
  var linter = require('./' + conf.linter + '-linter').create(conf.linterOptions);

  var lintScanner = require('./lint-scanner').create(linter, glob, conf.excludes);
  var repository = require('./repository').create(linter);

  var lintReporter = require('./lint-reporter').create(repository);
  var summaryReporter = require('./summary-reporter').create(repository);

  repository.listen();
  lintReporter.listen();

  lintScanner.scan(conf.paths).then(function () {
    summaryReporter.print();
  });

};<commit_msg>--once exits with error code if any lint.<commit_after>var glob = require('glob');

module.exports = function (conf) {
  var linter = require('./' + conf.linter + '-linter').create(conf.linterOptions);

  var lintScanner = require('./lint-scanner').create(linter, glob, conf.excludes);
  var repository = require('./repository').create(linter);

  var lintReporter = require('./lint-reporter').create(repository);
  var summaryReporter = require('./summary-reporter').create(repository);

  repository.listen();
  lintReporter.listen();

  lintScanner.scan(conf.paths).then(function () {
    summaryReporter.print();
    if (summaryReporter.numDirtyFiles() > 0) {
      process.exit(-1);
    }
  });

};<|endoftext|>


<commit_before>Package.describe({
  summary: "is.js micro check library for Meteor",
  version: "0.0.1",
  git: "https://github.com/hb5co/meteor-is.js.git"
});

Package.on_use(function (api, where) {
  api.add_files('lib/is.js/is.min.js');
});
<commit_msg>Updated package description info<commit_after>Package.describe({
  name: 'hb5:meteor-is.js',
  summary: 'is.js micro check library for Meteor',
  version: '0.0.1',
  git: 'https://github.com/hb5co/meteor-is.js.git'
});

Package.on_use(function(api) {
  api.add_files('lib/is.js/is.min.js');
});
<|endoftext|>