<commit_before>'use strict';

/**
 * Module dependencies
 */
var mongoose = require('mongoose'),
    _ = require('lodash'),
    Mcp3008 = require('mcp3008.js'),
    adc = new Mcp3008(),
    Tmp35Model = mongoose.model('Tmp35');

/**
 * Handles the interaction a tmp35 sensor connected through
 * a mcp3008 to the raspberry pi
 * @constructor
 * @param {object} options  options for the sensor
 */
function Tmp35(options) {
  this.settings = _.assign({
    'rVoltage': 3.3,
    'database': true,
  }, options );

  if( typeof this.settings.sensorName === 'undefined') {
    throw new Error('TMP35: sensorName must be given');
  }
  if( typeof this.settings.pin === 'undefined') {
    throw new Error('TMP35: pin must be specified');
  } else if(this.settings.pin < 0 || this.settings.pin > 7){
    throw new Error('TMP35: pin must be between 0 and 7');
  }
}

/**
 * Save read value to the database
 *
 * The read data is saved in documents for each hour
 * The read value contains a 2-dimensional array with the reads
 * the first demension is the hour the second the minute
 *
 * @param {object} self
 * @param {mixed} value  the value to save from reading
 * @param {function} callback  callback function
 * @api private
 */
var save = function(self, value, callback) {
  if(typeof callback !== 'function'){
    throw new Error('Tmp35.save() has to be called with callback function');
  }

  var date = new Date(),
      hour = date.getHours(),
      minute = date.getMinutes(),
      hourTimestamp = date.setMinutes(0, 0, 0),
      data = {};

  // Base data
  var search = {
    timestamp: hourTimestamp,
    sensor: self.settings.sensorName,
  };

  // Insert read in two dimensional array
  data['read.'+ hour + '.' + minute] = value;

  Tmp35Model.update(search, data, { 'upsert': true }, function(err, affLn) {
    if(err) {
      return callback(err);
    } else {
      return callback(null);
    }
  });
};

/**
 * Reads the current state of the tmp35
 * @return {double} read value
 * @api public
 */
Tmp35.prototype.read = function(callback){
  var self = this;
  if(typeof callback !== 'function'){
    return (new Error('Tmp35.read() has to be called with callback function'), null);
  }
  // Read value from mcp3008
  adc.read(this.settings.pin, function(value) {
    value = value / self.settings.rVoltage; // convert from bit to celsius
    value = value - 0.5; // 500mv offset from datasheet
    value = Math.round(value * 10) / 10; // round with 1 decimal place

    if(!value){
      return callback(new Error('Tmp35.read() get\'s no response from sensor'), null);
    }

    if(self.settings.database === true) {
      save(self, value, function(err) {
        if(err) {
          return callback(err, value);
        } else {
          return callback(null, value);
        }
      });
    } else {
      return callback(null, value);
    }
  });
};

/**
 * @ignore
 */
module.exports = Tmp35;
<commit_msg>Catch errors from tmp35 read<commit_after>'use strict';

/**
 * Module dependencies
 */
var mongoose = require('mongoose'),
    _ = require('lodash'),
    Mcp3008 = require('mcp3008.js'),
    adc = new Mcp3008(),
    Tmp35Model = mongoose.model('Tmp35');

/**
 * Handles the interaction a tmp35 sensor connected through
 * a mcp3008 to the raspberry pi
 * @constructor
 * @param {object} options  options for the sensor
 */
function Tmp35(options) {
  this.settings = _.assign({
    'rVoltage': 3.3,
    'database': true,
  }, options );

  if( typeof this.settings.sensorName === 'undefined') {
    throw new Error('TMP35: sensorName must be given');
  }
  if( typeof this.settings.pin === 'undefined') {
    throw new Error('TMP35: pin must be specified');
  } else if(this.settings.pin < 0 || this.settings.pin > 7){
    throw new Error('TMP35: pin must be between 0 and 7');
  }
}

/**
 * Save read value to the database
 *
 * The read data is saved in documents for each hour
 * The read value contains a 2-dimensional array with the reads
 * the first demension is the hour the second the minute
 *
 * @param {object} self
 * @param {mixed} value  the value to save from reading
 * @param {function} callback  callback function
 * @api private
 */
var save = function(self, value, callback) {
  if(typeof callback !== 'function'){
    throw new Error('Tmp35.save() has to be called with callback function');
  }

  var date = new Date(),
      hour = date.getHours(),
      minute = date.getMinutes(),
      hourTimestamp = date.setMinutes(0, 0, 0),
      data = {};

  // Base data
  var search = {
    timestamp: hourTimestamp,
    sensor: self.settings.sensorName,
  };

  // Insert read in two dimensional array
  data['read.'+ hour + '.' + minute] = value;

  Tmp35Model.update(search, data, { 'upsert': true }, function(err, affLn) {
    if(err) {
      return callback(err);
    } else {
      return callback(null);
    }
  });
};

/**
 * Reads the current state of the tmp35
 * @return {double} read value
 * @api public
 */
Tmp35.prototype.read = function(callback){
  var self = this;
  if(typeof callback !== 'function'){
    return (new Error('Tmp35.read() has to be called with callback function'), null);
  }
  // Read value from mcp3008
  adc.read(this.settings.pin, function(value) {
    if(value <= 0 || value >= 1023) {
      return callback(new Error('Tmp35.read() get\'s invalid response from sensor'), null);
    }
    value = value / self.settings.rVoltage; // convert from bit to celsius
    value = value - 0.5; // 500mv offset from datasheet
    value = Math.round(value * 10) / 10; // round with 1 decimal place

    if(!value){
      return callback(new Error('Tmp35.read() get\'s no response from sensor'), null);
    }

    if(self.settings.database === true) {
      save(self, value, function(err) {
        if(err) {
          return callback(err, value);
        } else {
          return callback(null, value);
        }
      });
    } else {
      return callback(null, value);
    }
  });
};

/**
 * @ignore
 */
module.exports = Tmp35;
<|endoftext|>


<commit_before>var elasticsearch = require('elasticsearch');
var querystring = require('querystring');
var cip = require('../cip-methods.js');

// Autosuggest for search field
exports.suggest = function suggest(req, res) {
    var es_client = req.app.get('es_client');
    var text = req.param('text');
    var query = {
        "body": {
            "suggest" : {
                "text" : text,
                "completion" : {
                    "field" : "suggest",
                    "fuzzy" : {
                        "fuzziness" : 1
                    }
                }
            }
        }
    };

    es_client.suggest(query).then(function (resp) {
        var results = [];
        var temp_results = resp.suggest;
        res.header('Content-type', 'application/json; charset=utf-8');
        if(resp.suggest && resp.suggest.length >= 1) {
            var suggestions = resp.suggest[0].options;
            res.json(suggestions);
        }
    });
};
<commit_msg>Adding error handling on json.suggest<commit_after>var elasticsearch = require('elasticsearch');
var querystring = require('querystring');
var cip = require('../cip-methods.js');

// Autosuggest for search field
exports.suggest = function suggest(req, res, next) {
    var es_client = req.app.get('es_client');
    var text = req.param('text');
    var query = {
        "body": {
            "suggest" : {
                "text" : text,
                "completion" : {
                    "field" : "suggest",
                    "fuzzy" : {
                        "fuzziness" : 1
                    }
                }
            }
        }
    };

    es_client.suggest(query).then(function (resp) {
        var results = [];
        var temp_results = resp.suggest;
        res.header('Content-type', 'application/json; charset=utf-8');
        if(resp.suggest && resp.suggest.length >= 1) {
            var suggestions = resp.suggest[0].options;
            res.json(suggestions);
        } else {
            next(new Error('Empty suggestion result from Elasticsearch.'));
        }
    }, function(err) {
        next(new Error('Error getting suggestions from Elasticsearch: '+err));
    });
};
<|endoftext|>


<commit_before>/**
  Delve Server Manager
  @description Manages the Delve server process
**/
'use babel';

const ChildProc    = require('child-process');
const EventEmitter = require('events');
const Path         = require('path');

import { Config } from './config.js';

const delveCommands = {
  debug: 'debug',
  test: 'test'
};

/**
  @class
  @extends EventEmitter
  @name DelveServerMgr
  @desc Manages the Delve server process and lifecycle of the session
  @emits 'startServer' on delve server start, gives host & port of server
  @emits 'error' on delve server error or unexpected disconnect
**/
export default class DelveServerMgr extends EventEmitter {
  constructor() {
    this.delveProc = null;
    this._pid = null;
    this.hasSessionStarted = false;
  }

  startDebugSession(packagePath, flags) {
    this.spawnProcess(delveCommands.debug, packagePath, flags);
  }

  startTestingSession(packagePath, flags) {
    this.spawnProcess(delveCommands.test, packagePath, flags);
  }

  endSession() {
    this.hasSessionStarted = false;
    this.delveProc.kill();
    this._pid = null;
    this.delveProc = null;
  }

  /**
    @private
    @name #spawnProcess
    @desc creates a new delve process with the given command and registers
      our event handlers with it
    @param { String } command
    @param { String } cwd => will affect what package is being run against
    @param { String|String[] } buildFlags :optional
  **/
  spawnProcess(command, cwd, buildFlags) {
    let { host, port, logServerMessages } = Config;
    let args = [ command, '--headless', `--listen=${host}:${port}` ];

    if (buildFlags)
      if (Array.isArray(buildFlags))
        args.push(`--build-flags=${buildFlags.join(' ')}`);
      else
        args.push(`--build-flags="${buildFlags}"`);

    if (logServerMessages) args.push('--log');

    this.delveProc = ChildProc.spawn('dlv', args, { cwd: Path.resolve(cwd) });
    this._pid = this.delveProc.pid;
    this.isRemote = false;

    this.delveProc.on('data', data => {
      if (!this.hasSessionStarted) {
        console.debug('Received server start from Delve server', data);
        this.hasSessionStarted = true;
        return this.emit('serverStart', host, port);
      }

      console.debug('Received Delve data: ', data);
    });

    this.delveProc.on('error', err => this.emit('error', err));
    this.delveProc.on('disconnect', () => {
      // make sure we think we have a session before declaring an error
      if (this.hasSessionStarted)
        this.emit('error', new Error('Delve server disconnected'));
    });

    if (logServerMessages)
      this.delveProc.on('message', msg => console.debug('Delve: ', msg));
  }
}
<commit_msg>Handle delve process 'close' event<commit_after>/**
  Delve Server Manager
  @description Manages the Delve server process
**/
'use babel';

const ChildProc    = require('child-process');
const EventEmitter = require('events');
const Path         = require('path');

import { Config } from './config.js';

const delveCommands = {
  debug: 'debug',
  test: 'test'
};

/**
  @class
  @extends EventEmitter
  @name DelveServerMgr
  @desc Manages the Delve server process and lifecycle of the session
  @emits 'startServer' on delve server start, gives host & port of server
  @emits 'error' on delve server error or unexpected disconnect
**/
export default class DelveServerMgr extends EventEmitter {
  constructor() {
    this.delveProc = null;
    this._pid = null;
    this.hasSessionStarted = false;
  }

  startDebugSession(packagePath, flags) {
    this.spawnProcess(delveCommands.debug, packagePath, flags);
  }

  startTestingSession(packagePath, flags) {
    this.spawnProcess(delveCommands.test, packagePath, flags);
  }

  endSession() {
    this.hasSessionStarted = false;
    this.delveProc.kill();
    this._pid = null;
    this.delveProc = null;
  }

  /**
    @private
    @name #spawnProcess
    @desc creates a new delve process with the given command and registers
      our event handlers with it
    @param { String } command
    @param { String } cwd => will affect what package is being run against
    @param { String|String[] } buildFlags :optional
  **/
  spawnProcess(command, cwd, buildFlags) {
    let { host, port, logServerMessages } = Config;
    let args = [ command, '--headless', `--listen=${host}:${port}` ];

    if (buildFlags)
      if (Array.isArray(buildFlags))
        args.push(`--build-flags=${buildFlags.join(' ')}`);
      else
        args.push(`--build-flags="${buildFlags}"`);

    if (logServerMessages) args.push('--log');

    this.delveProc = ChildProc.spawn('dlv', args, { cwd: Path.resolve(cwd) });
    this._pid = this.delveProc.pid;
    this.isRemote = false;

    this.delveProc.on('data', data => {
      if (!this.hasSessionStarted) {
        console.debug('Received server start from Delve server', data);
        this.hasSessionStarted = true;
        return this.emit('serverStart', host, port);
      }

      console.debug('Received Delve data: ', data);
    });

    this.delveProc.on('error', err => this.emit('error', err));
    this.delveProc.on('disconnect', () => {
      // make sure we think we have a session before declaring an error
      if (this.hasSessionStarted)
        this.emit('error', new Error('Delve server disconnected'));
    });

    this.delveProc.on('close', (exitCode, signal) =>
      this.emit(
        'error',
        new Error(`Delve exited with code ${exitCode} from ${signal}`)
      )
    );

    if (logServerMessages)
      this.delveProc.on('message', msg => console.debug('Delve: ', msg));
  }
}
<|endoftext|>


<commit_before>var Set = require('../util/set');

module.exports = function (pkgs, dependencies, pkgName) {

  if (dependencies === undefined || dependencies.length === 0) {
    return [];
  }

  var ret = new Set();
  var loop = function (name) {
    if (!(name in pkgs)) {
      throw new Error('Package [' + name + '] not found!');
    }
    if (name === pkgName) {
      // TODO: warn this circular dependency
      return;
    }
    if (!ret.has(name)) {
      ret.add(name);
      var subDep = pkgs[name].dependencies;
      if (subDep && subDep.forEach) {
        subDep.forEach(loop);
      }
    }
  };

  dependencies.forEach(loop);

  return ret.array;

};
<commit_msg>Update recur: check circularity before existence<commit_after>var Set = require('../util/set');

module.exports = function (pkgs, dependencies, pkgName) {

  if (dependencies === undefined || dependencies.length === 0) {
    return [];
  }

  var ret = new Set();
  var loop = function (name) {
    if (name === pkgName) {
      // TODO: warn this circular dependency
      return;
    }
    if (!(name in pkgs)) {
      throw new Error('Package [' + name + '] not found!');
    }
    if (!ret.has(name)) {
      ret.add(name);
      var subDep = pkgs[name].dependencies;
      if (subDep && subDep.forEach) {
        subDep.forEach(loop);
      }
    }
  };

  dependencies.forEach(loop);

  return ret.array;

};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2012 Andreas Madsen
 * MIT License
 */

(function () {
  "use strict";

  var helpers = require('../helpers.js');
  var path = require('path');

  var core = require(path.join(helpers.core, 'core.js'));
  var Process = require(path.join(helpers.core, 'process.js'));
  var streams = require(path.join(helpers.core, 'streams.js'));

  // get and parse the options
  var options = JSON.parse(process.env.nestedOptions);

  // get the monitor module given by options.monitor
  var Monitor = require(options.monitor).Monitor;

  // create a new process object
  // the child will first be spawned when child.spawn is executed
  var child = new Process(options);

  // first create monitor object, the callback is executed when
  // the monitor constructor call this.ready
  var setupMonitor = function (emits, message) {
    var monitorOptions = options.options;
    var monitor = new Monitor(message, monitorOptions, function () {

      // emit events before starting child
      emits.forEach(function (event) {
        monitor.emit(event.name, event.state);
      });

      // spawn child when monitor is ready
      child.spawn();

      // start pumping streams to monitor
      child.streamPump(monitor);
    });

    // relay stop and restart to process event on monitor
    child.on('stop', monitor.emit.bind(monitor, 'process', 'stop'));
    child.on('restart', monitor.emit.bind(monitor, 'process', 'restart'));
  };

  // handle communication between daemon and pump
  if (options.strategy === 'daemon') {

    // setup IPC channel with daemon
    var ipc = new streams.LineStream(process.stdout, process.stdin);
    ipc.on('message', function (msg) {

      // watch daemon by its PID
      // callback will be executed when dead
      helpers.processWatcher(msg.daemon, function () {

        // kill child process
        child.kill();

        // when the child is dead start a new daemon
        helpers.processWatcher(child.pid, function () {
          // the restart argument will let the the daemon.js know that it was
          // restarted
          var daemon = core.spawnDaemon(options, ['restart']);

          // the streams will be closed followed by killing the this process
          // this mimics the execute.js procedure but without the extra overhead
          // of createing a new process.
          daemon.close(process.exit.bind(process, 0));
        });
      });

      // start monitor with a errroMessage if exist
      setupMonitor(msg.emit, msg.message);
    });

    // when child start or restart send new PID information to daemon
    var informDaemon = function () {
      ipc.send({cmd: 'pid', pid: child.pid});
    };
    child.on('start', informDaemon);
    child.on('restart', informDaemon);

  } else {
    setupMonitor([{name: 'monitor', state: 'start'}], null);
  }

  // handle child death
  child.on('stop', function () {

    // restart child
    child.spawn(true);
  });

})();
<commit_msg>[fix] print output when in development<commit_after>/**
 * Copyright (c) 2012 Andreas Madsen
 * MIT License
 */

(function () {
  "use strict";

  var helpers = require('../helpers.js');
  var path = require('path');

  var core = require(path.join(helpers.core, 'core.js'));
  var Process = require(path.join(helpers.core, 'process.js'));
  var streams = require(path.join(helpers.core, 'streams.js'));

  // get and parse the options
  var options = JSON.parse(process.env.nestedOptions);

  // get the monitor module given by options.monitor
  var Monitor = require(options.monitor).Monitor;

  // create a new process object
  // the child will first be spawned when child.spawn is executed
  var child = new Process(options);

  // when useing development print output
  if (options.strategy === 'development') {
    child.streamPump(process);
  }

  // first create monitor object, the callback is executed when
  // the monitor constructor call this.ready
  var setupMonitor = function (emits, message) {
    var monitorOptions = options.options;
    var monitor = new Monitor(message, monitorOptions, function () {

      // emit events before starting child
      emits.forEach(function (event) {
        monitor.emit(event.name, event.state);
      });

      // spawn child when monitor is ready
      child.spawn();

      // start pumping streams to monitor
      child.streamPump(monitor);
    });

    // relay stop and restart to process event on monitor
    child.on('stop', monitor.emit.bind(monitor, 'process', 'stop'));
    child.on('restart', monitor.emit.bind(monitor, 'process', 'restart'));
  };

  // handle communication between daemon and pump
  if (options.strategy === 'daemon') {

    // setup IPC channel with daemon
    var ipc = new streams.LineStream(process.stdout, process.stdin);
    ipc.on('message', function (msg) {

      // watch daemon by its PID
      // callback will be executed when dead
      helpers.processWatcher(msg.daemon, function () {

        // kill child process
        child.kill();

        // when the child is dead start a new daemon
        helpers.processWatcher(child.pid, function () {
          // the restart argument will let the the daemon.js know that it was
          // restarted
          var daemon = core.spawnDaemon(options, ['restart']);

          // the streams will be closed followed by killing the this process
          // this mimics the execute.js procedure but without the extra overhead
          // of createing a new process.
          daemon.close(process.exit.bind(process, 0));
        });
      });

      // start monitor with a errroMessage if exist
      setupMonitor(msg.emit, msg.message);
    });

    // when child start or restart send new PID information to daemon
    var informDaemon = function () {
      ipc.send({cmd: 'pid', pid: child.pid});
    };
    child.on('start', informDaemon);
    child.on('restart', informDaemon);

  } else {
    setupMonitor([{name: 'monitor', state: 'start'}], null);
  }

  // handle child death
  child.on('stop', function () {

    // restart child
    child.spawn(true);
  });

})();
<|endoftext|>


<commit_before>var extension = module.exports = function () {};

extension.cache = function (opts, resolver) {
	if (typeof opts == "function") {
		resolver   = opts;
		opts = {};
	}
	return new Cache(opts || {}, resolver);
};

function Cache(opts, resolver) {
	var cache = {};
	var queue = {};
	var check_cache = function () {
		var dt = Date.now();

		for (var k in cache) {
			if (cache[k].e === null) continue;
			if (cache[k].e > dt) continue;

			delete cache[k];
		}
	};

	if (!opts.hasOwnProperty("timeout")) {
		opts.timeout = null;
	}

	return {
		cached: function () {
			var key = Array.prototype.join.call(arguments, "|");

			return cache.hasOwnProperty(key) && (cache[key].e === null || cache[key].e > Date.now());
		},
		queued: function () {
			return queue.hasOwnProperty(Array.prototype.join.call(arguments, "|"));
		},
		get: function () {
			var args = Array.prototype.slice.apply(arguments);
			var next = args.pop();
			var key  = args.join("|");

			if (cache.hasOwnProperty(key)) {
				if (cache[key].e !== null && cache[key].e <= Date.now()) {
					// expired
					delete cache[key];
				} else {
					next.apply(null, cache[key].a);
					return this;
				}
			}

			if (queue.hasOwnProperty(key)) {
				queue[key].push(next);
				return this;
			}

			queue[key] = [ next ];

			args.push(function () {
				var args = Array.prototype.slice.apply(arguments);

				cache[key] = {
					a : args,
					e : (opts.timeout === null ? null : Date.now() + (opts.timeout * 1000))
				};

				for (var i = 0; i < queue[key].length; i++) {
					queue[key][i].apply(null, cache[key].a);
				}

				delete queue[key];

				if (opts.timeout !== null) {
					check_cache();
				}
			});

			resolver.apply(null, args);
			return this;
		}
	};
}
<commit_msg>Removes unnecessary line from cache extension<commit_after>var extension = module.exports = function () {};

extension.cache = function (opts, resolver) {
	if (typeof opts == "function") {
		resolver   = opts;
		opts = {};
	}
	return new Cache(opts || {}, resolver);
};

function Cache(opts, resolver) {
	var cache = {};
	var queue = {};
	var check_cache = function () {
		var dt = Date.now();

		for (var k in cache) {
			if (cache[k].e > dt) continue;

			delete cache[k];
		}
	};

	if (!opts.hasOwnProperty("timeout")) {
		opts.timeout = null;
	}

	return {
		cached: function () {
			var key = Array.prototype.join.call(arguments, "|");

			return cache.hasOwnProperty(key) && (cache[key].e === null || cache[key].e > Date.now());
		},
		queued: function () {
			return queue.hasOwnProperty(Array.prototype.join.call(arguments, "|"));
		},
		get: function () {
			var args = Array.prototype.slice.apply(arguments);
			var next = args.pop();
			var key  = args.join("|");

			if (cache.hasOwnProperty(key)) {
				if (cache[key].e !== null && cache[key].e <= Date.now()) {
					// expired
					delete cache[key];
				} else {
					next.apply(null, cache[key].a);
					return this;
				}
			}

			if (queue.hasOwnProperty(key)) {
				queue[key].push(next);
				return this;
			}

			queue[key] = [ next ];

			args.push(function () {
				var args = Array.prototype.slice.apply(arguments);

				cache[key] = {
					a : args,
					e : (opts.timeout === null ? null : Date.now() + (opts.timeout * 1000))
				};

				for (var i = 0; i < queue[key].length; i++) {
					queue[key][i].apply(null, cache[key].a);
				}

				delete queue[key];

				if (opts.timeout !== null) {
					check_cache();
				}
			});

			resolver.apply(null, args);
			return this;
		}
	};
}
<|endoftext|>


<commit_before>const childProcess = require('child_process');
const escapeRegExp = require('lodash.escaperegexp');
const minimatch = require('minimatch');
const sortBy = require('lodash.sortby');
const uniqBy = require('lodash.uniqby');

const JsModule = require('./JsModule');

/**
 * Takes a string in any of the following four formats:
 *   dash-separated
 *   snake_case
 *   camelCase
 *   PascalCase
 * and turns it into a star-separated lower case format, like so:
 *   star*separated
 *
 * @param {String} string
 * @return {String}
 */
function formattedToRegex(string) {
  // Based on
  // http://stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby

  // The pattern to match in between words. The "es" and "s" match is there
  // to catch pluralized folder names. There is a risk that this is overly
  // aggressive and will lead to trouble down the line. In that case, we can
  // consider adding a configuration option to control mapping a singular
  // variable name to a plural folder name (suggested by @lencioni in #127).
  // E.g.
  //
  // {
  //   "^mock": "./mocks/"
  // }
  const splitPattern = '(es|s)?.?';

  // Split up the string, allow pluralizing and a single (any) character
  // in between. This will make e.g. 'fooBar' match 'foos/bar', 'foo_bar',
  // and 'foobar'.
  return string
    .replace(/([a-z\d])([A-Z])/g, `$1${splitPattern}$2`) // camelCase
    .replace(/[-_]/g, splitPattern)
    .toLowerCase();
}

/**
 * @param {Configuration} config
 * @param {String} variableName
 * @return {Array<JsModule>}
 */
function findEnvironmentCoreModules(config, variableName) {
  return config.environmentCoreModules()
    .filter(dep => dep.toLowerCase() === variableName.toLowerCase())
    .map(dep => new JsModule({ importPath: dep }));
}

/**
 * @param {Configuration} config
 * @param {String} variableName
 * @return {Array<JsModule>}
 */
function findImportsFromPackageJson(config, variableName) {
  const formattedVarName = formattedToRegex(variableName);

  const ignorePrefixes = config.get('ignore_package_prefixes')
    .map(prefix => escapeRegExp(prefix));

  const depRegex = RegExp(
    `^(?:${ignorePrefixes.join('|')})?${formattedVarName}$`
  );

  return config.packageDependencies()
    .filter(dep => dep.match(depRegex))
    .map(dep => (
      JsModule.construct({
        lookupPath: 'node_modules',
        relativeFilePath: `node_modules/${dep}/package.json`,
        stripFileExtensions: [],
      })
    ))
    .filter(jsModule => !!jsModule);
}

/**
 * @param {Configuration} config
 * @param {String} variableName
 * @param {String} pathToCurrentFile
 * @return {Array<JsModule>}
 */
function findImportsFromLocalFiles(config, variableName, pathToCurrentFile) {
  const formattedVarName = formattedToRegex(variableName);
  const egrepCommand =
    `egrep -i \"(/|^)${formattedVarName}(/index)?(/package)?\.js.*\"`;

  const matchedModules = [];

  config.get('lookup_paths').forEach((lookupPath) => {
    if (lookupPath === '') {
      // If lookupPath is an empty string, the `find` command will not work
      // as desired so we bail early.
      throw new Error(`lookup path cannot be empty (${lookupPath})`);
    }

    const findCommand = [
      `find ${lookupPath}`,
      '-name "**.js*"',
      '-not -path "./node_modules/*"',
    ].join(' ');
    const command = `${findCommand} | ${egrepCommand}`;

    // TODO switch to spawn so we can start processing the stream as it comes
    // in.
    let out = '';
    let err = '';
    try {
      out = String(childProcess.execSync(command));
    } catch (error) {
      err = String(error.stderr);
    }

    if (err !== '') {
      throw new Error(err);
    }

    out.split('\n').forEach((f) => {
      // TODO: it looks like we process empty strings here too (f === '')
      if (config.get('excludes').some(
        (globPattern) => minimatch(f, globPattern))) {
        return;
      }

      const module = JsModule.construct({
        lookupPath,
        relativeFilePath: f,
        stripFileExtensions:
          config.get('strip_file_extensions', { fromFile: f }),
        makeRelativeTo:
          config.get('use_relative_paths', { fromFile: f }) &&
          pathToCurrentFile,
        stripFromPath: config.get('strip_from_path', { fromFile: f }),
      });

      if (module) {
        matchedModules.push(module);
      }
    });
  });

  return matchedModules;
}

/**
 * @param {Configuration} config
 * @param {String} pathToCurrentFile
 * @param {String} variableName
 * @return {Array}
 */
function findJsModulesFor(config, pathToCurrentFile, variableName) {
  const aliasModule = config.resolveAlias(variableName, pathToCurrentFile);
  if (aliasModule) {
    return [aliasModule];
  }

  const namedImportsModule = config.resolveNamedExports(variableName);
  if (namedImportsModule) {
    return [namedImportsModule];
  }

  let matchedModules = [];

  matchedModules.push(
    ...findImportsFromLocalFiles(config, variableName, pathToCurrentFile)
  );
  matchedModules.push(...findEnvironmentCoreModules(config, variableName));
  matchedModules.push(...findImportsFromPackageJson(config, variableName));

  // If you have overlapping lookup paths, you might end up seeing the same
  // module to import twice. In order to dedupe these, we remove the module
  // with the longest path
  matchedModules = sortBy(matchedModules,
    (module) => module.importPath.length);
  matchedModules = uniqBy(matchedModules,
    (module) => module.filePath);
  return sortBy(matchedModules, (module) => module.displayName());
}

module.exports = findJsModulesFor;
<commit_msg>Find imports from local files last<commit_after>const childProcess = require('child_process');
const escapeRegExp = require('lodash.escaperegexp');
const minimatch = require('minimatch');
const sortBy = require('lodash.sortby');
const uniqBy = require('lodash.uniqby');

const JsModule = require('./JsModule');

/**
 * Takes a string in any of the following four formats:
 *   dash-separated
 *   snake_case
 *   camelCase
 *   PascalCase
 * and turns it into a star-separated lower case format, like so:
 *   star*separated
 *
 * @param {String} string
 * @return {String}
 */
function formattedToRegex(string) {
  // Based on
  // http://stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby

  // The pattern to match in between words. The "es" and "s" match is there
  // to catch pluralized folder names. There is a risk that this is overly
  // aggressive and will lead to trouble down the line. In that case, we can
  // consider adding a configuration option to control mapping a singular
  // variable name to a plural folder name (suggested by @lencioni in #127).
  // E.g.
  //
  // {
  //   "^mock": "./mocks/"
  // }
  const splitPattern = '(es|s)?.?';

  // Split up the string, allow pluralizing and a single (any) character
  // in between. This will make e.g. 'fooBar' match 'foos/bar', 'foo_bar',
  // and 'foobar'.
  return string
    .replace(/([a-z\d])([A-Z])/g, `$1${splitPattern}$2`) // camelCase
    .replace(/[-_]/g, splitPattern)
    .toLowerCase();
}

/**
 * @param {Configuration} config
 * @param {String} variableName
 * @return {Array<JsModule>}
 */
function findEnvironmentCoreModules(config, variableName) {
  return config.environmentCoreModules()
    .filter(dep => dep.toLowerCase() === variableName.toLowerCase())
    .map(dep => new JsModule({ importPath: dep }));
}

/**
 * @param {Configuration} config
 * @param {String} variableName
 * @return {Array<JsModule>}
 */
function findImportsFromPackageJson(config, variableName) {
  const formattedVarName = formattedToRegex(variableName);

  const ignorePrefixes = config.get('ignore_package_prefixes')
    .map(prefix => escapeRegExp(prefix));

  const depRegex = RegExp(
    `^(?:${ignorePrefixes.join('|')})?${formattedVarName}$`
  );

  return config.packageDependencies()
    .filter(dep => dep.match(depRegex))
    .map(dep => (
      JsModule.construct({
        lookupPath: 'node_modules',
        relativeFilePath: `node_modules/${dep}/package.json`,
        stripFileExtensions: [],
      })
    ))
    .filter(jsModule => !!jsModule);
}

/**
 * @param {Configuration} config
 * @param {String} variableName
 * @param {String} pathToCurrentFile
 * @return {Array<JsModule>}
 */
function findImportsFromLocalFiles(config, variableName, pathToCurrentFile) {
  const formattedVarName = formattedToRegex(variableName);
  const egrepCommand =
    `egrep -i \"(/|^)${formattedVarName}(/index)?(/package)?\.js.*\"`;

  const matchedModules = [];

  config.get('lookup_paths').forEach((lookupPath) => {
    if (lookupPath === '') {
      // If lookupPath is an empty string, the `find` command will not work
      // as desired so we bail early.
      throw new Error(`lookup path cannot be empty (${lookupPath})`);
    }

    const findCommand = [
      `find ${lookupPath}`,
      '-name "**.js*"',
      '-not -path "./node_modules/*"',
    ].join(' ');
    const command = `${findCommand} | ${egrepCommand}`;

    // TODO switch to spawn so we can start processing the stream as it comes
    // in.
    let out = '';
    let err = '';
    try {
      out = String(childProcess.execSync(command));
    } catch (error) {
      err = String(error.stderr);
    }

    if (err !== '') {
      throw new Error(err);
    }

    out.split('\n').forEach((f) => {
      // TODO: it looks like we process empty strings here too (f === '')
      if (config.get('excludes').some(
        (globPattern) => minimatch(f, globPattern))) {
        return;
      }

      const module = JsModule.construct({
        lookupPath,
        relativeFilePath: f,
        stripFileExtensions:
          config.get('strip_file_extensions', { fromFile: f }),
        makeRelativeTo:
          config.get('use_relative_paths', { fromFile: f }) &&
          pathToCurrentFile,
        stripFromPath: config.get('strip_from_path', { fromFile: f }),
      });

      if (module) {
        matchedModules.push(module);
      }
    });
  });

  return matchedModules;
}

/**
 * @param {Configuration} config
 * @param {String} pathToCurrentFile
 * @param {String} variableName
 * @return {Array}
 */
function findJsModulesFor(config, pathToCurrentFile, variableName) {
  const aliasModule = config.resolveAlias(variableName, pathToCurrentFile);
  if (aliasModule) {
    return [aliasModule];
  }

  const namedImportsModule = config.resolveNamedExports(variableName);
  if (namedImportsModule) {
    return [namedImportsModule];
  }

  let matchedModules = [];

  matchedModules.push(...findEnvironmentCoreModules(config, variableName));
  matchedModules.push(...findImportsFromPackageJson(config, variableName));
  matchedModules.push(
    ...findImportsFromLocalFiles(config, variableName, pathToCurrentFile)
  );

  // If you have overlapping lookup paths, you might end up seeing the same
  // module to import twice. In order to dedupe these, we remove the module
  // with the longest path
  matchedModules = sortBy(matchedModules,
    (module) => module.importPath.length);
  matchedModules = uniqBy(matchedModules,
    (module) => module.filePath);
  return sortBy(matchedModules, (module) => module.displayName());
}

module.exports = findJsModulesFor;
<|endoftext|>


<commit_before>/*
 * Copyright 2012, Mozilla Foundation and contributors
 *
 * 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.
 */

define(function(require, exports, module) {

/*
 * A spell-checker based on Damerau-Levenshtein distance.
 */

var INSERTION_COST = 1;
var DELETION_COST = 1;
var SWAP_COST = 1;
var SUBSTITUTION_COST = 2;
var MAX_EDIT_DISTANCE = 4;

/**
 * Compute Damerau-Levenshtein Distance
 * @see http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
 */
function damerauLevenshteinDistance(wordi, wordj) {
  var N = wordi.length;
  var M = wordj.length;

  // We only need to store three rows of our dynamic programming matrix.
  // (Without swap, it would have been two.)
  var row0 = new Array(N+1);
  var row1 = new Array(N+1);
  var row2 = new Array(N+1);
  var tmp;

  var i, j;

  // The distance between the empty string and a string of size i is the cost
  // of i insertions.
  for (i = 0; i <= N; i++) {
    row1[i] = i * INSERTION_COST;
  }

  // Row-by-row, we're computing the edit distance between substrings wordi[0..i]
  // and wordj[0..j].
  for (j = 1; j <= M; j++)
  {
    // Edit distance between wordi[0..0] and wordj[0..j] is the cost of j
    // insertions.
    row0[0] = j * INSERTION_COST;

    for (i = 1; i <= N; i++)
    {
      // Handle deletion, insertion and substitution: we can reach each cell
      // from three other cells corresponding to those three operations. We
      // want the minimum cost.
      row0[i] = Math.min(
          row0[i-1] + DELETION_COST,
          row1[i] + INSERTION_COST,
          row1[i-1] + (wordi[i-1] === wordj[j-1] ? 0 : SUBSTITUTION_COST));
      // We handle swap too, eg. distance between help and hlep should be 1. If
      // we find such a swap, there's a chance to update row0[1] to be lower.
      if (i > 1 && j > 1 && wordi[i-1] === wordj[j-2] && wordj[j-1] === wordi[i-2]) {
        row0[i] = Math.min(row0[i], row2[i-2] + SWAP_COST);
      }
    }

    tmp = row2;
    row2 = row1;
    row1 = row0;
    row0 = tmp;
  }

  return row1[N];
};

/**
 * A function that returns the correction for the specified word.
 */
exports.correct = function(word, names) {
  var distance = {};
  var sorted_candidates;

  names.forEach(function(candidate) {
    distance[candidate] = damerauLevenshteinDistance(word, candidate);
  });

  sorted_candidates = names.sort(function(worda, wordb) {
    if (distance[worda] !== distance[wordb]) {
      return distance[worda] - distance[wordb];
    } else {
      // if the score is the same, always return the first string
      // in the lexicographical order
      return worda < wordb;
    }
  });

  if (distance[sorted_candidates[0]] <= MAX_EDIT_DISTANCE) {
    return sorted_candidates[0];
  } else {
    return undefined;
  }
};

});
<commit_msg>tidy-822209: Tidy-up speller<commit_after>/*
 * Copyright 2012, Mozilla Foundation and contributors
 *
 * 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.
 */

define(function(require, exports, module) {

/*
 * A spell-checker based on Damerau-Levenshtein distance.
 */

var INSERTION_COST = 1;
var DELETION_COST = 1;
var SWAP_COST = 1;
var SUBSTITUTION_COST = 2;
var MAX_EDIT_DISTANCE = 4;

/**
 * Compute Damerau-Levenshtein Distance
 * @see http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
 */
function damerauLevenshteinDistance(wordi, wordj) {
  var wordiLen = wordi.length;
  var wordjLen = wordj.length;

  // We only need to store three rows of our dynamic programming matrix.
  // (Without swap, it would have been two.)
  var row0 = new Array(wordiLen+1);
  var row1 = new Array(wordiLen+1);
  var row2 = new Array(wordiLen+1);
  var tmp;

  var i, j;

  // The distance between the empty string and a string of size i is the cost
  // of i insertions.
  for (i = 0; i <= wordiLen; i++) {
    row1[i] = i * INSERTION_COST;
  }

  // Row-by-row, we're computing the edit distance between substrings wordi[0..i]
  // and wordj[0..j].
  for (j = 1; j <= wordjLen; j++)
  {
    // Edit distance between wordi[0..0] and wordj[0..j] is the cost of j
    // insertions.
    row0[0] = j * INSERTION_COST;

    for (i = 1; i <= wordiLen; i++) {
      // Handle deletion, insertion and substitution: we can reach each cell
      // from three other cells corresponding to those three operations. We
      // want the minimum cost.
      row0[i] = Math.min(
          row0[i-1] + DELETION_COST,
          row1[i] + INSERTION_COST,
          row1[i-1] + (wordi[i-1] === wordj[j-1] ? 0 : SUBSTITUTION_COST));
      // We handle swap too, eg. distance between help and hlep should be 1. If
      // we find such a swap, there's a chance to update row0[1] to be lower.
      if (i > 1 && j > 1 && wordi[i-1] === wordj[j-2] && wordj[j-1] === wordi[i-2]) {
        row0[i] = Math.min(row0[i], row2[i-2] + SWAP_COST);
      }
    }

    tmp = row2;
    row2 = row1;
    row1 = row0;
    row0 = tmp;
  }

  return row1[wordiLen];
};

/**
 * A function that returns the correction for the specified word.
 */
exports.correct = function(word, names) {
  if (names.length === 0) {
    return undefined;
  }

  var distance = {};
  var sortedCandidates;

  names.forEach(function(candidate) {
    distance[candidate] = damerauLevenshteinDistance(word, candidate);
  });

  sortedCandidates = names.sort(function(worda, wordb) {
    if (distance[worda] !== distance[wordb]) {
      return distance[worda] - distance[wordb];
    }
    else {
      // if the score is the same, always return the first string
      // in the lexicographical order
      return worda < wordb;
    }
  });

  if (distance[sortedCandidates[0]] <= MAX_EDIT_DISTANCE) {
    return sortedCandidates[0];
  }
  else {
    return undefined;
  }
};

});
<|endoftext|>


<commit_before>var assert = require('assert');
var path = require('path');
var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var _ = require('underscore');
var gutil = require('gulp-util');
var json2css = require('json2css');
var spritesmith = require('spritesmith');
var url = require('url2');
var fs = require('fs');

function ExtFormat() {
  this.formatObj = {};
}
ExtFormat.prototype = {
  'add': function (name, val) {
    this.formatObj[name] = val;
  },
  'get': function (filepath) {
    // Grab the extension from the filepath
    var ext = path.extname(filepath),
        lowerExt = ext.toLowerCase();

    // Look up the file extenion from our format object
    var formatObj = this.formatObj,
        format = formatObj[lowerExt];
    return format;
  }
};

// Create img and css formats
var imgFormats = new ExtFormat();
var cssFormats = new ExtFormat();

// Add our img formats
imgFormats.add('.png', 'png');
imgFormats.add('.jpg', 'jpeg');
imgFormats.add('.jpeg', 'jpeg');

// Add our css formats
cssFormats.add('.styl', 'stylus');
cssFormats.add('.stylus', 'stylus');
cssFormats.add('.sass', 'sass');
cssFormats.add('.scss', 'scss');
cssFormats.add('.less', 'less');
cssFormats.add('.json', 'json');
cssFormats.add('.css', 'css');

// Create a gulp-spritesmith function
function gulpSpritesmith(params) {
  var imgName = params.imgName;
  var cssName = params.cssName;
  assert(imgName, 'An `imgName` parameter was not provided to `gulp.spritesmith` (required)');
  assert(cssName, 'A `cssName` parameter was not provided to `gulp.spritesmith` (required)');

  // Create a stream to take in images
  var images = [];
  var spriteData = new Writable({objectMode: true});
  spriteData._write = function (file, encoding, cb) {
    var filepath = file.path;
    if (filepath) {
      images.push(filepath);
    }
    cb();
  };

  // Define our output streams
  spriteData.img = new Readable({objectMode: true});
  spriteData.img._read = function imgRead () {
    // Do nothing, let the `finish` handler take care of this
  };
  spriteData.css = new Readable({objectMode: true});
  spriteData.css._read = function cssRead () {
    // Do nothing, let the `finish` handler take care of this
  };

  // When we have completed our input
  spriteData.on('finish', function createSprite () {
    // Determine the format of the image
    var imgOpts = params.imgOpts || {};
    var imgFormat = imgOpts.format || imgFormats.get(imgName) || 'png';

    // Set up the defautls for imgOpts
    imgOpts = _.defaults({}, imgOpts, {'format': imgFormat});

    // Run through spritesmith
    var spritesmithParams = {
      'src': images,
      'engine': params.engine || 'auto',
      'algorithm': params.algorithm || 'top-down',
      'padding': params.padding || 0,
      'engineOpts': params.engineOpts || {},
      'exportOpts': imgOpts
    };
    spritesmith(spritesmithParams, function (err, result) {
      // If an error occurred, emit it
      if (err) {
        return spriteData.emit('error', err);
      }

      // Otherwise, write out the image
      spriteData.img.push(new gutil.File({
        path: imgName,
        contents: new Buffer(result.image, 'binary')
      }));
      spriteData.img.push(null);

      // START OF BARELY MODIFIED SECTION FROM grunt-spritesmith@1.22.0
      // Generate a listing of CSS variables
      var coordinates = result.coordinates;
      var properties = result.properties;
      var spritePath = params.imgPath || url.relative(cssName, imgName);
      var cssVarMap = params.cssVarMap || function noop () {};
      var cleanCoords = [];

      // Clean up the file name of the file
      Object.getOwnPropertyNames(coordinates).sort().forEach(function (file) {
        // Extract the image name (exlcuding extension)
        var fullname = path.basename(file);
        var nameParts = fullname.split('.');

        // If there is are more than 2 parts, pop the last one
        if (nameParts.length >= 2) {
          nameParts.pop();
        }

        // Extract out our name
        var name = nameParts.join('.');
        var coords = coordinates[file];

        // Specify the image for the sprite
        coords.name = name;
        coords.source_image = file;
        coords.image = spritePath;
        coords.total_width = properties.width;
        coords.total_height = properties.height;

        // Map the coordinates through cssVarMap
        coords = cssVarMap(coords) || coords;

        // Save the cleaned name and coordinates
        cleanCoords.push(coords);
      });

      // Render the variables via json2css
      var cssFormat = params.cssFormat || cssFormats.get(cssName) || 'json';
      var cssTemplate = params.cssTemplate;

      // If there's a custom template, use it
      if (cssTemplate) {
        if (typeof cssTemplate === 'function') {
          json2css.addTemplate(cssFormat, cssTemplate);
        } else {
          json2css.addMustacheTemplate(cssFormat, fs.readFileSync(cssTemplate, 'utf8'));
        }
      }

      var cssStr = json2css(cleanCoords, {'format': cssFormat, 'formatOpts': params.cssOpts || {}});
      // END OF BARELY MODIFIED SECTION FROM grunt-spritesmith@1.22.0

      // Output the CSS
      spriteData.css.push(new gutil.File({
        path: cssName,
        contents: new Buffer(cssStr)
      }));
      spriteData.css.push(null);
    });
  });

  // Return out input stream with 2 outputs
  return spriteData;
}

module.exports = gulpSpritesmith;<commit_msg>Change template name when custom template is used<commit_after>var assert = require('assert');
var path = require('path');
var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var _ = require('underscore');
var gutil = require('gulp-util');
var json2css = require('json2css');
var spritesmith = require('spritesmith');
var url = require('url2');
var fs = require('fs');

function ExtFormat() {
  this.formatObj = {};
}
ExtFormat.prototype = {
  'add': function (name, val) {
    this.formatObj[name] = val;
  },
  'get': function (filepath) {
    // Grab the extension from the filepath
    var ext = path.extname(filepath),
        lowerExt = ext.toLowerCase();

    // Look up the file extenion from our format object
    var formatObj = this.formatObj,
        format = formatObj[lowerExt];
    return format;
  }
};

// Create img and css formats
var imgFormats = new ExtFormat();
var cssFormats = new ExtFormat();

// Add our img formats
imgFormats.add('.png', 'png');
imgFormats.add('.jpg', 'jpeg');
imgFormats.add('.jpeg', 'jpeg');

// Add our css formats
cssFormats.add('.styl', 'stylus');
cssFormats.add('.stylus', 'stylus');
cssFormats.add('.sass', 'sass');
cssFormats.add('.scss', 'scss');
cssFormats.add('.less', 'less');
cssFormats.add('.json', 'json');
cssFormats.add('.css', 'css');

// Create a gulp-spritesmith function
function gulpSpritesmith(params) {
  var imgName = params.imgName;
  var cssName = params.cssName;
  assert(imgName, 'An `imgName` parameter was not provided to `gulp.spritesmith` (required)');
  assert(cssName, 'A `cssName` parameter was not provided to `gulp.spritesmith` (required)');

  // Create a stream to take in images
  var images = [];
  var spriteData = new Writable({objectMode: true});
  spriteData._write = function (file, encoding, cb) {
    var filepath = file.path;
    if (filepath) {
      images.push(filepath);
    }
    cb();
  };

  // Define our output streams
  spriteData.img = new Readable({objectMode: true});
  spriteData.img._read = function imgRead () {
    // Do nothing, let the `finish` handler take care of this
  };
  spriteData.css = new Readable({objectMode: true});
  spriteData.css._read = function cssRead () {
    // Do nothing, let the `finish` handler take care of this
  };

  // When we have completed our input
  spriteData.on('finish', function createSprite () {
    // Determine the format of the image
    var imgOpts = params.imgOpts || {};
    var imgFormat = imgOpts.format || imgFormats.get(imgName) || 'png';

    // Set up the defautls for imgOpts
    imgOpts = _.defaults({}, imgOpts, {'format': imgFormat});

    // Run through spritesmith
    var spritesmithParams = {
      'src': images,
      'engine': params.engine || 'auto',
      'algorithm': params.algorithm || 'top-down',
      'padding': params.padding || 0,
      'engineOpts': params.engineOpts || {},
      'exportOpts': imgOpts
    };
    spritesmith(spritesmithParams, function (err, result) {
      // If an error occurred, emit it
      if (err) {
        return spriteData.emit('error', err);
      }

      // Otherwise, write out the image
      spriteData.img.push(new gutil.File({
        path: imgName,
        contents: new Buffer(result.image, 'binary')
      }));
      spriteData.img.push(null);

      // START OF BARELY MODIFIED SECTION FROM grunt-spritesmith@1.22.0
      // Generate a listing of CSS variables
      var coordinates = result.coordinates;
      var properties = result.properties;
      var spritePath = params.imgPath || url.relative(cssName, imgName);
      var cssVarMap = params.cssVarMap || function noop () {};
      var cleanCoords = [];

      // Clean up the file name of the file
      Object.getOwnPropertyNames(coordinates).sort().forEach(function (file) {
        // Extract the image name (exlcuding extension)
        var fullname = path.basename(file);
        var nameParts = fullname.split('.');

        // If there is are more than 2 parts, pop the last one
        if (nameParts.length >= 2) {
          nameParts.pop();
        }

        // Extract out our name
        var name = nameParts.join('.');
        var coords = coordinates[file];

        // Specify the image for the sprite
        coords.name = name;
        coords.source_image = file;
        coords.image = spritePath;
        coords.total_width = properties.width;
        coords.total_height = properties.height;

        // Map the coordinates through cssVarMap
        coords = cssVarMap(coords) || coords;

        // Save the cleaned name and coordinates
        cleanCoords.push(coords);
      });

      // Render the variables via json2css
      var cssFormat = params.cssFormat || cssFormats.get(cssName) || 'json';
      var cssTemplate = params.cssTemplate;

      // If there's a custom template, use it
      if (cssTemplate) {
        cssFormat = 'spritesmith-custom';
        if (typeof cssTemplate === 'function') {
          json2css.addTemplate(cssFormat, cssTemplate);
        } else {
          json2css.addMustacheTemplate(cssFormat, fs.readFileSync(cssTemplate, 'utf8'));
        }
      }

      var cssStr = json2css(cleanCoords, {'format': cssFormat, 'formatOpts': params.cssOpts || {}});
      // END OF BARELY MODIFIED SECTION FROM grunt-spritesmith@1.22.0

      // Output the CSS
      spriteData.css.push(new gutil.File({
        path: cssName,
        contents: new Buffer(cssStr)
      }));
      spriteData.css.push(null);
    });
  });

  // Return out input stream with 2 outputs
  return spriteData;
}

module.exports = gulpSpritesmith;<|endoftext|>


<commit_before>'use strict'

var write = require('../write')

function PubAck (packet) {
  this.cmd = 'puback'
  this.messageId = packet.messageId
}

function PubRec (packet) {
  this.cmd = 'pubrec'
  this.messageId = packet.messageId
}

var publishActions = [
  authorizePublish,
  enqueuePublish
]
function handlePublish (client, packet, done) {
  var topic = packet.topic
  var err
  for (var i = 0; i < topic.length; i++) {
    switch (topic.charCodeAt(i)) {
      case 35:
        err = new Error('# is not allowed in PUBLISH')
        return done(err)
      case 43:
        err = new Error('+ is not allowed in PUBLISH')
        return done(err)
    }
  }
  client.broker._series(client, publishActions, packet, done)
}

function enqueuePublish (packet, done) {
  var client = this

  switch (packet.qos) {
    case 2:
      write(client, new PubRec(packet))
      client.broker.persistence.incomingStorePacket(client, packet, done)
      break
    case 1:
      write(client, new PubAck(packet))
      client.broker.publish(packet, client, done)
      break
    case 0:
      client.broker.publish(packet, client, done)
      break
    default:
      // nothing to do
  }
}

function authorizePublish (packet, done) {
  this.broker.authorizePublish(this, packet, done)
}

module.exports = handlePublish
<commit_msg>Error on PUBLISH with empty topic<commit_after>'use strict'

var write = require('../write')

function PubAck (packet) {
  this.cmd = 'puback'
  this.messageId = packet.messageId
}

function PubRec (packet) {
  this.cmd = 'pubrec'
  this.messageId = packet.messageId
}

var publishActions = [
  authorizePublish,
  enqueuePublish
]
function handlePublish (client, packet, done) {
  var topic = packet.topic
  var err
  if (topic.length === 0) {
    err = new Error('empty topic not allowed in PUBLISH')
    return done(err)
  }
  for (var i = 0; i < topic.length; i++) {
    switch (topic.charCodeAt(i)) {
      case 35:
        err = new Error('# is not allowed in PUBLISH')
        return done(err)
      case 43:
        err = new Error('+ is not allowed in PUBLISH')
        return done(err)
    }
  }
  client.broker._series(client, publishActions, packet, done)
}

function enqueuePublish (packet, done) {
  var client = this

  switch (packet.qos) {
    case 2:
      write(client, new PubRec(packet))
      client.broker.persistence.incomingStorePacket(client, packet, done)
      break
    case 1:
      write(client, new PubAck(packet))
      client.broker.publish(packet, client, done)
      break
    case 0:
      client.broker.publish(packet, client, done)
      break
    default:
      // nothing to do
  }
}

function authorizePublish (packet, done) {
  this.broker.authorizePublish(this, packet, done)
}

module.exports = handlePublish
<|endoftext|>


<commit_before>let _ = require('lodash');
let PouchDB = require('pouchdb');

module.exports = (db, search, config) => {
  db.paginate = (viewName, start, length, options) => {
    start = parseInt(start) || 0;
    length = parseInt(length) || 0;

    if (!options) options = {};

    var objs = [];
    var pagination = {
      previous: start - length,
      start: start + 1,
      end: null,
      length: length,
      next: null
    };
    if (pagination.previous < 0) {
      if (start <= 0)
        pagination.previous = null;
      else
        pagination.previous = 0;
    }

    if (typeof(options.include_docs) === 'undefined')
      options.include_docs = true;
    options = _.extend(options, {
      skip: start,
      limit: length + 1,
    });

    return db.query(viewName, options).then((_result) => {
      if (_result && _result.rows) {
        objs = _result.rows;
        if (objs.length > length) {
          objs.splice(length, objs.length - length);
          pagination.next = start + length;
        }
        objs = objs.map(row => options.include_docs ? row.doc :  row.value);
        pagination.end = start + objs.length;
      }

      return {
        list: objs,
        pagination: pagination
      };
    });
  };

  if (search) {
    search.paginate = async (searchTerm, type, start, length, sort) => {
      start = parseInt(start) || 0;
      length = parseInt(length) || 0;

      if (!sort) {
        sort = {
          column: '_score',
          desc: true
        }
      }

      let opts = {
        index: config.search.index,
        type: type,
        q: searchTerm.indexOf(':') >= 0 ? searchTerm : `_all:${searchTerm}`,
        from: start,
        size: length,
        sort: `${type}.${sort.column}:${sort.desc ? 'desc' : 'asc'}`
      };
      let results = await search.search(opts);

      let p = {
        list: results.hits.hits.map(v => {
          v._source[type]._id = v._id;
          return v._source[type];
        }),
        pagination: {
          previous: start - length,
          start: start + 1,
          end: start + results.hits.hits.length,
          length: length,
          next: (results.hits.total > start + length) ? start + length : null
        }
      };
      if (p.pagination.previous < 0) {
        if (start <= 0)
          p.pagination.previous = null;
        else
          p.pagination.previous = 0;
      }
      return p;
    }
  }
};<commit_msg>Add type wrapping to search.paginate searchterm<commit_after>let _ = require('lodash');
let PouchDB = require('pouchdb');

module.exports = (db, search, config) => {
  db.paginate = (viewName, start, length, options) => {
    start = parseInt(start) || 0;
    length = parseInt(length) || 0;

    if (!options) options = {};

    var objs = [];
    var pagination = {
      previous: start - length,
      start: start + 1,
      end: null,
      length: length,
      next: null
    };
    if (pagination.previous < 0) {
      if (start <= 0)
        pagination.previous = null;
      else
        pagination.previous = 0;
    }

    if (typeof(options.include_docs) === 'undefined')
      options.include_docs = true;
    options = _.extend(options, {
      skip: start,
      limit: length + 1,
    });

    return db.query(viewName, options).then((_result) => {
      if (_result && _result.rows) {
        objs = _result.rows;
        if (objs.length > length) {
          objs.splice(length, objs.length - length);
          pagination.next = start + length;
        }
        objs = objs.map(row => options.include_docs ? row.doc :  row.value);
        pagination.end = start + objs.length;
      }

      return {
        list: objs,
        pagination: pagination
      };
    });
  };

  if (search) {
    search.paginate = async (searchTerm, type, start, length, sort) => {
      start = parseInt(start) || 0;
      length = parseInt(length) || 0;

      if (!sort) {
        sort = {
          column: '_score',
          desc: true
        }
      }

      let opts = {
        index: config.search.index,
        type: type,
        q: searchTerm.indexOf(':') >= 0 ? `${type}.${searchTerm}` : `_all:${searchTerm}`,
        from: start,
        size: length,
        sort: `${type}.${sort.column}:${sort.desc ? 'desc' : 'asc'}`
      };
      let results = await search.search(opts);

      let p = {
        list: results.hits.hits.map(v => {
          v._source[type]._id = v._id;
          return v._source[type];
        }),
        pagination: {
          previous: start - length,
          start: start + 1,
          end: start + results.hits.hits.length,
          length: length,
          next: (results.hits.total > start + length) ? start + length : null
        }
      };
      if (p.pagination.previous < 0) {
        if (start <= 0)
          p.pagination.previous = null;
        else
          p.pagination.previous = 0;
      }
      return p;
    }
  }
};<|endoftext|>


<commit_before>/*
 *  This file is part of Rennspur.
 *
 *  Copyright (C) 2016  burghard.britzke, bubi@charmides.in-berlin.de
 *
 *  Rennspur is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Rennspur is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Clear all saved Locations from the localstorage
 * only called after successfully sending them to the server
 */
function clearLocalStorage(){
	/** clear status array in json */
}

/**
 * Sends all positions from the localstorage to the server
 */
function sendLocations(){
	/** Use POST to send the positions as json string to server */
}

/**
 * Prepare the localStorage to save positions and the key
 */
function prepareLocalStorage(){
	//TODO: Insert key from HTML into json string
	var json = '{"key":"","status" : []}';
	localStorage.setItem("rennspur_gps_locations", json);
}

/**
 * Initialize data on localstorage.
 * Should be called once before calling other functions
 */
function init() {
	/** check if localStorage is empty */
	var storageItem = localStorage.getItem("rennspur_gps_locations");
	if (storageItem == null) {
		/** nothing found, creating new */
		prepareLocalStorage();
	} else {
		/** if existing check if saved Data is the correct JSON-Format */
		var storageItemJson = JSON.parse(storageItem);
		if(storageItemJson.status == null || storageItemJson.key == null){
			/** status array or auth key in JSON object is missing, creating new */
			prepareLocalStorage();
		}
		//TODO: check if the found data is old, maybe from another event?
		/** everything is fine, keeping old localStorage */

	}
}

/**
 * Saves the location into the localstorage with the current system-time
 *
 * @param {number} lo [lo = 51.3256] - longitude of the location
 * @param {number} la [la = 40.9034] - latitude of the location
 */
function saveLocation(lo, la) {
	/** Get the time of the function call */
	var time = Date.now();

	/** Save positions and time as json */
	var positionJson = JSON.parse(JSON.stringify({
		"long" : lo,
		"lat" : la,
		"time" : time
	}));

	/** Get existing array of positions from the localstorage */
	var locationJsonString = localStorage.getItem("rennspur_gps_locations");

	/** Turn them into a JSON object */
	var locactionJson = JSON.parse(locationJsonString);

	/** Add the saved position into the array */
	locactionJson.status.push(positionJson);

	/** Save the JSON object back into the localstorage as string */
	localStorage.setItem("rennspur_gps_locations", JSON.stringify(locactionJson));
}

/**
 * To test , call init at start and then save a test-location
 */
window.onload = function() {
	init();
	saveLocation(10, 20);
}<commit_msg>Formatted and added some functionalities to JS.<commit_after>/*
 *  This file is part of Rennspur.
 *
 *  Copyright (C) 2016  burghard.britzke, bubi@charmides.in-berlin.de
 *
 *  Rennspur is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Rennspur is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Clear all saved Locations from the localstorage only called after
 * successfully sending them to the server
 */
function clearStatusArray() {
	/** Get the status array out of the localstorage */
	var jsonString = localStorage.getItem("rennspur_gps_locations");
	var jsonObject = JSON.parse(jsonString);

	/** clear the array by initializing it as a new, empty array */
	jsonObject.status.length = [];

	/** put the JSON object back into the localStorage */
	jsonString = JSON.stringify(jsonObject);
	localStorage.setItem("rennspur_gps_locations", jsonString);
}

/**
 * Sends all positions from the localstorage to the server
 * Example how making a POST request might be done
 */
function sendLocations() {
	/** create XMLHttpRequest object, set the URL to the Member-GPS API */
	var request = new XMLHttpRequest();
	var url = "https://???.??/API/mGPS";

	/** insert the JSON string into the post attribute "json" */
	var params = "json=" + localStorage.getItem("rennspur_gps_locations");
	request.open("POST", url, true);

	/** set content type */
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	/** create anonymous callback to handle the answer of the server */
	request.onreadystatechange = function() {
		if (request.readyState == 4 && request.status == 200) {
			alert(request.responseText);
		}
	}

	/** finally send POST request */
	request.send(params);
}

/**
 * Prepare the localStorage to save positions and the key
 */
function prepareLocalStorage() {
	// TODO: Insert key from HTML into json string
	var json = '{"key":"","status" : []}';
	localStorage.setItem("rennspur_gps_locations", json);
}

/**
 * Initialize data on localstorage. Should be called once before calling other
 * functions
 */
function init() {
	/** check if localStorage is empty */
	var storageItem = localStorage.getItem("rennspur_gps_locations");
	if (storageItem == null) {
		/** nothing found, creating new */
		prepareLocalStorage();
	} else {
		/** if existing check if saved Data is the correct JSON-Format */
		var storageItemJson = JSON.parse(storageItem);
		if (storageItemJson.status == null || storageItemJson.key == null) {
			/** status array or auth key in JSON object is missing, creating new */
			prepareLocalStorage();
		}
		// TODO: check if the found data is old, maybe from another event?
	}
}

/**
 * Saves the location into the localstorage with the current system-time
 *
 * @param {number}
 *            lo [lo = 51.3256] - longitude of the location
 * @param {number}
 *            la [la = 40.9034] - latitude of the location
 */
function saveLocation(lo, la) {
	/** Get the time of the function call */
	var time = Date.now();

	/** Save positions and time as json */
	var positionJson = JSON.parse(JSON.stringify({
		"long" : lo,
		"lat" : la,
		"time" : time
	}));

	/** Get existing array of positions from the localstorage */
	var locationJsonString = localStorage.getItem("rennspur_gps_locations");

	/** Turn them into a JSON object */
	var locactionJson = JSON.parse(locationJsonString);

	/** Add the saved position into the array */
	locactionJson.status.push(positionJson);

	/** Save the JSON object back into the localstorage as string */
	localStorage.setItem("rennspur_gps_locations", JSON.stringify(locactionJson));
}

/**
 * onClick to test some functions
 */
function clickTest() {
	sendLocations(); // testing
}

/**
 * To test , call init at start and then save a test-location
 */
window.onload = function() {
	init();
	saveLocation(10, 20);
}
<|endoftext|>


<commit_before>import React from 'react';

import Analyzer from 'parser/core/Analyzer';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Abilities from 'parser/shared/modules/Abilities';
import calculateMaxCasts from 'parser/core/calculateMaxCasts';

import ExecuteRange from './ExecuteRange';

class MortalStrikeAnalyzer extends Analyzer {
  static dependencies = {
    abilities: Abilities,
    executeRange: ExecuteRange,
  };

  mortalStrikes = 0;
  mortalStrikesInExecuteRange = 0;

  constructor(...args) {
    super(...args);
    this.active = !this.selectedCombatant.hasTrait(SPELLS.EXECUTIONERS_PRECISION_TRAIT.id);
  }

  on_byPlayer_cast(event) {
    if(event.ability.guid !== SPELLS.MORTAL_STRIKE.id) {
      return;
    }

    this.mortalStrikes += 1;
    if(this.executeRange.isTargetInExecuteRange(event)) {
      this.mortalStrikesInExecuteRange += 1;

      event.meta = event.meta || {};
      event.meta.isInefficientCast = true;
      event.meta.inefficientCastReason = 'This Mortal Strike was used on a target in Execute range.';
    }
  }

  get goodMortalStrikeThresholds() {
    const cd = this.abilities.getAbility(SPELLS.MORTAL_STRIKE.id).cooldown;
    const max = calculateMaxCasts(cd, this.owner.fightDuration - this.executeRange.executionPhaseDuration());

    return {
      actual: this.mortalStrikes / max,
      isLessThan: {
        minor: 0.9,
        average: 0.8,
        major: 0.7,
      },
      style: 'percentage',
    };
  }

  get badMortalStrikeThresholds() {
    const cd = this.abilities.getAbility(SPELLS.MORTAL_STRIKE.id).cooldown;
    const max = calculateMaxCasts(cd, this.executeRange.executionPhaseDuration());

    return {
      actual: this.mortalStrikesInExecuteRange / max,
      isGreaterThan: {
        minor: 0,
        average: 0.05,
        major: 0.1,
      },
      style: 'percentage',
    };
  }

  suggestions(when) {
    when(this.badMortalStrikeThresholds).addSuggestion((suggest, actual, recommended) => {
      return suggest(<>Try to avoid using <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> on a target in <SpellLink id={SPELLS.EXECUTE.id} icon /> range if you don't have <SpellLink id={SPELLS.EXECUTIONERS_PRECISION_TRAIT.id} /> trait, as <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> is less rage efficient than <SpellLink id={SPELLS.EXECUTE.id} />.</>)
        .icon(SPELLS.MORTAL_STRIKE.icon)
        .actual(`Mortal Strike was used ${formatPercentage(actual)}% of the time on a target in execute range.`)
        .recommended(`${formatPercentage(recommended)}% is recommended`);
    });
    when(this.goodMortalStrikeThresholds).addSuggestion((suggest, actual, recommended) => {
      return suggest(<>Try to cast <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> more often when the target is outside execute range.</>)
        .icon(SPELLS.MORTAL_STRIKE.icon)
        .actual(`Mortal Strike was used ${formatPercentage(actual)}% of the time on a target outside execute range.`)
        .recommended(`${formatPercentage(recommended)}% is recommended`);
    });
  }
}

export default MortalStrikeAnalyzer;
<commit_msg>Fixed error on MS outside exec phase<commit_after>import React from 'react';

import Analyzer from 'parser/core/Analyzer';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Abilities from 'parser/shared/modules/Abilities';
import calculateMaxCasts from 'parser/core/calculateMaxCasts';

import ExecuteRange from './ExecuteRange';

class MortalStrikeAnalyzer extends Analyzer {
  static dependencies = {
    abilities: Abilities,
    executeRange: ExecuteRange,
  };

  mortalStrikesOutsideExecuteRage = 0;
  mortalStrikesInExecuteRange = 0;

  constructor(...args) {
    super(...args);
    this.active = !this.selectedCombatant.hasTrait(SPELLS.EXECUTIONERS_PRECISION_TRAIT.id);
  }

  on_byPlayer_cast(event) {
    if(event.ability.guid !== SPELLS.MORTAL_STRIKE.id) {
      return;
    }

    if(this.executeRange.isTargetInExecuteRange(event)) {
      this.mortalStrikesInExecuteRange += 1;

      event.meta = event.meta || {};
      event.meta.isInefficientCast = true;
      event.meta.inefficientCastReason = 'This Mortal Strike was used on a target in Execute range.';
    } else {
      this.mortalStrikesOutsideExecuteRage += 1;
    }
  }

  get goodMortalStrikeThresholds() {
    const cd = this.abilities.getAbility(SPELLS.MORTAL_STRIKE.id).cooldown;
    const max = calculateMaxCasts(cd, this.owner.fightDuration - this.executeRange.executionPhaseDuration());

    return {
      actual: this.mortalStrikesOutsideExecuteRage / max,
      isLessThan: {
        minor: 0.9,
        average: 0.8,
        major: 0.7,
      },
      style: 'percentage',
    };
  }

  get badMortalStrikeThresholds() {
    const cd = this.abilities.getAbility(SPELLS.MORTAL_STRIKE.id).cooldown;
    const max = calculateMaxCasts(cd, this.executeRange.executionPhaseDuration());

    return {
      actual: this.mortalStrikesInExecuteRange / max,
      isGreaterThan: {
        minor: 0,
        average: 0.05,
        major: 0.1,
      },
      style: 'percentage',
    };
  }

  suggestions(when) {
    when(this.badMortalStrikeThresholds).addSuggestion((suggest, actual, recommended) => {
      return suggest(<>Try to avoid using <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> on a target in <SpellLink id={SPELLS.EXECUTE.id} icon /> range if you don't have <SpellLink id={SPELLS.EXECUTIONERS_PRECISION_TRAIT.id} /> trait, as <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> is less rage efficient than <SpellLink id={SPELLS.EXECUTE.id} />.</>)
        .icon(SPELLS.MORTAL_STRIKE.icon)
        .actual(`Mortal Strike was used ${formatPercentage(actual)}% of the time on a target in execute range.`)
        .recommended(`${formatPercentage(recommended)}% is recommended`);
    });
    when(this.goodMortalStrikeThresholds).addSuggestion((suggest, actual, recommended) => {
      return suggest(<>Try to cast <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> more often when the target is outside execute range.</>)
        .icon(SPELLS.MORTAL_STRIKE.icon)
        .actual(`Mortal Strike was used ${formatPercentage(actual)}% of the time on a target outside execute range.`)
        .recommended(`${formatPercentage(recommended)}% is recommended`);
    });
  }
}

export default MortalStrikeAnalyzer;
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name requisition-non-full-supply.addProductModalService
     *
     * @description
     * It shows modal with possibility to add non-full supply line item
     * with one of given products.
     */
    angular
        .module('requisition-non-full-supply')
        .service('addProductModalService', service);

    service.$inject = [
        '$q', '$rootScope', '$compile', '$templateRequest', '$ngBootbox', 'messageService',
        '$controller', 'categoryFactory'
    ];

    function service($q, $rootScope, $compile, $templateRequest, $ngBootbox, messageService,
                     $controller, categoryFactory) {

        this.show = show;

        /**
         * @ngdoc method
         * @methodOf requisition-non-full-supply.addProductModalService
         * @name show
         *
         * @description
         * Shows modal that allows to add line item to requisition. If there are no products to be
         * added an alert will be shown.
         *
         * @param {Array} categories Facility approved categories
         * @return {Promise} resolved with line item when product is added
         */
        function show(products, programId) {
            var deferred = $q.defer(),
                scope = $rootScope.$new();

            scope.vm = $controller('AddProductModalController', {
                deferred: deferred,
                categories: categoryFactory.groupProducts(products, programId),
                programId: programId
            });

            $templateRequest('requisition-non-full-supply/add-product-modal.html')
                .then(function(template) {
                    $ngBootbox.customDialog({
                        title: messageService.get('requisitionNonFullSupply.addProduct'),
                        message: $compile(angular.element(template))(scope),
                        className: 'add-product-modal'
                    });
                });

            return deferred.promise;
        }
    }

})();
<commit_msg>Revert "OLMIS-2483: Updated JSDoc for addProductModalService"<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name requisition-non-full-supply.addProductModalService
     *
     * @description
     * It shows modal with possibility to add non-full supply line item
     * with one of given products.
     */
    angular
        .module('requisition-non-full-supply')
        .service('addProductModalService', service);

    service.$inject = [
        '$q', '$rootScope', '$compile', '$templateRequest', '$ngBootbox', 'messageService',
        '$controller', 'categoryFactory'
    ];

    function service($q, $rootScope, $compile, $templateRequest, $ngBootbox, messageService,
                     $controller, categoryFactory) {

        this.show = show;

        /**
         * @ngdoc method
         * @methodOf requisition-non-full-supply.addProductModalService
         * @name show
         *
         * @description
         * Shows modal that allows to add line item to requisition.
         *
         * @param {Array} categories Facility approved categories
         * @return {Promise} resolved with line item when product is added
         */
        function show(products, programId) {
            var deferred = $q.defer(),
                scope = $rootScope.$new();

            scope.vm = $controller('AddProductModalController', {
                deferred: deferred,
                categories: categoryFactory.groupProducts(products, programId),
                programId: programId
            });

            $templateRequest('requisition-non-full-supply/add-product-modal.html')
                .then(function(template) {
                    $ngBootbox.customDialog({
                        title: messageService.get('requisitionNonFullSupply.addProduct'),
                        message: $compile(angular.element(template))(scope),
                        className: 'add-product-modal'
                    });
                });

            return deferred.promise;
        }
    }

})();
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define([
	"./ObjectPageHeaderRenderer",
	"./ObjectImageHelper"], function (ObjectPageHeaderRenderer, ObjectImageHelper) {
	"use strict";

	/**
	 * @class HeaderContent renderer.
	 * @static
	 */
	var ObjectPageHeaderContentRenderer = {};

	ObjectPageHeaderContentRenderer.render = function (oRm, oControl) {
		var oParent = oControl.getParent(),
			bParentLayout = oParent && oParent.isA("sap.uxap.ObjectPageLayout"),
			oHeader = (oParent && bParentLayout) ? oParent.getHeaderTitle() : undefined,
			bRenderTitle = (oParent && bParentLayout) ? (oParent.isA("sap.uxap.ObjectPageLayout")
				&& oParent.getShowTitleInHeaderContent()) : false,
			bRenderEditBtn = bParentLayout && oParent.getShowEditHeaderButton() && oControl.getContent() && oControl.getContent().length > 0;

		if (bRenderEditBtn) {
			oRm.write("
");
		}
		oRm.write("<div ");
		if (bRenderEditBtn) {
			oRm.addClass("sapUxAPObjectPageHeaderContentCellLeft");
		} else {
			oRm.writeControlData(oControl);
			oRm.addClass("sapUxAPObjectPageHeaderContentDesign-" + oControl.getContentDesign());
			if (oHeader) {
				oRm.addClass('sapUxAPObjectPageContentObjectImage-' + oHeader.getObjectImageShape());
			}
		}
		oRm.addClass("ui-helper-clearfix");
		oRm.addClass("sapUxAPObjectPageHeaderContent");

		if (!oControl.getVisible()) {
			oRm.addClass("sapUxAPObjectPageHeaderContentHidden");
		}
		oRm.writeClasses();
		oRm.write(">");

		if (bParentLayout && oParent.getIsChildPage()) {
			oRm.write("

");
		}

		if (bRenderTitle) {
			this._renderTitleImage(oRm, oControl, oHeader);

			if (oControl.getContent().length == 0) {
				oRm.write("");
				this._renderTitle(oRm, oHeader);
				oRm.write("");
			}
		}

		oControl.getContent().forEach(function (oItem, iIndex) {
			this._renderHeaderContentItem(oItem, iIndex, oRm, bRenderTitle, oHeader, oControl);
		}, this);

		oRm.write("
");

		if (bRenderEditBtn) {
			this._renderEditButton(oRm, oControl);

			oRm.write("
"); // end of "sapUxAPObjectPageHeaderContentFlexBox" div
		}
	};

	/**
	 * This method is called to render the content
	 * @param {sap.ui.core.Control} oHeaderContentItem header content item
	 * @param {int} iIndex index
	 * @param {sap.ui.core.RenderManager} oRm oRm
	 * @param {boolean} bRenderTitle render title
	 * @param {sap.uxap.ObjectPageHeader} oTitle header title
	 * @param {sap.ui.core.Control} oControl control
	 */
	ObjectPageHeaderContentRenderer._renderHeaderContentItem = function (oHeaderContentItem, iIndex, oRm, bRenderTitle, oTitle, oControl) {
		var bHasSeparatorBefore = false,
			bHasSeparatorAfter = false,
			oLayoutData = oControl._getLayoutDataForControl(oHeaderContentItem),
			bIsFirstControl = iIndex === 0;

		if (oLayoutData) {
			bHasSeparatorBefore = oLayoutData.getShowSeparatorBefore();
			bHasSeparatorAfter = oLayoutData.getShowSeparatorAfter();

			oRm.write("<span ");
			oRm.addClass("sapUxAPObjectPageHeaderWidthContainer");
			oRm.addClass("sapUxAPObjectPageHeaderContentItem");
			oRm.addStyle("width", oLayoutData.getWidth());
			oRm.writeStyles();

			if (bHasSeparatorAfter || bHasSeparatorBefore) {
				oRm.addClass("sapUxAPObjectPageHeaderSeparatorContainer");
			}

			if (!oLayoutData.getVisibleL()) {
				oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenL");
			}
			if (!oLayoutData.getVisibleM()) {
				oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenM");
			}
			if (!oLayoutData.getVisibleS()) {
				oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenS");
			}

			oRm.writeClasses();
			oRm.write(">");

			if (bHasSeparatorBefore) {
				oRm.write("");
			}

			if (bIsFirstControl && bRenderTitle) { // render title inside the first contentItem
				this._renderTitle(oRm, oTitle);
			}
		} else {
			if (bIsFirstControl && bRenderTitle) { // render title inside the first contentItem
				oRm.write("");
				this._renderTitle(oRm, oTitle);
			} else {
				oHeaderContentItem.addStyleClass("sapUxAPObjectPageHeaderContentItem");
			}
		}

		oRm.renderControl(oHeaderContentItem);

		if (bHasSeparatorAfter) {
			oRm.write("");
		}

		if (oLayoutData || (bIsFirstControl && bRenderTitle)) {
			oRm.write("");
		}
	};

	/**
	 * This method is called to render title and all it's parts if the property showTitleInHeaderContent is set to true
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 * @param {sap.ui.core.Control} oHeader an object representation of the titleHeader that should be rendered
	 */
	ObjectPageHeaderContentRenderer._renderTitleImage = function (oRm, oControl, oHeader) {

		ObjectImageHelper._renderImageAndPlaceholder(oRm, {
			oHeader: oHeader,
			oObjectImage: oControl._getObjectImage(),
			oPlaceholder: oControl._getPlaceholder(),
			bIsObjectIconAlwaysVisible: false,
			bAddSubContainer: false,
			sBaseClass: 'sapUxAPObjectPageHeaderContentImageContainer'
		});
	};

	/**
	 * This method is called to render title and all it's parts if the property showTitleInHeaderContent is set to true
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oHeader an object representation of the control that should be rendered
	 */
	ObjectPageHeaderContentRenderer._renderTitle = function (oRm, oHeader) {
		ObjectPageHeaderRenderer._renderObjectPageTitle(oRm, oHeader, true); // force title to be visible inside the content header
	};

	/**
	 * This method is called to render the Edit button when the property showEditHeaderButton is set to true
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oHeader an object representation of the control that should be rendered
	 */
	ObjectPageHeaderContentRenderer._renderEditButton = function (oRm, oHeader) {
		oRm.write("
");
		oRm.renderControl(oHeader.getAggregation("_editHeaderButton"));
		oRm.write("
");
	};

	return ObjectPageHeaderContentRenderer;

}, /* bExport= */ true);
<commit_msg>[FIX] uxap.ObjectPageHeaderContent: belize_deep appearance corrected<commit_after>/*!
 * ${copyright}
 */

sap.ui.define([
	"./ObjectPageHeaderRenderer",
	"./ObjectImageHelper"], function (ObjectPageHeaderRenderer, ObjectImageHelper) {
	"use strict";

	/**
	 * @class HeaderContent renderer.
	 * @static
	 */
	var ObjectPageHeaderContentRenderer = {};

	ObjectPageHeaderContentRenderer.render = function (oRm, oControl) {
		var oParent = oControl.getParent(),
			bParentLayout = oParent && oParent.isA("sap.uxap.ObjectPageLayout"),
			oHeader = (oParent && bParentLayout) ? oParent.getHeaderTitle() : undefined,
			bRenderTitle = (oParent && bParentLayout) ? (oParent.isA("sap.uxap.ObjectPageLayout")
				&& oParent.getShowTitleInHeaderContent()) : false,
			bRenderEditBtn = bParentLayout && oParent.getShowEditHeaderButton() && oControl.getContent() && oControl.getContent().length > 0;

		if (bRenderEditBtn) {
			oRm.write("
");
		}
		oRm.write("<div ");
		if (bRenderEditBtn) {
			oRm.addClass("sapUxAPObjectPageHeaderContentCellLeft");
		} else {
			oRm.writeControlData(oControl);
			oRm.addClass("sapUxAPObjectPageHeaderContentDesign-" + oControl.getContentDesign());
			if (oHeader) {
				oRm.addClass('sapUxAPObjectPageContentObjectImage-' + oHeader.getObjectImageShape());
			}
		}
		oRm.addClass("sapContrastPlus");
		oRm.addClass("ui-helper-clearfix");
		oRm.addClass("sapUxAPObjectPageHeaderContent");

		if (!oControl.getVisible()) {
			oRm.addClass("sapUxAPObjectPageHeaderContentHidden");
		}
		oRm.writeClasses();
		oRm.write(">");

		if (bParentLayout && oParent.getIsChildPage()) {
			oRm.write("

");
		}

		if (bRenderTitle) {
			this._renderTitleImage(oRm, oControl, oHeader);

			if (oControl.getContent().length == 0) {
				oRm.write("");
				this._renderTitle(oRm, oHeader);
				oRm.write("");
			}
		}

		oControl.getContent().forEach(function (oItem, iIndex) {
			this._renderHeaderContentItem(oItem, iIndex, oRm, bRenderTitle, oHeader, oControl);
		}, this);

		oRm.write("
");

		if (bRenderEditBtn) {
			this._renderEditButton(oRm, oControl);

			oRm.write("
"); // end of "sapUxAPObjectPageHeaderContentFlexBox" div
		}
	};

	/**
	 * This method is called to render the content
	 * @param {sap.ui.core.Control} oHeaderContentItem header content item
	 * @param {int} iIndex index
	 * @param {sap.ui.core.RenderManager} oRm oRm
	 * @param {boolean} bRenderTitle render title
	 * @param {sap.uxap.ObjectPageHeader} oTitle header title
	 * @param {sap.ui.core.Control} oControl control
	 */
	ObjectPageHeaderContentRenderer._renderHeaderContentItem = function (oHeaderContentItem, iIndex, oRm, bRenderTitle, oTitle, oControl) {
		var bHasSeparatorBefore = false,
			bHasSeparatorAfter = false,
			oLayoutData = oControl._getLayoutDataForControl(oHeaderContentItem),
			bIsFirstControl = iIndex === 0;

		if (oLayoutData) {
			bHasSeparatorBefore = oLayoutData.getShowSeparatorBefore();
			bHasSeparatorAfter = oLayoutData.getShowSeparatorAfter();

			oRm.write("<span ");
			oRm.addClass("sapUxAPObjectPageHeaderWidthContainer");
			oRm.addClass("sapUxAPObjectPageHeaderContentItem");
			oRm.addStyle("width", oLayoutData.getWidth());
			oRm.writeStyles();

			if (bHasSeparatorAfter || bHasSeparatorBefore) {
				oRm.addClass("sapUxAPObjectPageHeaderSeparatorContainer");
			}

			if (!oLayoutData.getVisibleL()) {
				oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenL");
			}
			if (!oLayoutData.getVisibleM()) {
				oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenM");
			}
			if (!oLayoutData.getVisibleS()) {
				oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenS");
			}

			oRm.writeClasses();
			oRm.write(">");

			if (bHasSeparatorBefore) {
				oRm.write("");
			}

			if (bIsFirstControl && bRenderTitle) { // render title inside the first contentItem
				this._renderTitle(oRm, oTitle);
			}
		} else {
			if (bIsFirstControl && bRenderTitle) { // render title inside the first contentItem
				oRm.write("");
				this._renderTitle(oRm, oTitle);
			} else {
				oHeaderContentItem.addStyleClass("sapUxAPObjectPageHeaderContentItem");
			}
		}

		oRm.renderControl(oHeaderContentItem);

		if (bHasSeparatorAfter) {
			oRm.write("");
		}

		if (oLayoutData || (bIsFirstControl && bRenderTitle)) {
			oRm.write("");
		}
	};

	/**
	 * This method is called to render title and all it's parts if the property showTitleInHeaderContent is set to true
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 * @param {sap.ui.core.Control} oHeader an object representation of the titleHeader that should be rendered
	 */
	ObjectPageHeaderContentRenderer._renderTitleImage = function (oRm, oControl, oHeader) {

		ObjectImageHelper._renderImageAndPlaceholder(oRm, {
			oHeader: oHeader,
			oObjectImage: oControl._getObjectImage(),
			oPlaceholder: oControl._getPlaceholder(),
			bIsObjectIconAlwaysVisible: false,
			bAddSubContainer: false,
			sBaseClass: 'sapUxAPObjectPageHeaderContentImageContainer'
		});
	};

	/**
	 * This method is called to render title and all it's parts if the property showTitleInHeaderContent is set to true
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oHeader an object representation of the control that should be rendered
	 */
	ObjectPageHeaderContentRenderer._renderTitle = function (oRm, oHeader) {
		ObjectPageHeaderRenderer._renderObjectPageTitle(oRm, oHeader, true); // force title to be visible inside the content header
	};

	/**
	 * This method is called to render the Edit button when the property showEditHeaderButton is set to true
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oHeader an object representation of the control that should be rendered
	 */
	ObjectPageHeaderContentRenderer._renderEditButton = function (oRm, oHeader) {
		oRm.write("
");
		oRm.renderControl(oHeader.getAggregation("_editHeaderButton"));
		oRm.write("
");
	};

	return ObjectPageHeaderContentRenderer;

}, /* bExport= */ true);
<|endoftext|>


<commit_before>import futureRoutes from 'app/routes.json!';
import 'ui-router-extras';

export var routing = function(module){

  module.requires.push('ct.ui.router.extras.future');

  var $inject = ['$stateProvider', '$futureStateProvider'];
  var RouterConfig = function ($stateProvider, $futureStateProvider) {

    $futureStateProvider.stateFactory('load', function($q, $ocLazyLoad, futureState){
      var def = $q.defer();

      System.import(futureState.src).then(loaded => {
        var newModule = loaded;
        if (!loaded.name) {
          var key = Object.keys(loaded);
          newModule = loaded[key[0]];
        }

        $ocLazyLoad.load(newModule).then(function() {
          def.resolve();
        });
      });

      return def.promise;
    });

    futureRoutes.forEach(function(r){
      $futureStateProvider.futureState(r);
    });
  };

  RouterConfig.$inject = $inject;

  return RouterConfig;
};
<commit_msg>mangled minification doesn't work because of ngAnnotate failing to recognize this injection<commit_after>import futureRoutes from 'app/routes.json!';
import 'ui-router-extras';

export var routing = function(module) {

  module.requires.push('ct.ui.router.extras.future');

  var RouterConfig = function ($stateProvider, $futureStateProvider) {

    $futureStateProvider.stateFactory('load', ['$q', '$ocLazyLoad', 'futureState', function($q, $ocLazyLoad, futureState) {
      var def = $q.defer();

      System.import(futureState.src).then(loaded => {
        var newModule = loaded;
        if (!loaded.name) {
          var key = Object.keys(loaded);
          newModule = loaded[key[0]];
        }

        $ocLazyLoad.load(newModule).then(function() {
          def.resolve();
        });
      });

      return def.promise;
    }]);

    futureRoutes.forEach(function(r) {
      $futureStateProvider.futureState(r);
    });

  };

  RouterConfig.$inject = ['$stateProvider', '$futureStateProvider'];

  return RouterConfig;
};
<|endoftext|>