<commit_before>'use strict'

var filter = require('lodash.filter')
var map = require('lodash.map')
var forEach = require('lodash.foreach')

var keyPrefix = 'reduxPersistStore:'

function persistStore(store, config, cb){
  //defaults
  config = config || {}
  var blacklist = config.blacklist || []
  var actionCreator = config.actionCreator || defaultActionCreator
  var storage = config.storage || defaultStorage

  //initialize values
  let timeIterator = null
  let lastState = store.getState()

  //rehydrate
  let restoreCount = 0
  let completionCount = 0
  forEach(lastState, function(s, key){
    if(blacklist.indexOf(key) !== -1){ return }
    restoreCount += 1
    setImmediate(function(){
      rehydrate(key, function(){
        completionCount += 1
        if(completionCount === restoreCount){
          cb && cb()
        }
      })
    })
  })

  //store state to disk
  var unsub = store.subscribe(function(){
    //Clear unfinished timeIterator if exists
    if(timeIterator !== null){
      clearInterval(timeIterator)
    }

    let state = store.getState()
    let storesToProcess = filter(map(state, function(subState, key){
      if(blacklist.indexOf(key) !== -1){ return }
      //only store keys that have changed
      return lastState[key] !== state[key] ? key : false
    }))

    //time iterator runs every 33ms (30fps)
    let i = 0
    timeIterator = setInterval(function(){
      if(i === storesToProcess.length){
        clearInterval(timeIterator)
        return
      }
      storage.setItem(createStorageKey(storesToProcess[i]), JSON.stringify(state[storesToProcess[i]]), warnIfSetError)
      i += 1
    }, 33)

    lastState = state
  })

  function rehydrate(key, cb){
    storage.getItem(createStorageKey(key), function(err, serialized){
      try{
        if(err){ throw err }
        let data = JSON.parse(serialized)
        store.dispatch(actionCreator(key, data))
      }
      catch(e){
        console.warn('Error restoring data for key:', key, e)
        storage.removeItem(key, warnIfRemoveError)
      }
      cb()
    })
  }

  return {
    purge: function(keys){
      forEach(keys, function(key){
        storage.removeItem(createStorageKey(key), warnIfRemoveError)
      })
    },
    purgeAll: function(){
      storage.getAllKeys(function(err, keys){
        forEach(keys, function(key){
          if(key.indexOf(keyPrefix) === 0){
            storage.removeItem(key, warnIfRemoveError)
          }
        })
      })
    }
  }
}

function warnIfRemoveError(err){
  if(err){ console.warn('Error removing data for key:', key, err) }
}

function warnIfSetError(err){
  if(err){ console.warn('Error storing data for key:', key, err) }
}

function createStorageKey(key){
  return keyPrefix+key
}

function defaultActionCreator(key, data){
  return {
    type: 'REHYDRATE',
    reducer: key,
    data: data,
  }
}

var defaultStorage = {
  getItem: function(key, cb){
    try{
      var s = localStorage.getItem(key)
      cb(null, s)
    }
    catch(e){
      cb(e)
    }
  },
  setItem: function(key, string, cb){
    try{
      localStorage.setItem(key, string)
      cb(null)
    }
    catch(e){
      cb(e)
    }
  },
  removeItem: function(key, cb){
    try{
      localStorage.removeItem(key)
      cb(null)
    }
    catch(e){
      cb(e)
    }
  },
  getAllKeys: function(cb){
    try{
      var keys = []
      for ( var i = 0, len = localStorage.length; i < len; ++i ) {
        keys.push(localStorage.key(i))
      }
      cb(null, keys)
    }
    catch(e){
      cb(err)
    }
  }
}

module.exports = persistStore
<commit_msg>storesToProcess should be a queue that is added to and picked from<commit_after>'use strict'

var filter = require('lodash.filter')
var map = require('lodash.map')
var forEach = require('lodash.foreach')

var keyPrefix = 'reduxPersistStore:'

function persistStore(store, config, cb){
  //defaults
  config = config || {}
  var blacklist = config.blacklist || []
  var actionCreator = config.actionCreator || defaultActionCreator
  var storage = config.storage || defaultStorage

  //initialize values
  let timeIterator = null
  let lastState = store.getState()

  //rehydrate
  let restoreCount = 0
  let completionCount = 0
  forEach(lastState, function(s, key){
    if(blacklist.indexOf(key) !== -1){ return }
    restoreCount += 1
    setImmediate(function(){
      rehydrate(key, function(){
        completionCount += 1
        if(completionCount === restoreCount){
          cb && cb()
        }
      })
    })
  })

  let storesToProcess = []
  //store state to disk
  var unsub = store.subscribe(function(){
    //Clear unfinished timeIterator if exists
    if(timeIterator !== null){
      clearInterval(timeIterator)
    }

    let state = store.getState()
    forEach(state, function(subState, key){
      if(blacklist.indexOf(key) !== -1){ return }
      //only store keys that have changed
      if(lastState[key] === state[key]){ return }
      if(storesToProcess.indexOf(key) !== -1){ return }
      storesToProcess.push(key)
    })

    //time iterator runs every 33ms (30fps)
    timeIterator = setInterval(function(){
      if(storesToProcess.length === 0){
        clearInterval(timeIterator)
        return
      }

      storage.setItem(createStorageKey(storesToProcess[0]), JSON.stringify(state[storesToProcess[0]]), warnIfSetError)
      storesToProcess.shift()
    }, 33)

    lastState = state
  })

  function rehydrate(key, cb){
    storage.getItem(createStorageKey(key), function(err, serialized){
      try{
        if(err){ throw err }
        let data = JSON.parse(serialized)
        store.dispatch(actionCreator(key, data))
      }
      catch(e){
        console.warn('Error restoring data for key:', key, e)
        storage.removeItem(key, warnIfRemoveError)
      }
      cb()
    })
  }

  return {
    purge: function(keys){
      forEach(keys, function(key){
        storage.removeItem(createStorageKey(key), warnIfRemoveError)
      })
    },
    purgeAll: function(){
      storage.getAllKeys(function(err, keys){
        forEach(keys, function(key){
          if(key.indexOf(keyPrefix) === 0){
            storage.removeItem(key, warnIfRemoveError)
          }
        })
      })
    }
  }
}

function warnIfRemoveError(err){
  if(err){ console.warn('Error removing data for key:', key, err) }
}

function warnIfSetError(err){
  if(err){ console.warn('Error storing data for key:', key, err) }
}

function createStorageKey(key){
  return keyPrefix+key
}

function defaultActionCreator(key, data){
  return {
    type: 'REHYDRATE',
    reducer: key,
    data: data,
  }
}

var defaultStorage = {
  getItem: function(key, cb){
    try{
      var s = localStorage.getItem(key)
      cb(null, s)
    }
    catch(e){
      cb(e)
    }
  },
  setItem: function(key, string, cb){
    try{
      localStorage.setItem(key, string)
      cb(null)
    }
    catch(e){
      cb(e)
    }
  },
  removeItem: function(key, cb){
    try{
      localStorage.removeItem(key)
      cb(null)
    }
    catch(e){
      cb(e)
    }
  },
  getAllKeys: function(cb){
    try{
      var keys = []
      for ( var i = 0, len = localStorage.length; i < len; ++i ) {
        keys.push(localStorage.key(i))
      }
      cb(null, keys)
    }
    catch(e){
      cb(err)
    }
  }
}

module.exports = persistStore
<|endoftext|>


<commit_before>var CachingWriter = require('broccoli-caching-writer');
var ES6Transpiler = require('es6-module-transpiler').Compiler;
var path = require('path');
var mkdirp = require('mkdirp');
var fs = require('fs');
var helpers = require('broccoli-kitchen-sink-helpers');
var walkSync = require('walk-sync');

module.exports = CachingWriter.extend({
  enforceSingleInputTree: true,

  init: function() {
    this.transpilerCache = {};
  },

  updateCache: function(inDir, outDir) {
    this.newTranspilerCache = {};
    walkSync(inDir)
      .forEach(function(relativePath) {
        if (relativePath.slice(-1) !== '/') {
          this.handleFile(inDir, outDir, relativePath);
        }
      }.bind(this));
    this.transpilerCache = this.newTranspilerCache;
  },

  handleFile: function(inDir, outDir, relativePath) {
    var moduleName = relativePath.replace(/\.js$/, '');
    var fullInputPath = path.join(inDir, relativePath);
    var fullOutputPath = path.join(outDir, relativePath);

    var entry = this.transpileThroughCache(
      moduleName,
      fs.readFileSync(fullInputPath, 'utf-8')
    );

    mkdirp.sync(path.dirname(fullOutputPath));
    fs.writeFileSync(fullOutputPath, entry.amd);
  },

  transpileThroughCache: function(moduleName, source) {
    var key = helpers.hashStrings([moduleName, source]);
    var entry = this.transpilerCache[key];
    if (entry) {
      return this.newTranspilerCache[key] = entry;
    }
    var compiler = new ES6Transpiler(source, moduleName);
    patchRelativeImports(moduleName, compiler);
    return this.newTranspilerCache[key] = {
      amd: compiler.toAMD()
    };
  }
});

// This function based on
// http://github.com/joliss/broccoli-es6-concatenator. MIT Licensed,
// Copyright 2013 Jo Liss.
function patchRelativeImports(moduleName, compiler) {
  for (var i = 0; i < compiler.imports.length; i++) {
    var importNode = compiler.imports[i];
    if ((importNode.type !== 'ImportDeclaration' &&
         importNode.type !== 'ModuleDeclaration') ||
        !importNode.source ||
        importNode.source.type !== 'Literal' ||
        !importNode.source.value) {
      throw new Error('Internal error: Esprima import node has unexpected structure');
    }
    if (importNode.source.value.slice(0, 1) === '.') {
      importNode.source.value = path.join(moduleName, '..', importNode.source.value).replace(/\\/g, '/');
    }
  }
}
<commit_msg>tag transpilation errors with filename<commit_after>var CachingWriter = require('broccoli-caching-writer');
var ES6Transpiler = require('es6-module-transpiler').Compiler;
var path = require('path');
var mkdirp = require('mkdirp');
var fs = require('fs');
var helpers = require('broccoli-kitchen-sink-helpers');
var walkSync = require('walk-sync');

module.exports = CachingWriter.extend({
  enforceSingleInputTree: true,

  init: function() {
    this.transpilerCache = {};
  },

  updateCache: function(inDir, outDir) {
    this.newTranspilerCache = {};
    walkSync(inDir)
      .forEach(function(relativePath) {
        if (relativePath.slice(-1) !== '/') {
          this.handleFile(inDir, outDir, relativePath);
        }
      }.bind(this));
    this.transpilerCache = this.newTranspilerCache;
  },

  handleFile: function(inDir, outDir, relativePath) {
    var moduleName = relativePath.replace(/\.js$/, '');
    var fullInputPath = path.join(inDir, relativePath);
    var fullOutputPath = path.join(outDir, relativePath);

    var entry = this.transpileThroughCache(
      moduleName,
      fs.readFileSync(fullInputPath, 'utf-8')
    );

    mkdirp.sync(path.dirname(fullOutputPath));
    fs.writeFileSync(fullOutputPath, entry.amd);
  },

  transpileThroughCache: function(moduleName, source) {
    var key = helpers.hashStrings([moduleName, source]);
    var entry = this.transpilerCache[key];
    if (entry) {
      return this.newTranspilerCache[key] = entry;
    }
    try {
      var compiler = new ES6Transpiler(source, moduleName);
      patchRelativeImports(moduleName, compiler);
      return this.newTranspilerCache[key] = {
        amd: compiler.toAMD()
      };
    } catch(err) {
      err.file = moduleName;
      throw err;
    }
  }
});

// This function based on
// http://github.com/joliss/broccoli-es6-concatenator. MIT Licensed,
// Copyright 2013 Jo Liss.
function patchRelativeImports(moduleName, compiler) {
  for (var i = 0; i < compiler.imports.length; i++) {
    var importNode = compiler.imports[i];
    if ((importNode.type !== 'ImportDeclaration' &&
         importNode.type !== 'ModuleDeclaration') ||
        !importNode.source ||
        importNode.source.type !== 'Literal' ||
        !importNode.source.value) {
      throw new Error('Internal error: Esprima import node has unexpected structure');
    }
    if (importNode.source.value.slice(0, 1) === '.') {
      importNode.source.value = path.join(moduleName, '..', importNode.source.value).replace(/\\/g, '/');
    }
  }
}
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var sass = new EventEmitter();

function prepArgs(options) {

	var args = [];

	if (options.filepath) {
		args.push(options.filepath);
	} else if (options.data) {
		if (!options.type) {
			options.type = 'scss';
		}
		args.push('--' + options.type);
	} else {
		throw new Error('Please either specify a filepath or data string to compile');
	}

	return args;
}

function compile(options) {

	var args = prepArgs(options);
	var child = require('child_process').spawn('sass', args);

	child.stdout.on('data', function (data) {
		sass.emit('success', new Buffer(data).toString('utf8'));
	});

	child.stderr.on('data', function (data) {
		sass.emit('error', new Buffer(data).toString('utf8'));
	});

	if (options.data) {
		child.stdin.setEncoding('utf8');
		child.stdin.write(options.data);
    	child.stdin.end();
    }
}

sass.compile = compile;
module.exports = sass;<commit_msg>Comments and whitespace fixes<commit_after>var EventEmitter = require('events').EventEmitter;
var sass = new EventEmitter();

/**
 * Prepare the command arguments
 * @param  {object} options - The options passed to the compile method
 * @return {array}
 */

function prepArgs(options) {

  var args = [];

  if (options.filepath) {
    args.push(options.filepath);
  } else if (options.data) {
    if (!options.type) {
      options.type = 'scss';
    }
    args.push('--' + options.type);
  } else {
    throw new Error('Please either specify a filepath or data string to compile');
  }

  return args;
}

/**
 * Compiles the sass, either from a filepath or from a data string
 * @param  {object} options - The compile options
 */

function compile(options) {

  var args = prepArgs(options);
  var child = require('child_process').spawn('sass', args);

  child.stdout.on('data', function (data) {
    sass.emit('success', new Buffer(data).toString('utf8'));
  });

  child.stderr.on('data', function (data) {
    sass.emit('error', new Buffer(data).toString('utf8'));
  });

  if (options.data) {
    child.stdin.setEncoding('utf8');
    child.stdin.write(options.data);
    child.stdin.end();
  }
}

sass.compile = compile;
module.exports = sass;<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var utils = require('./utils');

function loader(patterns, config) {
  if (utils.isObject(patterns)) {
    config = patterns;
    patterns = undefined;
  }

  return function plugin(app) {
    if (utils.isRegistered(app, 'assemble-loader')) {
      return plugin;
    }

    if (utils.isValidInstance(app)) {
      appLoader(this, config);
    }

    if (utils.isValidInstance(app, ['views', 'items', 'collection'])) {
      collectionLoader(this, config);
    }

    if (utils.isValidGlob(patterns)) {
      return viewLoader(app, config, patterns);
    }

    return plugin;
  };
}

/**
 * If a glob pattern is passed on the outer function, this means the
 * user wants to load views onto the collection. Example:
 *
 * ```js
 * app.create('pages')
 *   .use(loader('*.hbs'))
 * ```
 *
 * So we pass the pattern to the `loadViews` function that we create
 * for the collection in the `collectionLoader` function below.
 */

function viewLoader(app, config, patterns) {
  app.loadViews(patterns, createOptions(app, config, {}));
  return app;
}

/**
 * Load views that don't belong to a collection
 *
 * @param {Object} `app` top level application instance (e.g. instance of assemble)
 * @param {Object} `config` Settings passed to the plugin
 * @return {Object}
 */

function appLoader(app, config) {
  var viewFn = app.view;

  app.define('load', function(patterns, options) {
    var opts = createOptions(app, config, options);
    var cache = {};
    var load = utils.loader(cache, opts, viewFn.bind(this));
    load.apply(this, arguments);
    return cache;
  });
}

/**
 * Load views onto a collection.
 *
 * @param {Object} `collection` Collection instance (.e.g. `pages` or `partials`)
 * @param {Object} `config` Settings passed to the plugin
 * @return {Object}
 */

function collectionLoader(collection, config) {
  var addViews = collection.addViews;
  var addView = collection.addView;

  collection.define('addView', function(key, value) {
    if (utils.isFilepath(key, value)) {
      return this.loadView.apply(this, arguments);
    }
    return addView.apply(this, arguments);
  });

  collection.define('addViews', function(key, value) {
    if (utils.isGlob(key, value) || utils.isFilepath(key, value)) {
      return this.loadViews.apply(this, arguments);
    }
    return addViews.apply(this, arguments);
  });

  collection.define('load', function(patterns, options) {
    var opts = createOptions(this, config, options);
    var load = utils.loader(this.views, opts, addView.bind(this));
    load.apply(this, arguments);
    return this;
  });

  collection.define('loadView', function(filepath, options) {
    if (utils.hasGlob(filepath)) {
      return this.loadViews.apply(this, arguments);
    }

    var opts = createOptions(this, config, options);
    var absolute = path.resolve(opts.cwd, filepath);
    var buf = null;

    if (utils.exists(absolute)) {
      buf = fs.readFileSync(absolute);
    }
    return this.addView(absolute, {contents: buf});
  });

  collection.define('loadViews', function(patterns, options) {
    var opts = createOptions(this, config, options);
    var load = utils.loader({}, opts, this.addView.bind(this));
    load.apply(this, arguments);
    return this;
  });
}

/**
 * Create options from:
 *   + `config` - settings passed to plugin
 *   + `app.options` - general instance options
 *   + `options` - options specifically passed to the method being called
 */

function createOptions(app, config, options) {
  var cwd = app.cwd || process.cwd();
  return utils.extend({cwd: cwd}, config, app.options, options);
}

/**
 * Expose `loader`
 */

module.exports = loader;
<commit_msg>ensure contents is synced<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var utils = require('./utils');

function loader(patterns, config) {
  if (utils.isObject(patterns)) {
    config = patterns;
    patterns = undefined;
  }

  return function plugin(app) {
    if (utils.isRegistered(app, 'assemble-loader')) {
      return plugin;
    }

    if (utils.isValidInstance(app)) {
      appLoader(this, config);
    }

    if (utils.isValidInstance(app, ['views', 'items', 'collection'])) {
      collectionLoader(this, config);
    }

    if (utils.isValidGlob(patterns)) {
      return viewLoader(app, config, patterns);
    }

    return plugin;
  };
}

/**
 * If a glob pattern is passed on the outer function, this means the
 * user wants to load views onto the collection. Example:
 *
 * ```js
 * app.create('pages')
 *   .use(loader('*.hbs'))
 * ```
 *
 * So we pass the pattern to the `loadViews` function that we create
 * for the collection in the `collectionLoader` function below.
 */

function viewLoader(app, config, patterns) {
  app.loadViews(patterns, createOptions(app, config, {}));
  return app;
}

/**
 * Load views that don't belong to a collection
 *
 * @param {Object} `app` top level application instance (e.g. instance of assemble)
 * @param {Object} `config` Settings passed to the plugin
 * @return {Object}
 */

function appLoader(app, config) {
  var viewFn = app.view;

  app.define('load', function(patterns, options) {
    var opts = createOptions(app, config, options);
    var cache = {};
    var load = utils.loader(cache, opts, viewFn.bind(this));
    load.apply(this, arguments);
    return cache;
  });
}

/**
 * Load views onto a collection.
 *
 * @param {Object} `collection` Collection instance (.e.g. `pages` or `partials`)
 * @param {Object} `config` Settings passed to the plugin
 * @return {Object}
 */

function collectionLoader(collection, config) {
  var addViews = collection.addViews;
  var addView = collection.addView;

  collection.define('addView', function(key, value) {
    if (utils.isFilepath(key, value)) {
      return this.loadView.apply(this, arguments);
    }
    var view = addView.apply(this, arguments);
    return utils.contents.sync(view);
  });

  collection.define('addViews', function(key, value) {
    if (utils.isGlob(key, value) || utils.isFilepath(key, value)) {
      return this.loadViews.apply(this, arguments);
    }
    return addViews.apply(this, arguments);
  });

  collection.define('load', function(patterns, options) {
    var opts = createOptions(this, config, options);
    var load = utils.loader(this.views, opts, addView.bind(this));
    load.apply(this, arguments);
    return this;
  });

  collection.define('loadView', function(filepath, options) {
    if (utils.hasGlob(filepath)) {
      return this.loadViews.apply(this, arguments);
    }

    var opts = createOptions(this, config, options);
    var absolute = path.resolve(opts.cwd, filepath);
    return this.addView(absolute, {contents: null});
  });

  collection.define('loadViews', function(patterns, options) {
    var opts = createOptions(this, config, options);
    var load = utils.loader({}, opts, this.addView.bind(this));
    load.apply(this, arguments);
    return this;
  });
}

/**
 * Create options from:
 *   + `config` - settings passed to plugin
 *   + `app.options` - general instance options
 *   + `options` - options specifically passed to the method being called
 */

function createOptions(app, config, options) {
  var cwd = app.cwd || process.cwd();
  return utils.extend({cwd: cwd}, config, app.options, options);
}

/**
 * Expose `loader`
 */

module.exports = loader;
<|endoftext|>


<commit_before>exports.Gateways = require("./src/gateways.js");
exports.Methods  = require("./src/methods.js");<commit_msg>Fixing index.js<commit_after>exports.Creditcards = require("./src/Creditcards.js");
<|endoftext|>


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

var couchpotato = function(){
    this.name = 'couchpotato';
    this.displayname = 'CouchPotato';
    this.description = 'Send commands to CouchPotato';

    this.defaultPrefs = [{
        name: 'hostname',
        type: 'text',
        value: 'localhost'
    },{
        name: 'port',
        type: 'text',
        value: '5050'
    },{
        name: 'api_key',
        type: 'text',
        value: ''
    }];
}

couchpotato.prototype.init = function(){
    var self = this;

    this.listen('couchpotato add (.+?)', 'standard', function(from, interface, params){
        self.findMovie(params[0], interface, from)
    });
}

couchpotato.prototype.findMovie = function(name, interface, from){
    var self = this;
    this.getPrefs().done(function(prefs){
        var options = {
            hostname: prefs.hostname,
            port: prefs.port,
            path: '/api/'+prefs.api_key+'/search/?q='+encodeURIComponent(name),
            headers: {
                'user-agent': 'Woodhouse Bot - https://github.com/Woodhouse-bot/woodhouse'
            }
        };
        var data = "";

        var req = http.get(options, function(res) {
            res.on('data', function (response) {
                data += String(response);
            });

            res.on('end', function() {
                var obj = JSON.parse(data);
                var movies = obj.movies;

                self.checkMovie(movies, interface, from);
            });
        }).on('error', function(e) {
            console.log('problem with request: ' + e.message);
        });
    });
}

couchpotato.prototype.checkMovie = function(movies, interface, from){
    var self = this;

    if (movies.length > 0){
        var movie = movies.shift();
        var message = 'Did you mean: ' + movie.titles[0] + ' (' + movie.year + ') - http://www.imdb.com/title/' + movie.imdb;

        this.sendMessage(message, interface, from);
        this.api.addYesNoQuestion(
            from,
            message,
            function(){
                self.addMovie(movie, interface, from);
            },
            function(){
                self.checkMovie(movies, interface, from)
            }
        );
    } else {
        this.sendMessage('No more results', interface, from);
    }
}

couchpotato.prototype.addMovie = function(movie, interface, from){
    var self = this;
    this.getPrefs().done(function(prefs){
        var options = {
            hostname: prefs.hostname,
            port: prefs.port,
            path: '/api/'+prefs.api_key+'/movie.add/?identifier='+movie.imdb+'&title='+encodeURIComponent(movie.titles[0]),
            headers: {
                'user-agent': 'Woodhouse Bot - https://github.com/Woodhouse-bot/woodhouse'
            }
        },
        data = '';

        var req = http.get(options, function(res) {
            res.on('data', function (response) {
                data += response;
            });

            res.on('end', function() {
                var obj = JSON.parse(data);

                if (obj.success === 'true') {
                    self.sendMessage(movie.titles[0] + ' added', interface, from);
                } else {
                    self.sendMessage('There was an error, please check the CouchPotato logs', interface, from);
                }

            });
        }).on('error', function(e) {
            console.log('problem with request: ' + e.message);
        });
    });
}

module.exports = couchpotato;
<commit_msg>Added name to regex group<commit_after>var http = require('http');

var couchpotato = function(){
    this.name = 'couchpotato';
    this.displayname = 'CouchPotato';
    this.description = 'Send commands to CouchPotato';

    this.defaultPrefs = [{
        name: 'hostname',
        type: 'text',
        value: 'localhost'
    },{
        name: 'port',
        type: 'text',
        value: '5050'
    },{
        name: 'api_key',
        type: 'text',
        value: ''
    }];
}

couchpotato.prototype.init = function(){
    var self = this;

    this.listen('couchpotato add (:<movie>.+?)', 'standard', function(from, interface, params){
        self.findMovie(params[0], interface, from)
    });
}

couchpotato.prototype.findMovie = function(name, interface, from){
    var self = this;
    this.getPrefs().done(function(prefs){
        var options = {
            hostname: prefs.hostname,
            port: prefs.port,
            path: '/api/'+prefs.api_key+'/search/?q='+encodeURIComponent(name),
            headers: {
                'user-agent': 'Woodhouse Bot - https://github.com/Woodhouse-bot/woodhouse'
            }
        };
        var data = "";

        var req = http.get(options, function(res) {
            res.on('data', function (response) {
                data += String(response);
            });

            res.on('end', function() {
                var obj = JSON.parse(data);
                var movies = obj.movies;

                self.checkMovie(movies, interface, from);
            });
        }).on('error', function(e) {
            console.log('problem with request: ' + e.message);
        });
    });
}

couchpotato.prototype.checkMovie = function(movies, interface, from){
    var self = this;

    if (movies.length > 0){
        var movie = movies.shift();
        var message = 'Did you mean: ' + movie.titles[0] + ' (' + movie.year + ') - http://www.imdb.com/title/' + movie.imdb;

        this.sendMessage(message, interface, from);
        this.api.addYesNoQuestion(
            from,
            message,
            function(){
                self.addMovie(movie, interface, from);
            },
            function(){
                self.checkMovie(movies, interface, from)
            }
        );
    } else {
        this.sendMessage('No more results', interface, from);
    }
}

couchpotato.prototype.addMovie = function(movie, interface, from){
    var self = this;
    this.getPrefs().done(function(prefs){
        var options = {
            hostname: prefs.hostname,
            port: prefs.port,
            path: '/api/'+prefs.api_key+'/movie.add/?identifier='+movie.imdb+'&title='+encodeURIComponent(movie.titles[0]),
            headers: {
                'user-agent': 'Woodhouse Bot - https://github.com/Woodhouse-bot/woodhouse'
            }
        },
        data = '';

        var req = http.get(options, function(res) {
            res.on('data', function (response) {
                data += response;
            });

            res.on('end', function() {
                var obj = JSON.parse(data);

                if (obj.success === 'true') {
                    self.sendMessage(movie.titles[0] + ' added', interface, from);
                } else {
                    self.sendMessage('There was an error, please check the CouchPotato logs', interface, from);
                }

            });
        }).on('error', function(e) {
            console.log('problem with request: ' + e.message);
        });
    });
}

module.exports = couchpotato;
<|endoftext|>


<commit_before>var Stream = require('stream');
var configureEngine = require('./lib/configure-engine');
var getTemplate = require('./lib/get-template');
var checkNodeType = require('./lib/check-node-type');
var areChildren = checkNodeType.areChildren;
var isChild = checkNodeType.isChild;
var isRaw = checkNodeType.isRaw;
var fillMold = require('./lib/fill-mold');
var normalizeCondition = require('./lib/normalize-condition');
var indentHtml = require('./lib/indent-html');

function renderTemplate(template, fillers, options) {

	var html = '';

	options = configureEngine(template, options);

	if(options.doctype) html += options.doctype;

	// Consider raws as template filename
	if(isRaw(template)) template = getTemplate(template.toString(), 'views', options);

	if(areChildren(template)) template = {'in' : template};

	if(options.wrap !== false) {

		options.wrapped = template;

		if(!options.wrap) options.wrap = options.defaultWrap;

			var wrap = getTemplate(options.wrap, 'wraps', options);

			// Start recursive nodes inspection from wrap
			html += inspectNode(wrap, fillers, options);

	} else {

		// Start recursive nodes inspection from template
		html += inspectNode(template, fillers, options);

	}

	// Delete first EOL when pretty is enabled and doctype is disabled
	if(options.pretty && !options.doctype) html = html.substr(1);

	if(options.out === 'buffer') return new Buffer(html);
	if(options.out === 'stream') {
		var stream = new Stream.Readable();
		stream.push(html, 'utf8');
		stream.push(null);
		return stream;
	}

	return html;

}

function inspectNode(node, fillers, options) {

	// Node local configuration
	if(node.options) options = configureEngine(node, options);

	// HTML tag
	if(node.tag) return buildTag(node, fillers, options);

	// API key
	if(node.api) return inspectApi(node, fillers, options);

	// Node tree
	if(node.in && !node.tag) return inspectNodeTree(node, fillers, options);

	return '';

}

function inspectApi(node, fillers, options) {

	switch(node.api) {

		case 'if' :
			if(node.in.constructor !== Array) node.in = [node.in];
			for(var i = 0, e = node.in.length; i < e; i++) {
				if(node.in[i].default) {
					return inspectNodeTree(node.in[i], fillers, options);
				}
				var condition = normalizeCondition(node.in[i].condition, options.alias);
				if(eval(condition)) {
					return inspectNodeTree(node.in[i], fillers, options);
				}
			}
			return '';
			break;

		case 'switch' :
			var expression = normalizeCondition(node.expression, options.alias);
			if(node.in.constructor !== Array) node.in = [node.in];
			for(var i = 0, e = node.in.length; i < e; i++) {
				if(node.in[i].default) {
					return inspectNodeTree(node.in[i], fillers, options);
				}
				var expressionValue = eval(expression);
				var caseValue = node.in[i].case;
				if(caseValue === String) handleRaw(caseValue, fillers, {'alias' : options.alias});
				if(expressionValue === caseValue) {
					return inspectNodeTree(node.in[i], fillers, options);
				}
			}
			return '';
			break;

		case 'each' :
			var html = '';
			var array = fillers[node.array];
			if(!node.item) node.item = 'item';
			array.forEach(function(item) {
				fillers[node.item] = item;
				html += inspectNodeTree(node, fillers, options);
			});
			return html;
			break;

		case 'repeat' :
			var html = '';
			if(!node.current) node.current = 'current';
			if(node.number.constructor === String) {
				node.number = handleRaw(node.number, fillers, {
					'alias' : options.alias
				});
			}
			for(var i = 1, e = node.number; i <= e; i++) {
				fillers[node.current] = i;
				html += inspectNodeTree(node, fillers, options);
			}
			return html;
			break;

		case 'inlay' :
			var template = getTemplate(node.name, 'inlays', options);
			return inspectNode(template, fillers, options);
			break;

		case 'wrap' :
			if(options.wrapped) {
				var wrapped = options.wrapped;
				options.wrapped = null;
				return inspectNode(wrapped, fillers, options);
			}
			break;

	}
	return '';

}

function inspectNodeTree(node, fillers, options) {

	var html = '';

	if(!node.in) return html;

	if(areChildren(node.in)) {

		node.in.forEach(function(child) {

			if(isRaw(child)) return html += handleRaw(child, fillers, options);

			html += inspectNode(child, fillers, options);

		});

		return html;

	}

	if(isChild(node.in)) return html += inspectNode(node.in, fillers, options);

	if(isRaw(node.in)) return html += handleRaw(node.in, fillers, options);

	return html;

}

function handleRaw(raw, fillers, options) {

	var html = '';

	if(options.pretty) html += indentHtml(options);

	return html += fillMold(raw, fillers, options.alias);

}

function buildTag(node, fillers, options) {

	var html = '';

	if(options.pretty) html += indentHtml(options);
	// Build start tag
	html += '<' + node.tag;

	// Append attributes
	if(node.attributes) {
		for(var attribute in node.attributes) {
			html += ' ' + attribute + '="' + node.attributes[attribute] + '"';
		}
	}

	// Close start tag
	html += '>';

	// Handle childless tag
	if(options.voids.indexOf(node.tag) != -1 || !node.in) return html;

	if(options.pretty) options.depth++;

	// Handle tag children
	html += inspectNodeTree(node, fillers, options);

	if(options.pretty) {
		options.depth--;
		html += indentHtml(options);
	}

	// Build end tag
	html += '</' + node.tag + '>';

	return html;

}

module.exports = renderTemplate;
<commit_msg>Remove useless condition part for node.in test<commit_after>var Stream = require('stream');
var configureEngine = require('./lib/configure-engine');
var getTemplate = require('./lib/get-template');
var checkNodeType = require('./lib/check-node-type');
var areChildren = checkNodeType.areChildren;
var isChild = checkNodeType.isChild;
var isRaw = checkNodeType.isRaw;
var fillMold = require('./lib/fill-mold');
var normalizeCondition = require('./lib/normalize-condition');
var indentHtml = require('./lib/indent-html');

function renderTemplate(template, fillers, options) {

	var html = '';

	options = configureEngine(template, options);

	if(options.doctype) html += options.doctype;

	// Consider raws as template filename
	if(isRaw(template)) template = getTemplate(template.toString(), 'views', options);

	if(areChildren(template)) template = {'in' : template};

	if(options.wrap !== false) {

		options.wrapped = template;

		if(!options.wrap) options.wrap = options.defaultWrap;

			var wrap = getTemplate(options.wrap, 'wraps', options);

			// Start recursive nodes inspection from wrap
			html += inspectNode(wrap, fillers, options);

	} else {

		// Start recursive nodes inspection from template
		html += inspectNode(template, fillers, options);

	}

	// Delete first EOL when pretty is enabled and doctype is disabled
	if(options.pretty && !options.doctype) html = html.substr(1);

	if(options.out === 'buffer') return new Buffer(html);
	if(options.out === 'stream') {
		var stream = new Stream.Readable();
		stream.push(html, 'utf8');
		stream.push(null);
		return stream;
	}

	return html;

}

function inspectNode(node, fillers, options) {

	// Node local configuration
	if(node.options) options = configureEngine(node, options);

	// HTML tag
	if(node.tag) return buildTag(node, fillers, options);

	// API key
	if(node.api) return inspectApi(node, fillers, options);

	// Node tree
	if(node.in) return inspectNodeTree(node, fillers, options);

	return '';

}

function inspectApi(node, fillers, options) {

	switch(node.api) {

		case 'if' :
			if(node.in.constructor !== Array) node.in = [node.in];
			for(var i = 0, e = node.in.length; i < e; i++) {
				if(node.in[i].default) {
					return inspectNodeTree(node.in[i], fillers, options);
				}
				var condition = normalizeCondition(node.in[i].condition, options.alias);
				if(eval(condition)) {
					return inspectNodeTree(node.in[i], fillers, options);
				}
			}
			return '';
			break;

		case 'switch' :
			var expression = normalizeCondition(node.expression, options.alias);
			if(node.in.constructor !== Array) node.in = [node.in];
			for(var i = 0, e = node.in.length; i < e; i++) {
				if(node.in[i].default) {
					return inspectNodeTree(node.in[i], fillers, options);
				}
				var expressionValue = eval(expression);
				var caseValue = node.in[i].case;
				if(caseValue === String) handleRaw(caseValue, fillers, {'alias' : options.alias});
				if(expressionValue === caseValue) {
					return inspectNodeTree(node.in[i], fillers, options);
				}
			}
			return '';
			break;

		case 'each' :
			var html = '';
			var array = fillers[node.array];
			if(!node.item) node.item = 'item';
			array.forEach(function(item) {
				fillers[node.item] = item;
				html += inspectNodeTree(node, fillers, options);
			});
			return html;
			break;

		case 'repeat' :
			var html = '';
			if(!node.current) node.current = 'current';
			if(node.number.constructor === String) {
				node.number = handleRaw(node.number, fillers, {
					'alias' : options.alias
				});
			}
			for(var i = 1, e = node.number; i <= e; i++) {
				fillers[node.current] = i;
				html += inspectNodeTree(node, fillers, options);
			}
			return html;
			break;

		case 'inlay' :
			var template = getTemplate(node.name, 'inlays', options);
			return inspectNode(template, fillers, options);
			break;

		case 'wrap' :
			if(options.wrapped) {
				var wrapped = options.wrapped;
				options.wrapped = null;
				return inspectNode(wrapped, fillers, options);
			}
			break;

	}
	return '';

}

function inspectNodeTree(node, fillers, options) {

	var html = '';

	if(!node.in) return html;

	if(areChildren(node.in)) {

		node.in.forEach(function(child) {

			if(isRaw(child)) return html += handleRaw(child, fillers, options);

			html += inspectNode(child, fillers, options);

		});

		return html;

	}

	if(isChild(node.in)) return html += inspectNode(node.in, fillers, options);

	if(isRaw(node.in)) return html += handleRaw(node.in, fillers, options);

	return html;

}

function handleRaw(raw, fillers, options) {

	var html = '';

	if(options.pretty) html += indentHtml(options);

	return html += fillMold(raw, fillers, options.alias);

}

function buildTag(node, fillers, options) {

	var html = '';

	if(options.pretty) html += indentHtml(options);
	// Build start tag
	html += '<' + node.tag;

	// Append attributes
	if(node.attributes) {
		for(var attribute in node.attributes) {
			html += ' ' + attribute + '="' + node.attributes[attribute] + '"';
		}
	}

	// Close start tag
	html += '>';

	// Handle childless tag
	if(options.voids.indexOf(node.tag) != -1 || !node.in) return html;

	if(options.pretty) options.depth++;

	// Handle tag children
	html += inspectNodeTree(node, fillers, options);

	if(options.pretty) {
		options.depth--;
		html += indentHtml(options);
	}

	// Build end tag
	html += '</' + node.tag + '>';

	return html;

}

module.exports = renderTemplate;
<|endoftext|>


<commit_before>'use strict';
var dns = require('native-dns');
var net = require('net');
var eachAsync = require('each-async');
var onetime = require('onetime');
var roots = require('root-hints')('A');

var timeout = 1000;
var domains = [
	'www.google.com',
	'www.cloudflare.com',
	'www.baidu.com',
	'www.yandex.ru'
];

module.exports = function (cb) {
	cb = onetime(cb);

	// Pick a random root server to query
	var server = roots[Math.floor(Math.random() * roots.length)];

	// Set up a DNS request that requests the authoritative information for
	// the 'com' zone
	var req = dns.Request({
		question: dns.Question({
			name: 'com',
			type: 'NS'
		}),
		server: {
			address: server
		},
		timeout: timeout
	});

	req.on('timeout', function () {
		// We ran into the timeout, we're offline with high confidence
		cb(null, false);
	});

	req.on('message', function (err, answer) {
		if (answer.authority.length && answer._socket.address === server) {
			// We got an answer and the source matches the queried server,
			// we're online with high confidence
			cb(null, true);
		} else {
			// Either DNS intercepting is in place or the response in mangled,
			// try connecting to our domains on port 80, and if one handshake
			// succeeds, we're definitely online
			eachAsync(domains, function (domain, i, next) {
				var socket = new net.Socket();
				socket.setTimeout(timeout);
				socket.on('error', function () {
					socket.destroy();
					next();
				});
				socket.connect(80, domain, function () {
					cb(null, true);
					socket.end();
					next(new Error()); // skip to end
				});
			}, function () {
				cb(null, false);
			});
		}
	});

	req.send();
};
<commit_msg>Remove unneccessary done callback - fix #16<commit_after>'use strict';
var dns = require('native-dns');
var net = require('net');
var eachAsync = require('each-async');
var onetime = require('onetime');
var roots = require('root-hints')('A');

var timeout = 1000;
var domains = [
	'www.google.com',
	'www.cloudflare.com',
	'www.baidu.com',
	'www.yandex.ru'
];

module.exports = function (cb) {
	cb = onetime(cb);

	// Pick a random root server to query
	var server = roots[Math.floor(Math.random() * roots.length)];

	// Set up a DNS request that requests the authoritative information for
	// the 'com' zone
	var req = dns.Request({
		question: dns.Question({
			name: 'com',
			type: 'NS'
		}),
		server: {
			address: server
		},
		timeout: timeout
	});

	req.on('timeout', function () {
		// We ran into the timeout, we're offline with high confidence
		cb(null, false);
	});

	req.on('message', function (err, answer) {
		if (answer.authority.length && answer._socket.address === server) {
			// We got an answer and the source matches the queried server,
			// we're online with high confidence
			cb(null, true);
		} else {
			// Either DNS intercepting is in place or the response in mangled,
			// try connecting to our domains on port 80, and if one handshake
			// succeeds, we're definitely online
			eachAsync(domains, function (domain, i, done) {
				var socket = new net.Socket();
				socket.setTimeout(timeout);
				socket.on('error', function () {
					socket.destroy();
				});
				socket.connect(80, domain, function () {
					cb(null, true);
					socket.end();
					done(new Error()); // skip to end
				});
			}, function () {
				cb(null, false);
			});
		}
	});

	req.send();
};
<|endoftext|>


<commit_before>var save_image_url = 'https://c1.staticflickr.com/3/2900/33745640515_a90c44b434_t.jpg';
var content_image_url = 'https://c1.staticflickr.com/4/3943/33793771665_e25336d636_t.jpg';
var contentCollection = [];

window.onload = function addSaveContentIcon(){
  event.preventDefault;
  getValues();
  var mediaSection = document.getElementsByClassName('media-block__content');
  var dropDown = createMenuField();
  var saveButton = createButtonField('save');
  var contentButton = createButtonField('content');
  mediaSection[4].appendChild(dropDown);
  mediaSection[4].appendChild(saveButton);
  mediaSection[4].prepend(contentButton);

}

function getValues() {
  contentCollection = [];
  chrome.storage.sync.get(null, function(items) {
    for (key in items) {
      contentCollection.push(key);
      console.log(key);
    }
  })
}

function createButtonField(type) {
  var button = createButton(type);
  var buttonField = createField(button, type);
  return buttonField;
}

function createButton(type){
  var button = document.createElement('button');
  var image = createImage(type);
  button.appendChild(image);
  button.id = `${type}_button`;
  button.style = "cursor: pointer";
  button.onclick = function(event){
    var type = event.target.id.split("_")[0];
    eval(type + 'Action()');
  }
  return button;
}

function createField(button, type){
  var buttonField = document.createElement('div');
  buttonField.setAttribute('class', `${type}_button_field`);
  buttonField.appendChild(button);
  return buttonField;
}

function createImage(type) {
  var image = document.createElement('IMG');
  image.id = `${type}_image`;
  var image_url = `${type}_image_url`;
  image.src = eval(image_url);
  return image;
}

function saveAction(){
  var content = document.getElementsByTagName('textarea')[1].value;
  var obj = {};
  obj[content] = content;
  if (content.length <= 1) {
    console.log('Error: No content selected');
    return;
  }
  chrome.storage.sync.set(obj, function() {
    console.log('content saved');
  })
  refreshMenuDiv();
}

function createMenuField() {
  var menuElement = document.createElement('select');
  menuElement.setAttribute('id', 'menuElement');
  menuElement.setAttribute('style', 'display:none');
  return menuElement;
}

function getMenu() {
  return document.getElementById('menuElement');
}

function appendMenuOptions(parentElement, content = contentCollection) {
  debugger;
  parentElement.innerText = "";
  for (var i = 0; i < contentCollection.length; i++) {
    var item = contentCollection[i];
    var element = document.createElement('option');
    element.text = item;
    element.value = item;
    parentElement.appendChild(element);
  }
  return parentElement
}

function refreshMenuDiv() {
  getValues();
  var menu = getMenu();
  newMenu = appendMenuOptions(menu);
  debugger;
  menu.innerHTML = newMenu.innerHTML;
}

function contentAction() {
  var menu = getMenu();
  appendMenuOptions(menu);
  displayMenuDiv();
  // filterMenu();

  // On input, display filtered results in menuElement
  // Add scroll
  // Allow for selection
  // Return selection to input field
}

function filterMenu() {
  var menu = getMenu();
  if (menu.style.display == 'block') {
    var input = document.getElementsByTagName('textarea')[1];
    input.onkeydown = function(event) {
      var filteredList = [];
      for (var i = 0; i < contentCollection.length; i++) {
      // loop through and filter by event target
      debugger;
      filteredList.push(content);
      appendMenuOptions(menu, filteredList);
      }
    }
  }
}

function clearContentDiv() {
  var content = getMenu();
  content.innerHTML = "";
}

function displayMenuDiv() {
  var menu = getMenu();
  if (menu.style.display == 'block' || menu.style.display == '') {
    menu.style.display = 'none';
  } else {
    menu.style.display = 'block';
  }
  // Turn on event watcher for input (toggle on)
}
<commit_msg>resetting input to selected option value<commit_after>var save_image_url = 'https://c1.staticflickr.com/3/2900/33745640515_a90c44b434_t.jpg';
var content_image_url = 'https://c1.staticflickr.com/4/3943/33793771665_e25336d636_t.jpg';
var contentCollection = [];

window.onload = function addSaveContentIcon(){
  event.preventDefault;
  getValues();
  var mediaSection = document.getElementsByClassName('media-block__content');
  var dropDown = createMenuField();
  var saveButton = createButtonField('save');
  var contentButton = createButtonField('content');
  mediaSection[4].appendChild(dropDown);
  mediaSection[4].appendChild(saveButton);
  mediaSection[4].prepend(contentButton);

}

function getValues() {
  contentCollection = [];
  chrome.storage.sync.get(null, function(items) {
    for (key in items) {
      contentCollection.push(key);
      console.log(key);
    }
  })
}

function createButtonField(type) {
  var button = createButton(type);
  var buttonField = createField(button, type);
  return buttonField;
}

function createButton(type){
  var button = document.createElement('button');
  var image = createImage(type);
  button.appendChild(image);
  button.id = `${type}_button`;
  button.style = "cursor: pointer";
  button.onclick = function(event){
    var type = event.target.id.split("_")[0];
    eval(type + 'Action()');
  }
  return button;
}

function createField(button, type){
  var buttonField = document.createElement('div');
  buttonField.setAttribute('class', `${type}_button_field`);
  buttonField.appendChild(button);
  return buttonField;
}

function createImage(type) {
  var image = document.createElement('IMG');
  image.id = `${type}_image`;
  var image_url = `${type}_image_url`;
  image.src = eval(image_url);
  return image;
}

function saveAction(){
  var content = document.getElementsByTagName('textarea')[1].value;
  var obj = {};
  obj[content] = content;
  if (content.length <= 1) {
    console.log('Error: No content selected');
    return;
  }
  chrome.storage.sync.set(obj, function() {
    console.log('content saved');
  })
  refreshMenuDiv();
}

function createMenuField() {
  var menuElement = document.createElement('select');
  menuElement.setAttribute('id', 'menuElement');
  menuElement.setAttribute('style', 'display:none');
  return menuElement;
}

function getMenu() {
  return document.getElementById('menuElement');
}

function appendMenuOptions(parentElement, content = contentCollection) {
  parentElement.innerText = "";
  for (var i = 0; i < contentCollection.length; i++) {
    var item = contentCollection[i];
    var element = document.createElement('option');
    element.text = item;
    element.value = item;
    parentElement.appendChild(element);
  }
  return parentElement
}

function refreshMenuDiv() {
  getValues();
  var menu = getMenu();
  newMenu = appendMenuOptions(menu);
  debugger;
  menu.innerHTML = newMenu.innerHTML;
}

function contentAction() {
  var menu = getMenu();
  appendMenuOptions(menu);
  displayMenuDiv();
  // getSelection(menu);
  // debugger;
  // filterMenu();

  // On input, display filtered results in menuElement
  // Add scroll
  // Allow for selection
  // Return selection to input field
}

function filterMenu() {
  var menu = getMenu();
  if (menu.style.display == 'block') {
    var input = document.getElementsByTagName('textarea')[1];
    input.onkeydown = function(event) {
      var filteredList = [];
      for (var i = 0; i < contentCollection.length; i++) {
      // loop through and filter by event target
      debugger;
      filteredList.push(content);
      appendMenuOptions(menu, filteredList);
      }
    }
  }
}

function clearContentDiv() {
  var content = getMenu();
  content.innerHTML = "";
}

function displayMenuDiv() {
  var menu = getMenu();
  if (menu.style.display == 'block' || menu.style.display == '') {
    menu.style.display = 'none';
  } else {
    menu.style.display = 'block';
    menu.addEventListener('change', function(event) {
      getSelection(event);
    })

  }
  // Turn on event watcher for input (toggle on)
}

function getSelection(event){
  var selection = event.target.value;
  document.getElementsByTagName('textarea')[1].value = selection;
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var gutil = require('gulp-util');
var through = require('through2');

var _ = require('lodash');

var TEMPLATE_PATH = path.join(__dirname, 'tpls', 'constant.tpl.ejs');
var DEFAULT_WRAP_PATH = path.join(__dirname, 'tpls', 'default-wrapper.tpl.ejs');
var AMD_WRAP_PATH = path.join(__dirname, 'tpls', 'amd-wrapper.tpl.ejs');
var COMMONJS_WRAP_PATH = path.join(__dirname, 'tpls', 'commonjs-wrapper.tpl.ejs');
var defaultWrapper, amdWrapper, commonjsWrapper;

var defaults = {
    space: '\t',
    deps: [],
    wrap: false,
    template: undefined,
    templatePath: TEMPLATE_PATH
};

function ngConstantPlugin(opts) {

    var options = _.merge({}, defaults, opts);
    var template = options.template || readFile(options.templatePath);

    return through.obj(objectStream);

    function objectStream(file, enc, cb) {
        /* jshint validthis: true */

        var _this = this;

        if (file.isStream()) {
            _this.emit('error', pluginError('Streaming not supported'));
            return cb();
        }

        try {
            var data = file.isNull() ? {} : JSON.parse(file.contents);

            // Create the module string
            var result = _.template(template, {
                moduleName: options.name || data.name,
                deps:       data.deps || options.deps,
                constants:  getConstants(data, options)
            });

            // Handle wrapping
            if (!options.wrap) { options.wrap = data.wrap; }
            result = wrap(result, options);

            file.path = gutil.replaceExtension(file.path, '.js');
            file.contents = new Buffer(result);
            _this.push(file);
        } catch (err) {
            err.fileName = file.path;
            _this.emit('error', pluginError(err));
        }

        cb();
    }
}

function getConstants(data, options) {
    var opts = options || {};
    if (typeof opts.constants === 'string') {
        opts.constants = JSON.parse(opts.constants);
    }

    var dataCnst = data.constants || data;
    var input = _.extend({}, dataCnst, opts.constants);
    var constants =  _.map(input, function (value, name) {
        return {
            name: name,
            value: stringify(value, opts.space)
        };
    });

    return constants;
}

function pluginError(msg) {
    return new gutil.PluginError('gulp-tslint-log', msg);
}

function wrap(input, options) {
    var wrapper = options.wrap || '<%= __ngModule %>';
    if (wrapper === true) {
        if (!defaultWrapper) { defaultWrapper = readFile(DEFAULT_WRAP_PATH); }
        wrapper = defaultWrapper;
    } else if (wrapper === 'amd') {
        if (!amdWrapper) { amdWrapper = readFile(AMD_WRAP_PATH); }
        wrapper = amdWrapper;
    } else if (wrapper === 'commonjs') {
        if (!commonjsWrapper) { commonjsWrapper = readFile(COMMONJS_WRAP_PATH); }
        wrapper = commonjsWrapper;
    }
    return _.template(wrapper, _.merge({ '__ngModule': input }, options));
}

function readFile(filepath) {
    return fs.readFileSync(filepath, 'utf8');
}

function stringify(value, space) {
    return _.isUndefined(value) ? 'undefined' : JSON.stringify(value, null, space);
}

_.extend(ngConstantPlugin, {
    getConstants: getConstants,
    wrap: wrap
});

module.exports = ngConstantPlugin;
<commit_msg>fix(deps): fallback to getting deps from options first as per documentation<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var gutil = require('gulp-util');
var through = require('through2');

var _ = require('lodash');

var TEMPLATE_PATH = path.join(__dirname, 'tpls', 'constant.tpl.ejs');
var DEFAULT_WRAP_PATH = path.join(__dirname, 'tpls', 'default-wrapper.tpl.ejs');
var AMD_WRAP_PATH = path.join(__dirname, 'tpls', 'amd-wrapper.tpl.ejs');
var COMMONJS_WRAP_PATH = path.join(__dirname, 'tpls', 'commonjs-wrapper.tpl.ejs');
var defaultWrapper, amdWrapper, commonjsWrapper;

var defaults = {
    space: '\t',
    deps: null,
    wrap: false,
    template: undefined,
    templatePath: TEMPLATE_PATH
};

function ngConstantPlugin(opts) {

    var options = _.merge({}, defaults, opts);
    var template = options.template || readFile(options.templatePath);

    return through.obj(objectStream);

    function objectStream(file, enc, cb) {
        /* jshint validthis: true */

        var _this = this;

        if (file.isStream()) {
            _this.emit('error', pluginError('Streaming not supported'));
            return cb();
        }

        try {
            var data = file.isNull() ? {} : JSON.parse(file.contents);

            // Create the module string
            var result = _.template(template, {
                moduleName: options.name || data.name,
                deps:       options.deps || data.deps || [],
                constants:  getConstants(data, options)
            });

            // Handle wrapping
            if (!options.wrap) { options.wrap = data.wrap; }
            result = wrap(result, options);

            file.path = gutil.replaceExtension(file.path, '.js');
            file.contents = new Buffer(result);
            _this.push(file);
        } catch (err) {
            err.fileName = file.path;
            _this.emit('error', pluginError(err));
        }

        cb();
    }
}

function getConstants(data, options) {
    var opts = options || {};
    if (typeof opts.constants === 'string') {
        opts.constants = JSON.parse(opts.constants);
    }

    var dataCnst = data.constants || data;
    var input = _.extend({}, dataCnst, opts.constants);
    var constants =  _.map(input, function (value, name) {
        return {
            name: name,
            value: stringify(value, opts.space)
        };
    });

    return constants;
}

function pluginError(msg) {
    return new gutil.PluginError('gulp-tslint-log', msg);
}

function wrap(input, options) {
    var wrapper = options.wrap || '<%= __ngModule %>';
    if (wrapper === true) {
        if (!defaultWrapper) { defaultWrapper = readFile(DEFAULT_WRAP_PATH); }
        wrapper = defaultWrapper;
    } else if (wrapper === 'amd') {
        if (!amdWrapper) { amdWrapper = readFile(AMD_WRAP_PATH); }
        wrapper = amdWrapper;
    } else if (wrapper === 'commonjs') {
        if (!commonjsWrapper) { commonjsWrapper = readFile(COMMONJS_WRAP_PATH); }
        wrapper = commonjsWrapper;
    }
    return _.template(wrapper, _.merge({ '__ngModule': input }, options));
}

function readFile(filepath) {
    return fs.readFileSync(filepath, 'utf8');
}

function stringify(value, space) {
    return _.isUndefined(value) ? 'undefined' : JSON.stringify(value, null, space);
}

_.extend(ngConstantPlugin, {
    getConstants: getConstants,
    wrap: wrap
});

module.exports = ngConstantPlugin;
<|endoftext|>


<commit_before>var arDrone = require('ar-drone')
var fs = require('fs')
var net = require('net')
var optimist = require('optimist')
var PaVEParser = require('./node_modules/ar-drone/lib/video/PaVEParser')
var split = require('split')
var through = require('through')

// Don't crash node on exceptions
process.on('uncaughtException', function (err) {
  console.error(err.stack)
  try {
    land()
  } catch (e) {}
  setTimeout(function () {
    process.exit(0)
  }, 200)
})

var argv = optimist
  .usage('Usage: $0 [--oculus] [--keyboard]')
  .alias('oculus', 'o')
  .alias('keyboard', 'k')
  .argv

var drone = arDrone.createClient()
var state = { x: 0, y: 0, z: 0, rot: 0 }
var inAir = false
var gestureEnabled = true

drone.disableEmergency()
drone.stop() // Stop command drone was executing before batt died

drone.on('batteryChange', function (num) {
  console.log('battery: ' + num)
})

setInterval(function () {
  console.log(state)
}, 1000)

function set (params) {
  for (var param in params) {
    var val = params[param]

    // Update parameter
    if (val > 1) {
      state[param] = 1
    } else if (val < -1) {
      state[param] = -1
    } else {
      state[param] = val
    }

    // Send movement command to drone
    if (param === 'x') {
      drone.front(val)
    } else if (param === 'y') {
      drone.right(val)
    } else if (param === 'z') {
      drone.up(val)
    } else if (param === 'rot') {
      drone.clockwise(val)
    } else {
      console.error('Invalid param to `set`')
    }
  }
}

function reset () {
  set({x: 0, y: 0, z: 0, rot: 0})
  drone.stop()
}

function takeoff () {
  drone.disableEmergency()
  drone.stop()
  drone.takeoff()
  inAir = true
}

function land () {
  inAir = false
  drone.land()
}

function flipAhead () {
  drone.animate('flipAhead', 500)
}
function flipBehind () {
  drone.animate('flipBehind', 500)
}
function flipLeft () {
  drone.animate('flipLeft', 500)
}
function flipRight () {
  drone.animate('flipRight', 500)
}

function disableGestureTimeout () {
  gestureEnabled = false
  setTimeout(function () {
    gestureEnabled = true
  }, 2000)
}

// Keyboard control
if (argv.keyboard) {
  process.stdin.setRawMode(true)
  process.stdin.on('data', function(chunk) {
    var key = chunk.toString()
    var keyBuf = chunk.toJSON()
    var speed = 0.2

    console.log(key)
    console.log(keyBuf)

    if (Array.isArray(keyBuf)) {
      var UP = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 65)
      var DOWN = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 66)
      var RIGHT = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 67)
      var LEFT = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 68)
    }

    if (key === 'w') {
      set({ x: speed })
    } else if (key === 's') {
      set({ x: -speed })
    } else if (key === 'd') {
      set({ y: speed })
    } else if (key === 'a') {
      set({ y: -speed })
    } else if (UP) {
      set({ z: speed })
    } else if (DOWN) {
      set({ z: -speed })
    } else if (LEFT) {
      set({ rot: -speed }) // COUNTERCLOCKWISE
    } else if (RIGHT) {
      set({ rot: speed }) // CLOCKWISE
    } else if (key === 'e') {
      drone.stop()
    } else if (key === 't') {
      takeoff()
    } else if (key === 'l') {
      land()
    } else if (key === 'k') {
      land()
      setTimeout(function () {
        process.exit(0)
      }, 200)
    } else if (keyBuf[0] === 32) {
      flipAhead()
    }
  })
}

if (argv.oculus) {
  // Connect to oculus server
  var oculusClient = net.connect({ port: 12345 })
  oculusClient.on('error', function (err) {
    console.error('Error connecting to oculus server.')
  })

  oculusClient
    .pipe(split())
    .pipe(through(function (line) {
      var arr = line.split(',')
      var x = Number(-arr[0]), rot = Number(-arr[1]), y = Number(-arr[2])
      set({ x: x, y: y, rot: rot })

      // Gestures:
      //   DOWN to takeoff/land
      //   UP to flip
      if (gestureEnabled) {
        if (x < -1) {
          flipBehind()
          disableGestureTimeout()
        } else if (x > 1) {
          if (inAir) {
            land()
          } else {
            takeoff()
          }
          disableGestureTimeout()
        }
      }
    }))
}

// Video server
net.createServer(function (c) {
  console.log('server connected')

  c.on('end', function() {
    console.log('server disconnected')
  })

  drone.getVideoStream()
    .pipe(new PaVEParser())
    .pipe(through(function (data) {
      this.queue(data.payload)
      console.log('video bits sent')
    }))
    .pipe(c)

}).listen(6969)

// drone.on('navdata', function (data) {
//   console.log(data)
// })

<commit_msg>keyboard control always on -- too useful<commit_after>var arDrone = require('ar-drone')
var fs = require('fs')
var net = require('net')
var optimist = require('optimist')
var PaVEParser = require('./node_modules/ar-drone/lib/video/PaVEParser')
var split = require('split')
var through = require('through')

// Don't crash node on exceptions
process.on('uncaughtException', function (err) {
  console.error(err.stack)
  try {
    land()
  } catch (e) {}
  setTimeout(function () {
    process.exit(0)
  }, 200)
})

var argv = optimist
  .usage('Usage: $0 [--oculus]')
  .alias('oculus', 'o')
  .argv

var drone = arDrone.createClient()
var state = { x: 0, y: 0, z: 0, rot: 0 }
var inAir = false
var gestureEnabled = true

drone.disableEmergency()
drone.stop() // Stop command drone was executing before batt died

drone.on('batteryChange', function (num) {
  console.log('battery: ' + num)
})

setInterval(function () {
  console.log(state)
}, 1000)

function set (params) {
  for (var param in params) {
    var val = params[param]

    // Update parameter
    if (val > 1) {
      state[param] = 1
    } else if (val < -1) {
      state[param] = -1
    } else {
      state[param] = val
    }

    // Send movement command to drone
    if (param === 'x') {
      drone.front(val)
    } else if (param === 'y') {
      drone.right(val)
    } else if (param === 'z') {
      drone.up(val)
    } else if (param === 'rot') {
      drone.clockwise(val)
    } else {
      console.error('Invalid param to `set`')
    }
  }
}

function reset () {
  set({x: 0, y: 0, z: 0, rot: 0})
  drone.stop()
}

function takeoff () {
  drone.disableEmergency()
  drone.stop()
  drone.takeoff()
  inAir = true
}

function land () {
  inAir = false
  drone.land()
}

function flipAhead () {
  drone.animate('flipAhead', 500)
}
function flipBehind () {
  drone.animate('flipBehind', 500)
}
function flipLeft () {
  drone.animate('flipLeft', 500)
}
function flipRight () {
  drone.animate('flipRight', 500)
}

function disableGestureTimeout () {
  gestureEnabled = false
  setTimeout(function () {
    gestureEnabled = true
  }, 2000)
}

// Keyboard control
process.stdin.setRawMode(true)
process.stdin.on('data', function(chunk) {
  var key = chunk.toString()
  var keyBuf = chunk.toJSON()
  var speed = 0.2

  console.log(key)
  console.log(keyBuf)

  if (Array.isArray(keyBuf)) {
    var UP = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 65)
    var DOWN = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 66)
    var RIGHT = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 67)
    var LEFT = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 68)
  }

  if (key === 'k') {
    land()
    setTimeout(function () {
      process.exit(0)
    }, 200)

  if (key === 'w') {
    set({ x: speed })
  } else if (key === 's') {
    set({ x: -speed })
  } else if (key === 'd') {
    set({ y: speed })
  } else if (key === 'a') {
    set({ y: -speed })
  } else if (UP) {
    set({ z: speed })
  } else if (DOWN) {
    set({ z: -speed })
  } else if (LEFT) {
    set({ rot: -speed }) // COUNTERCLOCKWISE
  } else if (RIGHT) {
    set({ rot: speed }) // CLOCKWISE
  } else if (key === 'e') {
    drone.stop()
  } else if (key === 't') {
    takeoff()
  } else if (key === 'l') {
    land()

  } else if (keyBuf[0] === 32) {
    flipAhead()
  }
})

if (argv.oculus) {
  // Connect to oculus server
  var oculusClient = net.connect({ port: 12345 })
  oculusClient.on('error', function (err) {
    console.error('Error connecting to oculus server.')
  })

  oculusClient
    .pipe(split())
    .pipe(through(function (line) {
      var arr = line.split(',')
      var x = Number(-arr[0]), rot = Number(-arr[1]), y = Number(-arr[2])
      set({ x: x, y: y, rot: rot })

      // Gestures:
      //   DOWN to takeoff/land
      //   UP to flip
      if (gestureEnabled) {
        if (x < -1) {
          flipBehind()
          disableGestureTimeout()
        } else if (x > 1) {
          if (inAir) {
            land()
          } else {
            takeoff()
          }
          disableGestureTimeout()
        }
      }
    }))
}

// Video server
net.createServer(function (c) {
  console.log('server connected')

  c.on('end', function() {
    console.log('server disconnected')
  })

  drone.getVideoStream()
    .pipe(new PaVEParser())
    .pipe(through(function (data) {
      this.queue(data.payload)
      console.log('video bits sent')
    }))
    .pipe(c)

}).listen(6969)

// drone.on('navdata', function (data) {
//   console.log(data)
// })

<|endoftext|>


<commit_before>
var locationData = [];

var map, pointarray, heatmap;

  var gradient = [
    'rgba(0, 255, 255, 0)',
    'rgba(0, 255, 255, 1)',
    'rgba(0, 191, 255, 1)',
    'rgba(0, 127, 255, 1)',
    'rgba(0, 63, 255, 1)',
    'rgba(0, 0, 255, 1)',
    'rgba(0, 0, 223, 1)',
    'rgba(0, 0, 191, 1)',
    'rgba(0, 0, 159, 1)',
    'rgba(0, 0, 127, 1)',
    'rgba(63, 0, 91, 1)',
    'rgba(127, 0, 63, 1)',
    'rgba(191, 0, 31, 1)',
    'rgba(255, 0, 0, 1)'
  ]

$.getJSON( "LocationHistory.json", function( data ) {

  for(i = 0; i < data.locations.length; i++){
    locationData.push(
      new google.maps.LatLng(data.locations[i].latitudeE7 / 10000000, data.locations[i].longitudeE7 / 10000000)
    );
  }

  var pointArray = new google.maps.MVCArray(locationData);

  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray,

    // If we don't do this, you get one massive dot above your house and
    // everything else fades to almost invisible. If you're only seeing a
    // bit of data above your most common locations you might want to lower
    // this.
    maxIntensity: 100
  });

  heatmap.setMap(map);

  heatmap.set('gradient', gradient);

  $('#loader').toggle();
});

function initialize() {
  var mapOptions = {
    zoom: 7,
    center: new google.maps.LatLng(52, -0.4)
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

}

function toggleHeatmap() {
  heatmap.setMap(heatmap.getMap() ? null : map);
}

function changeOpacity() {
  heatmap.set('opacity', heatmap.get('opacity') ? null : 0.2);
}

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>Formatting fixes<commit_after>
var locationData = [];

var map, pointarray, heatmap;

var gradient = [
  'rgba(0, 255, 255, 0)',
  'rgba(0, 255, 255, 1)',
  'rgba(0, 191, 255, 1)',
  'rgba(0, 127, 255, 1)',
  'rgba(0, 63, 255, 1)',
  'rgba(0, 0, 255, 1)',
  'rgba(0, 0, 223, 1)',
  'rgba(0, 0, 191, 1)',
  'rgba(0, 0, 159, 1)',
  'rgba(0, 0, 127, 1)',
  'rgba(63, 0, 91, 1)',
  'rgba(127, 0, 63, 1)',
  'rgba(191, 0, 31, 1)',
  'rgba(255, 0, 0, 1)'
]

$.getJSON( "LocationHistory.json", function( data ) {

  for(i = 0; i < data.locations.length; i++){
    locationData.push(
      new google.maps.LatLng(data.locations[i].latitudeE7 / 10000000, data.locations[i].longitudeE7 / 10000000)
    );
  }

  var pointArray = new google.maps.MVCArray(locationData);

  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray,

    // If we don't do this, you get one massive dot above your house and
    // everything else fades to almost invisible. If you're only seeing a
    // bit of data above your most common locations you might want to lower
    // this.
    maxIntensity: 100
  });

  heatmap.setMap(map);

  heatmap.set('gradient', gradient);

  $('#loader').toggle();
});

function initialize() {
  var mapOptions = {
    zoom: 7,
    center: new google.maps.LatLng(52, -0.4)
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

}

function toggleHeatmap() {
  heatmap.setMap(heatmap.getMap() ? null : map);
}

function changeOpacity() {
  heatmap.set('opacity', heatmap.get('opacity') ? null : 0.2);
}

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


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

const path = require('path');
const stripIndent = require('common-tags').stripIndent;

module.exports = {
  name: 'ember-mocha',

  init() {
    this._super.init && this._super.init.apply(this, arguments);

    this.setTestGenerator();
  },

  postBuild() {
    this.checkPackages();
  },

  checkPackages() {
    var packages = Object.keys(this.project.addonPackages);
    if (packages.indexOf('ember-cli-qunit') !== -1) {
      console.warn('\nIt looks like you are using "ember-cli-qunit" which can cause issues with "ember-cli-mocha", please remove this package.\n');
      process.exit(1);
    }
    if (packages.indexOf('ember-cli-htmlbars-inline-precompile') === -1) {
      console.warn('\nIt looks like you\'re not on ember-cli 1.13, which includes ember-cli-htmlbars-inline-precompile by default. Please run: ember install ember-cli-htmlbars-inline-precompile.\n');
      process.exit(1);
    }
  },

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

    this.import('vendor/mocha/mocha.js', { type: 'test' });
    this.import('vendor/mocha/mocha.css', { type: 'test' });
    this.import('vendor/ember-mocha/mocha-configuration.js', { type: 'test' });
    this.import('vendor/ember-mocha/ember-mocha-adapter.js', { type: 'test' });
    this.import('vendor/ember-mocha/test-loader.js', { type: 'test' });

    let addonOptions = this.targetOptions();
    let explicitlyDisabledStyles = addonOptions.disableContainerStyles === true;
    if (!explicitlyDisabledStyles) {
      this.import('vendor/ember-mocha/test-container-styles.css', { type: 'test' });
    }
  },

  targetOptions() {
    if (!this._targetOptions) {
      // 1. check this.parent.options['ember-mocha']
      let targetOptions = this.parent.options && this.parent.options['ember-mocha'];
      // 2. check this.app.options['ember-mocha']
      targetOptions = targetOptions || (this.app && this.app.options && this.app.options['ember-mocha']);
      // 3. check this.parent.options['ember-cli-mocha']
      targetOptions = targetOptions || (this.parent.options && this.parent.options['ember-cli-mocha']);
      // 4. check this.app.options['ember-cli-mocha']
      targetOptions = targetOptions || (this.app && this.app.options && this.app.options['ember-cli-mocha']);
      this._targetOptions = targetOptions || {};
    }

    return this._targetOptions;
  },

  contentFor(type) {
    // Skip if insertContentForTestBody === false.
    if (type === 'test-body' && !(this.targetOptions().insertContentForTestBody === false)) {
      return stripIndent`

      `;
    }
  },

  treeForVendor(tree) {
    const MergeTrees = require('broccoli-merge-trees');
    const Funnel = require('broccoli-funnel');
    let mochaPath = path.dirname(require.resolve('mocha'));

    let mochaTree = new Funnel(this.treeGenerator(mochaPath), {
      destDir: 'mocha',
      annotation: 'ember-mocha#treeForVendor',
    });

    return new MergeTrees([mochaTree, tree]);
  },

  treeForAddonTestSupport(tree) {
    // intentionally not calling _super here
    // so that can have our `import`'s be
    // import { ... } from 'ember-mocha';

    return this.preprocessJs(tree, '/', this.name, {
      registry: this.registry,
    });
  },

  setTestGenerator() {
    this.project.generateTestFile = function(moduleName, tests) {
      var output = `describe('${moduleName}', function() {\n`;

      tests.forEach(function(test) {
        output += `  it('${test.name}', function() {\n`;
        if (test.passed) {
          output +=
            "    // precompiled test passed\n";
        } else {
          output +=
            "    // precompiled test failed\n" +
            `    var error = new chai.AssertionError('${test.errorMessage}');\n` +
            "    error.stack = undefined;\n" +
            "    throw error;\n";
        }
        output +=   "  });\n";
      });

      output += "});\n";

      return output;
    };
  },
};
<commit_msg>Add missing `overrideTestCommandFilter()` method<commit_after>
/* eslint-env node */
'use strict';

const path = require('path');
const stripIndent = require('common-tags').stripIndent;

module.exports = {
  name: 'ember-mocha',

  init() {
    this._super.init && this._super.init.apply(this, arguments);

    this.overrideTestCommandFilter();
    this.setTestGenerator();
  },

  postBuild() {
    this.checkPackages();
  },

  checkPackages() {
    var packages = Object.keys(this.project.addonPackages);
    if (packages.indexOf('ember-cli-qunit') !== -1) {
      console.warn('\nIt looks like you are using "ember-cli-qunit" which can cause issues with "ember-cli-mocha", please remove this package.\n');
      process.exit(1);
    }
    if (packages.indexOf('ember-cli-htmlbars-inline-precompile') === -1) {
      console.warn('\nIt looks like you\'re not on ember-cli 1.13, which includes ember-cli-htmlbars-inline-precompile by default. Please run: ember install ember-cli-htmlbars-inline-precompile.\n');
      process.exit(1);
    }
  },

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

    this.import('vendor/mocha/mocha.js', { type: 'test' });
    this.import('vendor/mocha/mocha.css', { type: 'test' });
    this.import('vendor/ember-mocha/mocha-configuration.js', { type: 'test' });
    this.import('vendor/ember-mocha/ember-mocha-adapter.js', { type: 'test' });
    this.import('vendor/ember-mocha/test-loader.js', { type: 'test' });

    let addonOptions = this.targetOptions();
    let explicitlyDisabledStyles = addonOptions.disableContainerStyles === true;
    if (!explicitlyDisabledStyles) {
      this.import('vendor/ember-mocha/test-container-styles.css', { type: 'test' });
    }
  },

  targetOptions() {
    if (!this._targetOptions) {
      // 1. check this.parent.options['ember-mocha']
      let targetOptions = this.parent.options && this.parent.options['ember-mocha'];
      // 2. check this.app.options['ember-mocha']
      targetOptions = targetOptions || (this.app && this.app.options && this.app.options['ember-mocha']);
      // 3. check this.parent.options['ember-cli-mocha']
      targetOptions = targetOptions || (this.parent.options && this.parent.options['ember-cli-mocha']);
      // 4. check this.app.options['ember-cli-mocha']
      targetOptions = targetOptions || (this.app && this.app.options && this.app.options['ember-cli-mocha']);
      this._targetOptions = targetOptions || {};
    }

    return this._targetOptions;
  },

  contentFor(type) {
    // Skip if insertContentForTestBody === false.
    if (type === 'test-body' && !(this.targetOptions().insertContentForTestBody === false)) {
      return stripIndent`

      `;
    }
  },

  treeForVendor(tree) {
    const MergeTrees = require('broccoli-merge-trees');
    const Funnel = require('broccoli-funnel');
    let mochaPath = path.dirname(require.resolve('mocha'));

    let mochaTree = new Funnel(this.treeGenerator(mochaPath), {
      destDir: 'mocha',
      annotation: 'ember-mocha#treeForVendor',
    });

    return new MergeTrees([mochaTree, tree]);
  },

  treeForAddonTestSupport(tree) {
    // intentionally not calling _super here
    // so that can have our `import`'s be
    // import { ... } from 'ember-mocha';

    return this.preprocessJs(tree, '/', this.name, {
      registry: this.registry,
    });
  },

  overrideTestCommandFilter() {
    let TestCommand = this.project.require('ember-cli/lib/commands/test');

    TestCommand.prototype.buildTestPageQueryString = function(options) {
      let params = [];

      if (options.filter) {
        params.push(`grep=${options.filter}`);

        if (options.invert) {
          params.push('invert=1');
        }
      }

      if (options.query) {
        params.push(options.query);
      }

      return params.join('&');
    };

    TestCommand.prototype.availableOptions.push({
      name: 'invert',
      type: Boolean,
      default: false,
      description: 'Invert the filter specified by the --filter argument',
      aliases: ['i']
    });
  },

  setTestGenerator() {
    this.project.generateTestFile = function(moduleName, tests) {
      var output = `describe('${moduleName}', function() {\n`;

      tests.forEach(function(test) {
        output += `  it('${test.name}', function() {\n`;
        if (test.passed) {
          output +=
            "    // precompiled test passed\n";
        } else {
          output +=
            "    // precompiled test failed\n" +
            `    var error = new chai.AssertionError('${test.errorMessage}');\n` +
            "    error.stack = undefined;\n" +
            "    throw error;\n";
        }
        output +=   "  });\n";
      });

      output += "});\n";

      return output;
    };
  },
};
<|endoftext|>


<commit_before>var crypto = require('crypto');
var scmp = require('scmp');

// Arbitrary min length, nothing should shorter than this:
var MIN_KEY_LENGTH = 16;

module.exports = function(opts) {
  if( typeof(opts) == 'string' ) {
    opts = {
      key: opts,
      hmac: true,
      debug: false
    };
  }
  var key = opts.key;
  var verifyHmac = opts.hmac;
  var debug = opts.debug;
  var reviver = opts.reviver;

  if( !key || typeof(key) != 'string' ) {
    throw new Error('a string key must be specified');
  }
  if( key.length < MIN_KEY_LENGTH ) {
    throw new Error('key must be at least ' + MIN_KEY_LENGTH + ' characters long');
  }
  if( reviver !== undefined && reviver !== null && typeof(reviver) != 'function' ) {
    throw new Error('reviver must be a function');
  }

  // Use SHA-256 to derive a 32-byte key from the specified string.
  // NOTE: We could alternatively do some kind of key stretching here.
  var cryptoKey = crypto.createHash('sha256').update(key).digest();

  // Returns the HMAC(text) using the derived cryptoKey
  // Defaults to returning the result as hex.
  function hmac(text, format) {
    format = format || 'hex';
    return crypto.createHmac('sha256', cryptoKey).update(text).digest(format);
  }

  // Encrypts an arbitrary object using the derived cryptoKey and retursn the result as text.
  // The object is first serialized to JSON (via JSON.stringify) and the result is encrypted.
  //
  // The format of the output is:
  // [<hmac>]<iv><encryptedJson>
  //
  // <hmac>             : Optional HMAC
  // <iv>               : Randomly generated initailization vector
  // <encryptedJson>    : The encrypted object
  function encrypt(obj) {
    var json = JSON.stringify(obj);

    // First generate a random IV.
    // AES-256 IV size is sixteen bytes:
    var iv = crypto.randomBytes(16);

    // Make sure to use the 'iv' variant when creating the cipher object:
    var cipher = crypto.createCipheriv('aes256', cryptoKey, iv);

    // Generate the encrypted json:
    var encryptedJson = cipher.update(json, 'utf8', 'base64') + cipher.final('base64');

    // Include the hex-encoded IV + the encrypted base64 data
    // NOTE: We're using hex for encoding the IV to ensure that it's of constant length.
    var result = iv.toString('hex') + encryptedJson;

    if( verifyHmac ) {
      // Prepend an HMAC to the result to verify it's integrity prior to decrypting.
      // NOTE: We're using hex for encoding the hmac to ensure that it's of constant length
      result = hmac(result, 'hex') + result;
    }

    return result;
  }

  // Decrypts the encrypted cipherText and returns back the original object.
  // If the cipherText cannot be decrypted (bad key, bad text, bad serialization) then it returns null.
  //
  // NOTE: This function never throws an error. It will instead return null if it cannot decrypt the cipherText.
  // NOTE: It's possible that the data decrypted is null (since it's valid input for encrypt(...)).
  //       It's up to the caller to decide if the result is valid.
  function decrypt(cipherText) {
    if( !cipherText ) {
      return null;
    }
    try {
      if( verifyHmac ) {
        // Extract the HMAC from the start of the message:
        var expectedHmac = cipherText.substring(0, 64);
        // The remaining message is the IV + encrypted message:
        cipherText = cipherText.substring(64);
        // Calculate the actual HMAC of the message:
        var actualHmac = hmac(cipherText);
        if( !scmp(new Buffer(actualHmac), new Buffer(expectedHmac)) ) {
          throw new Error('HMAC does not match');
        }
      }

      // Extract the IV from the beginning of the message:
      var iv = new Buffer(cipherText.substring(0,32), 'hex');
      // The remaining text is the encrypted JSON:
      var encryptedJson = cipherText.substring(32);

      // Make sure to use the 'iv' variant when creating the decipher object:
      var decipher = crypto.createDecipheriv('aes256', cryptoKey, iv);
      // Decrypt the JSON:
      var json = decipher.update(encryptedJson, 'base64', 'utf8') + decipher.final('utf8');

      // Return the parsed object:
      return JSON.parse(json, reviver);
    } catch( e ) {
      // If we get an error log it and ignore it. Decrypting should never fail.
      if( debug ) {
        console.error('Exception in decrypt (ignored): %s', e);
      }
      return null;
    }
  }

  return {
    encrypt: encrypt,
    decrypt: decrypt,
    hmac: hmac
  };
};
<commit_msg>Replace new Buffer(...) with Buffer.from(...)<commit_after>var crypto = require('crypto');
var scmp = require('scmp');

// Arbitrary min length, nothing should shorter than this:
var MIN_KEY_LENGTH = 16;

module.exports = function(opts) {
  if( typeof(opts) == 'string' ) {
    opts = {
      key: opts,
      hmac: true,
      debug: false
    };
  }
  var key = opts.key;
  var verifyHmac = opts.hmac;
  var debug = opts.debug;
  var reviver = opts.reviver;

  if( !key || typeof(key) != 'string' ) {
    throw new Error('a string key must be specified');
  }
  if( key.length < MIN_KEY_LENGTH ) {
    throw new Error('key must be at least ' + MIN_KEY_LENGTH + ' characters long');
  }
  if( reviver !== undefined && reviver !== null && typeof(reviver) != 'function' ) {
    throw new Error('reviver must be a function');
  }

  // Use SHA-256 to derive a 32-byte key from the specified string.
  // NOTE: We could alternatively do some kind of key stretching here.
  var cryptoKey = crypto.createHash('sha256').update(key).digest();

  // Returns the HMAC(text) using the derived cryptoKey
  // Defaults to returning the result as hex.
  function hmac(text, format) {
    format = format || 'hex';
    return crypto.createHmac('sha256', cryptoKey).update(text).digest(format);
  }

  // Encrypts an arbitrary object using the derived cryptoKey and retursn the result as text.
  // The object is first serialized to JSON (via JSON.stringify) and the result is encrypted.
  //
  // The format of the output is:
  // [<hmac>]<iv><encryptedJson>
  //
  // <hmac>             : Optional HMAC
  // <iv>               : Randomly generated initailization vector
  // <encryptedJson>    : The encrypted object
  function encrypt(obj) {
    var json = JSON.stringify(obj);

    // First generate a random IV.
    // AES-256 IV size is sixteen bytes:
    var iv = crypto.randomBytes(16);

    // Make sure to use the 'iv' variant when creating the cipher object:
    var cipher = crypto.createCipheriv('aes256', cryptoKey, iv);

    // Generate the encrypted json:
    var encryptedJson = cipher.update(json, 'utf8', 'base64') + cipher.final('base64');

    // Include the hex-encoded IV + the encrypted base64 data
    // NOTE: We're using hex for encoding the IV to ensure that it's of constant length.
    var result = iv.toString('hex') + encryptedJson;

    if( verifyHmac ) {
      // Prepend an HMAC to the result to verify it's integrity prior to decrypting.
      // NOTE: We're using hex for encoding the hmac to ensure that it's of constant length
      result = hmac(result, 'hex') + result;
    }

    return result;
  }

  // Decrypts the encrypted cipherText and returns back the original object.
  // If the cipherText cannot be decrypted (bad key, bad text, bad serialization) then it returns null.
  //
  // NOTE: This function never throws an error. It will instead return null if it cannot decrypt the cipherText.
  // NOTE: It's possible that the data decrypted is null (since it's valid input for encrypt(...)).
  //       It's up to the caller to decide if the result is valid.
  function decrypt(cipherText) {
    if( !cipherText ) {
      return null;
    }
    try {
      if( verifyHmac ) {
        // Extract the HMAC from the start of the message:
        var expectedHmac = cipherText.substring(0, 64);
        // The remaining message is the IV + encrypted message:
        cipherText = cipherText.substring(64);
        // Calculate the actual HMAC of the message:
        var actualHmac = hmac(cipherText);
        if( !scmp(Buffer.from(actualHmac, 'hex'), Buffer.from(expectedHmac, 'hex')) ) {
          throw new Error('HMAC does not match');
        }
      }

      // Extract the IV from the beginning of the message:
      var iv = new Buffer(cipherText.substring(0,32), 'hex');
      // The remaining text is the encrypted JSON:
      var encryptedJson = cipherText.substring(32);

      // Make sure to use the 'iv' variant when creating the decipher object:
      var decipher = crypto.createDecipheriv('aes256', cryptoKey, iv);
      // Decrypt the JSON:
      var json = decipher.update(encryptedJson, 'base64', 'utf8') + decipher.final('utf8');

      // Return the parsed object:
      return JSON.parse(json, reviver);
    } catch( e ) {
      // If we get an error log it and ignore it. Decrypting should never fail.
      if( debug ) {
        console.error('Exception in decrypt (ignored): %s', e);
      }
      return null;
    }
  }

  return {
    encrypt: encrypt,
    decrypt: decrypt,
    hmac: hmac
  };
};
<|endoftext|>