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

module.exports = function (options) {
  var opts = options ? options : {};
  var paths = opts.paths || [];

  function stylusstream (file, cb) {
    // file is on object passed in by gulp
    // TODO: support streaming files

    var s = stylus(file.contents.toString('utf8'));
    s.set('filename', file.path);
    s.set('paths', paths.concat([path.dirname(file.path)]));

    //trying to load extensions from array passed by user
    if (options.use && options.use.length > 0){
      s.use(function(stylus){
        for (var i = 0, l = options.use.length; i < l; i++){
          try{
            stylus.use(require(options.use[i])());
          }
          catch(e){}
        }
      });
    }

    s.render(function(err, css){
      if (err) return cb(err);

      file.path = gutil.replaceExtension(file.path, '.css');
      file.contents = new Buffer(css);

      cb(null, file);
    });
  }

  return es.map(stylusstream);
};
<commit_msg>add check on options existence<commit_after>var es = require('event-stream');
var stylus = require('stylus');
var gutil = require('gulp-util');
var path = require('path');

module.exports = function (options) {
  var opts = options ? options : {};
  var paths = opts.paths || [];

  function stylusstream (file, cb) {
    // file is on object passed in by gulp
    // TODO: support streaming files

    var s = stylus(file.contents.toString('utf8'));
    s.set('filename', file.path);
    s.set('paths', paths.concat([path.dirname(file.path)]));

    //trying to load extensions from array passed by user
    if (options && options.use && options.use.length > 0){
      s.use(function(stylus){
        for (var i = 0, l = options.use.length; i < l; i++){
          try{
            stylus.use(require(options.use[i])());
          }
          catch(e){}
        }
      });
    }

    s.render(function(err, css){
      if (err) return cb(err);

      file.path = gutil.replaceExtension(file.path, '.css');
      file.contents = new Buffer(css);

      cb(null, file);
    });
  }

  return es.map(stylusstream);
};
<|endoftext|>


<commit_before>'use strict';

var ap = require('ap');
var d = require('themeleon/decorators');
var fs = require('fs');
var path = require('path');
var q = require('q');

var readFile = q.denodeify(fs.readFile);
var glob = q.denodeify(require('glob'));

/**
 * Given partials are in the following format:
 *
 *     {
 *       name: 'path/to/partial.mustache',
 *       ...
 *     }
 *
 * The promise will resolve to the following:
 *
 *     {
 *       name: 'template file content',
 *       ...
 *     }
 *
 * The template files are relative to `src` directory.
 *
 * @param {String} src
 * @param {Object} partials
 * @return {Promise}
 */
function readPartialsObject(src, partials) {
  var promises = [];

  for (var name in partials) {
    var file = path.resolve(src, partials[name]);
    var promise = q.all([q(name), readFile(file, 'utf8')]);
    promises.push(promise);
  }

  return q.all(promises)
    .then(function (list) {
      list.forEach(function (item) {
        var name = item[0];
        var content = item[1];

        partials[name] = content;
      });

      return partials;
    });
}

/**
 * Find all `.mustache` files from partials directory and build
 * an object, then pass it to `readPartialsObject`.
 */
function readPartialsDirectory(src, partials) {
  src = path.resolve(src);
  partials = path.resolve(src, partials);

  return glob(partials + '/**/*.mustache')
    .then(function (files) {
      var object = {};

      files.forEach(function (file) {
        // Strip partials directory
        var partial = file.substr(partials.length + 1);

        // Strip extension
        partial = partial.substr(0, partial.lastIndexOf('.'));

        object[partial] = file;
      });

      return object;
    })
    .then(function (partials) {
      return readPartialsObject(src, partials);
    });
}

/**
 * If partials is a string, it will be treated as a directory
 * with `readPartialsDirectory`, otherwise as an object with
 * `readPartialsObject`.
 *
 * @param {String} src
 * @param {String|Object} partials
 * @return {Promise}
 */
function readPartials(src, partials) {
  if (!partials) {
    return null;
  }

  if (typeof partials === 'string') {
    return readPartialsDirectory(src, partials);
  }

  return readPartialsObject(src, partials);
}

module.exports = function (mustache) {
  mustache = mustache || require('mustache');

  var writeFile = q.denodeify(fs.writeFile);

  return {
    mustache: d.srcDest(function (src, dest, partials) {
      var promise = q.all([
        readFile(src, 'utf8'),
        readPartials(this.src, partials)
      ])
        .spread(function (template, partials) {
          return mustache.render(template, this.ctx, partials);
        }.bind(this))
        .then(ap([dest], writeFile));

      this.push(promise);
    }),
  };
};
<commit_msg>Add support for `.mst` templates extension<commit_after>'use strict';

var ap = require('ap');
var d = require('themeleon/decorators');
var fs = require('fs');
var path = require('path');
var q = require('q');

var readFile = q.denodeify(fs.readFile);
var glob = q.denodeify(require('glob'));

/**
 * Given partials are in the following format:
 *
 *     {
 *       name: 'path/to/partial.mustache',
 *       ...
 *     }
 *
 * The promise will resolve to the following:
 *
 *     {
 *       name: 'template file content',
 *       ...
 *     }
 *
 * The template files are relative to `src` directory.
 *
 * @param {String} src
 * @param {Object} partials
 * @return {Promise}
 */
function readPartialsObject(src, partials) {
  var promises = [];

  for (var name in partials) {
    var file = path.resolve(src, partials[name]);
    var promise = q.all([q(name), readFile(file, 'utf8')]);
    promises.push(promise);
  }

  return q.all(promises)
    .then(function (list) {
      list.forEach(function (item) {
        var name = item[0];
        var content = item[1];

        partials[name] = content;
      });

      return partials;
    });
}

/**
 * Find all `.mustache` files from partials directory and build
 * an object, then pass it to `readPartialsObject`.
 */
function readPartialsDirectory(src, partials) {
  src = path.resolve(src);
  partials = path.resolve(src, partials);

  return glob(partials + '/**/*.+(mustache|mst)')
    .then(function (files) {
      var object = {};

      files.forEach(function (file) {
        // Strip partials directory
        var partial = file.substr(partials.length + 1);

        // Strip extension
        partial = partial.substr(0, partial.lastIndexOf('.'));

        object[partial] = file;
      });

      return object;
    })
    .then(function (partials) {
      return readPartialsObject(src, partials);
    });
}

/**
 * If partials is a string, it will be treated as a directory
 * with `readPartialsDirectory`, otherwise as an object with
 * `readPartialsObject`.
 *
 * @param {String} src
 * @param {String|Object} partials
 * @return {Promise}
 */
function readPartials(src, partials) {
  if (!partials) {
    return null;
  }

  if (typeof partials === 'string') {
    return readPartialsDirectory(src, partials);
  }

  return readPartialsObject(src, partials);
}

module.exports = function (mustache) {
  mustache = mustache || require('mustache');

  var writeFile = q.denodeify(fs.writeFile);

  return {
    mustache: d.srcDest(function (src, dest, partials) {
      var promise = q.all([
        readFile(src, 'utf8'),
        readPartials(this.src, partials)
      ])
        .spread(function (template, partials) {
          return mustache.render(template, this.ctx, partials);
        }.bind(this))
        .then(ap([dest], writeFile));

      this.push(promise);
    }),
  };
};
<|endoftext|>


<commit_before>'use strict';

var isPng = require('is-png');
var pngquant = require('pngquant-bin').path;
var spawn = require('child_process').spawn;
var through = require('through2');

/**
 * pngquant imagemin plugin
 *
 * @param {Object} opts
 * @api public
 */

module.exports = function (opts) {
	opts = opts || {};

	return through.obj(function (file, enc, cb) {
		if (file.isNull()) {
			cb(null, file);
			return;
		}

		if (file.isStream()) {
			cb(new Error('Streaming is not supported'));
			return;
		}

		if (!isPng(file.contents)) {
			cb(null, file);
			return;
		}

		var args = ['--skip-if-larger', '-'];
		var ret = [];
		var len = 0;

		if (opts.floyd) {
			args.push('--floyd', opts.floyd);
		}

		if (opts.nofs) {
			args.push('--nofs');
		}

		if (opts.posterize) {
			args.push('--posterize', opts.posterize);
		}

		if (opts.quality) {
			args.push('--quality', opts.quality);
		}

		if (opts.speed) {
			args.push('--speed', opts.speed);
		}

		if (opts.verbose) {
			args.push('--verbose');
		}

		var cp = spawn(pngquant, args);

		cp.on('error', function (err) {
			cb(err);
			return;
		});

		cp.stderr.setEncoding('utf8');
		cp.stderr.on('data', function (data) {
			cb(new Error(data));
			return;
		});

		cp.stdout.on('data', function (data) {
			ret.push(data);
			len += data.length;
		});

		cp.on('close', function () {
			file.contents = Buffer.concat(ret, len);
			cb(null, file);
		});

		cp.stdin.end(file.contents);
	});
};
<commit_msg>Manually check if optimized file is larger than the original<commit_after>'use strict';

var isPng = require('is-png');
var pngquant = require('pngquant-bin').path;
var spawn = require('child_process').spawn;
var through = require('through2');

/**
 * pngquant imagemin plugin
 *
 * @param {Object} opts
 * @api public
 */

module.exports = function (opts) {
	opts = opts || {};

	return through.obj(function (file, enc, cb) {
		if (file.isNull()) {
			cb(null, file);
			return;
		}

		if (file.isStream()) {
			cb(new Error('Streaming is not supported'));
			return;
		}

		if (!isPng(file.contents)) {
			cb(null, file);
			return;
		}

		var args = ['-'];
		var ret = [];
		var len = 0;

		if (opts.floyd) {
			args.push('--floyd', opts.floyd);
		}

		if (opts.nofs) {
			args.push('--nofs');
		}

		if (opts.posterize) {
			args.push('--posterize', opts.posterize);
		}

		if (opts.quality) {
			args.push('--quality', opts.quality);
		}

		if (opts.speed) {
			args.push('--speed', opts.speed);
		}

		if (opts.verbose) {
			args.push('--verbose');
		}

		var cp = spawn(pngquant, args);

		cp.on('error', function (err) {
			cb(err);
			return;
		});

		cp.stderr.setEncoding('utf8');
		cp.stderr.on('data', function (data) {
			cb(new Error(data));
			return;
		});

		cp.stdout.on('data', function (data) {
			ret.push(data);
			len += data.length;
		});

		cp.on('close', function () {
			if (len < file.contents.length) {
				file.contents = Buffer.concat(ret, len);
			}

			cb(null, file);
		});

		cp.stdin.end(file.contents);
	});
};
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var path = require('path');
var Funnel = require('broccoli-funnel');
var MergeTrees = require('broccoli-merge-trees');

module.exports = {
  name: 'ember-cli-dropzonejs',
  included() {
    this._super.included.apply(this, arguments);
    this.import('vendor/dropzone.min.js');
    this.import('vendor/dropzone.min.css');
  },
  treeForVendor(vendorTree) {
    let trees = [];
    let dropzoneTree = new Funnel(
      path.join(this.project.root, 'node_modules', 'dropzone/dist/min'),
      {
        files: ['dropzone.min.js', 'dropzone.min.css']
      }
    );

    trees.push(dropzoneTree);

    if (vendorTree) {
      trees.push(vendorTree);
    }
    return new MergeTrees(trees);
  }
};
<commit_msg>fastboot guard<commit_after>/* jshint node: true */
'use strict';

var path = require('path');
var Funnel = require('broccoli-funnel');
var MergeTrees = require('broccoli-merge-trees');

module.exports = {
  name: 'ember-cli-dropzonejs',
  included() {
    this._super.included.apply(this, arguments);
    if (!process.env.EMBER_CLI_FASTBOOT) {
      this.import('vendor/dropzone.min.js');
      this.import('vendor/dropzone.min.css');
    }
  },
  treeForVendor(vendorTree) {
    if (!process.env.EMBER_CLI_FASTBOOT) {
      let trees = [];
      let dropzoneTree = new Funnel(
        path.join(this.project.root, 'node_modules', 'dropzone/dist/min'),
        {
          files: ['dropzone.min.js', 'dropzone.min.css']
        }
      );

      trees.push(dropzoneTree);

      if (vendorTree) {
        trees.push(vendorTree);
      }
      return new MergeTrees(trees);
    }
  }
};
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var path = require('path');

exec('mkfifo omxpipe');

class OmxInterface {

	constructor() {
		this.defaults = null;
		this.progressHandler = null;
		this.cache = this.setDefault();

		this.dbus = "bash "+__dirname+"/dbus.sh ";
		this.dbusDest = "";

		this.playTryCount = 0;
		this.pauseTryCount = 0;
		this.stopTryCount = 0;
		this.quitTryCount = 0;
		this.togglePlayTryCount = 0;
		this.seekTryCount = 0;
		this.setPositionTryCount = 0;
		this.setVolumeTryCount = 0;

	}

	setDefault () {
		this.defaults = {
			path:{
				value:'',
				time:new Date(),
				valid:false
			},
			position:{
				value:false,
				time:new Date(),
				valid:false
			},
			duration:{
				value:0,
				time:new Date(),
				valid:false
			},
			volume:{
				value:1.0,
				time:new Date(),
				valid:false
			},
			isPlaying:{
				value:0,
				time:new Date(),
				valid:false
			}
		};

		return this.defaults;
	}

	checkProgressHandler() {
		if (this.progressHandler) {
			clearInterval(this.progressHandler);
			console.log('progressHandler cancelled');
		}
	}

	dbusCommand (command)  {
		let merge = "bash " +__dirname+"/dbus.sh " + this.dbusDest + " " + command;
		if (command != 'getplaystatus' && command !='getvolume' && command != 'getposition') { console.log('merge:', merge); }
		return merge;
	}

	play () {
		this.checkProgressHandler();
		exec(this.dbusCommand('getplaystatus'), (error, stdout, stderr) => {
			if(error && (this.playTryCount < 3)){
				this.playTryCount++;
				this.play();
			} else if(error) {
				this.playTryCount = 0;
			} else {
				this.playTryCount = 0;
				if (stdout.indexOf("Paused")>-1) {
					this.togglePlay();
					this.cache.isPlaying.value = 1;
					this.cache.isPlaying.time = new Date();
					this.cache.isPlaying.valid = true;
				}
			}
		});
	}

	pause () {
		exec(this.dbusCommand('getplaystatus'), (error, stdout, stderr) => {
			if (error) {
				console.log('getplaystatus error:', error);
			} else {
				console.log('getplaystatus result:', stdout);
			}
			if(error && (this.stopTryCount < 3)){
				this.pauseTryCount++;
				this.pause();
			} else if(error) {
				pauseTryCount = 0;
			} else {
				pauseTryCount = 0;
				if (stdout.indexOf("Playing")>-1) {
					this.togglePlay();
	 				this.cache.isPlaying.value = 0;
	 				this.cache.isPlaying.time = new Date();
	 				this.cache.isPlaying.valid = true;
				}
			}
		});
	}

	stop () {
		exec(this.dbusCommand('stop'), (error, stdout, stderr) => {
			if(error && (this.stopTryCount < 3)){
				this.stopTryCount++;
				this.stop();
			} else if(error) {
				this.stopTryCount = 0;
			} else {
				this.stopTryCount = 0;
				this.cache = this.defaults;
			}
		});
		this.checkProgressHandler();
	}

	quit () {
		this.checkProgressHandler();
		exec(this.dbusCommand('quit'), (error, stdout, stderr) => {
			if(error && (this.quitTryCount < 3)){
				this.quitTryCount++;
				this.quit();
			} else if(error) {
				this.quitTryCount = 0;
			} else {
				this.quitTryCount = 0;
				this.cache = this.defaults;
			}
	  });
	}

	togglePlay () {
		exec(this.dbusCommand('toggleplay'), (error, stdout, stderr) => {
			if (error) {
				console.log('toggleplay error:', error);
			} else {
				console.log('toggleplay result:', stdout);
			}
			if(error && (this.togglePlayTryCount < 4)){
				this.togglePlayTryCount++;
				this.togglePlay();
			} else {
				this.togglePlayTryCount = 0;
			}
	  });
	}

	seek (offset) {
		//seek offset in seconds; relative from current position; negative values will cause a jump back;
		exec(this.dbusCommand('seek ' +Math.round(offset*1000000)), (error, stdout, stderr) => {
			if(error && (seekTryCount < 4)){
				seekTryCount++;
				this.seek(offset);
			} else {
				seekTryCount = 0;
				this.update_position();
			}
	  });
	}

	setPosition (position) {
		//position in seconds from start; //positions larger than the duration will stop the player;
		exec(this.dbusCommand('setposition '+Math.round(position*1000000)), (error, stdout, stderr) => {
			if(error && (setPositionTryCount < 4)){
				setPositionTryCount++;
				this.setPosition(position);
			} else {
				setPositionTryCount = 0;
				this.update_position();
			}
	  });
	}

	setVolume (volume) {
		//volume should be set from 0.0 to 1.0; Above 1.0 is depreciated;
		exec(this.dbusCommand('setvolume '+volume), (error, stdout, stderr) => {
			if(error && (setPositionTryCount < 4)){
				setVolumeTryCount++;
				this.setVolume(volume);
			} else {
				setVolumeTryCount = 0;
				this.update_volume();
			}
	  });
	}

	setVisibility (visible) {
		let command = visible ? 'unhidevideo' : 'hidevideo';
		exec(this.dbusCommand(command), (err, stdout, stderr) => {
			console.log('result of setVisible:', command, ': error?', err);
		});
	}

	setAlpha (alpha) {
		exec(this.dbusCommand('setalpha ' + alpha), (err, stdout, stderr) => {
			console.log('result of setAlpha; error?', err);
		});
	}

	update_position () {
		exec(this.dbusCommand('getposition'), (error, stdout, stderr) => {
			if (error) return false;
			let position = parseInt(stdout);
			this.cache.position.value = position;
			this.cache.position.time = new Date();
			this.cache.position.valid = true;
	  });
	}

	update_status () {
		exec(this.dbusCommand('getplaystatus'), (error, stdout, stderr) => {
			if (error) return false;
			this.cache.isPlaying.value = ((stdout.indexOf("Playing")>-1) ? 1 : 0);
	 		this.cache.isPlaying.time = new Date();
			this.cache.isPlaying.valid = true;
	  });
	}

	update_duration () {
		exec( this.dbusCommand('getduration'), (error, stdout, stderr) => {
			if (error) return false;
	    	var duration = Math.round(Math.max(0,Math.round(parseInt(stdout.substring((stdout.indexOf("int64")>-1 ? stdout.indexOf("int64")+6:0)))/10000)/100));
			this.cache.duration.value = duration;
			this.cache.duration.time = new Date();
			this.cache.duration.valid = true;
	  });
	}

	update_volume () {
		exec(this.dbusCommand('getvolume'), (error, stdout, stderr) => {
			if (error) return false;
    	let volume = parseFloat(stdout);
			this.cache.volume.value = volume;
			this.cache.volume.time = new Date();
			this.cache.volume.valid = true;
	  });
	}

	getCurrentPosition () {
		if((new Date()-this.cache.position.time)/1000 > 2) {
			this.cache.position.valid = false;
		}
		if(!this.cache.position.valid) {
			this.update_position();
		}
		if(this.cache.position.value > 0) {
			return Math.round(Math.max(0,Math.min(Math.round((this.cache.position.value + getCurrentStatus()*((new Date())-this.cache.position.time)*1000)/1000000),getCurrentDuration())));
		} else {
			return 0;
		}
	}

	getCurrentStatus () {
		if((new Date()-cache.isPlaying.time)/1000 > 2) {
			this.cache.isPlaying.valid = false;
		}
		if(!this.cache.isPlaying.valid) {
			this.update_status();
		}
		return this.cache.isPlaying.value;
	}

	getCurrentDuration () {
		if(this.cache.duration.value <= 0) {
			this.cache.duration.valid = false;
		}
		if(!this.cache.duration.valid) {
			this.update_duration();
		}
		return this.cache.duration.value;
	}

	getCurrentVolume () {
		if(!this.cache.volume.valid) {
			this.update_volume();
		}
		return this.cache.volume.value;
	}

	onProgress (callback) {
		console.log('add new progress handler')
		this.progressHandler = setInterval( () => {
			if(this.getCurrentStatus()){
				callback({position: this.getCurrentPosition(), duration: this.getCurrentDuration()});
			}
		}, 1000);
	}

	open (path, options) {
		console.log('OmxInterface open()');
		let settings = options || {};
		let args = [];
		let command = 'omxplayer';

		this.cache = this.setDefault();

		this.cache.path.value = path;
		this.cache.path.valid = true;

		args.push('"'+path+'"');

		if (['hdmi','local','both'].indexOf(settings.audioOutput) != -1) {
			args.push('-o');
			args.push(settings.audioOutput);
		}

		if (settings.blackBackground !== false) { // defaults to true
			args.push('-b');
		}

		if (settings.disableKeys === true) { //defaults to  false
			args.push('--no-keys')
		}

		if (settings.disableOnScreenDisplay === true) { //defaults to  false
			args.push('--no-osd')
		}

		if (settings.disableGhostbox === true) { //defaults to  false
			args.push('--no-ghost-box');
		}

		if (settings.loop === true) { // defaults to false
			args.push('--loop');
		}

		if (settings.subtitlePath && settings.subtitlePath != "" ){
			args.push('--subtitles');
			args.push('"'+settings.subtitlePath+'"');
		}

		if (settings.startAt){
			args.push('--pos');
			args.push(''+settings.startAt+'');
		}

		let dbusName = 'org.mpris.MediaPlayer2.omxplayer'; // default
		if (settings.layer) {
			args.push('--layer');
			args.push(settings.layer);
			dbusName = dbusName + '_layer' + settings.layer;
			console.log('setup for layered mode; player will be on layer', settings.layer, 'and dbus name will be', dbusName);
		}

		args.push('--dbus_name');
		args.push(dbusName);

		this.dbusDest = dbusName;

	  exec( command+' '+args.join(' ')+' < omxpipe', (error, stdout, stderr) => {
			this.update_duration();
			console.log('omxpipe done');
			setTimeout( () => {
				this.checkProgressHandler();
			}, 1000);
	  	console.log(stdout);
	  });
	  exec(' . > omxpipe');

	  this.update_duration();

	}

}

module.exports = OmxInterface;
<commit_msg>stray ref<commit_after>var exec = require('child_process').exec;
var path = require('path');

exec('mkfifo omxpipe');

class OmxInterface {

	constructor() {
		this.defaults = null;
		this.progressHandler = null;
		this.cache = this.setDefault();

		this.dbus = "bash "+__dirname+"/dbus.sh ";
		this.dbusDest = "";

		this.playTryCount = 0;
		this.pauseTryCount = 0;
		this.stopTryCount = 0;
		this.quitTryCount = 0;
		this.togglePlayTryCount = 0;
		this.seekTryCount = 0;
		this.setPositionTryCount = 0;
		this.setVolumeTryCount = 0;

	}

	setDefault () {
		this.defaults = {
			path:{
				value:'',
				time:new Date(),
				valid:false
			},
			position:{
				value:false,
				time:new Date(),
				valid:false
			},
			duration:{
				value:0,
				time:new Date(),
				valid:false
			},
			volume:{
				value:1.0,
				time:new Date(),
				valid:false
			},
			isPlaying:{
				value:0,
				time:new Date(),
				valid:false
			}
		};

		return this.defaults;
	}

	checkProgressHandler() {
		if (this.progressHandler) {
			clearInterval(this.progressHandler);
			console.log('progressHandler cancelled');
		}
	}

	dbusCommand (command)  {
		let merge = "bash " +__dirname+"/dbus.sh " + this.dbusDest + " " + command;
		if (command != 'getplaystatus' && command !='getvolume' && command != 'getposition') { console.log('merge:', merge); }
		return merge;
	}

	play () {
		this.checkProgressHandler();
		exec(this.dbusCommand('getplaystatus'), (error, stdout, stderr) => {
			if(error && (this.playTryCount < 3)){
				this.playTryCount++;
				this.play();
			} else if(error) {
				this.playTryCount = 0;
			} else {
				this.playTryCount = 0;
				if (stdout.indexOf("Paused")>-1) {
					this.togglePlay();
					this.cache.isPlaying.value = 1;
					this.cache.isPlaying.time = new Date();
					this.cache.isPlaying.valid = true;
				}
			}
		});
	}

	pause () {
		exec(this.dbusCommand('getplaystatus'), (error, stdout, stderr) => {
			if (error) {
				console.log('getplaystatus error:', error);
			} else {
				console.log('getplaystatus result:', stdout);
			}
			if(error && (this.stopTryCount < 3)){
				this.pauseTryCount++;
				this.pause();
			} else if(error) {
				pauseTryCount = 0;
			} else {
				pauseTryCount = 0;
				if (stdout.indexOf("Playing")>-1) {
					this.togglePlay();
	 				this.cache.isPlaying.value = 0;
	 				this.cache.isPlaying.time = new Date();
	 				this.cache.isPlaying.valid = true;
				}
			}
		});
	}

	stop () {
		exec(this.dbusCommand('stop'), (error, stdout, stderr) => {
			if(error && (this.stopTryCount < 3)){
				this.stopTryCount++;
				this.stop();
			} else if(error) {
				this.stopTryCount = 0;
			} else {
				this.stopTryCount = 0;
				this.cache = this.defaults;
			}
		});
		this.checkProgressHandler();
	}

	quit () {
		this.checkProgressHandler();
		exec(this.dbusCommand('quit'), (error, stdout, stderr) => {
			if(error && (this.quitTryCount < 3)){
				this.quitTryCount++;
				this.quit();
			} else if(error) {
				this.quitTryCount = 0;
			} else {
				this.quitTryCount = 0;
				this.cache = this.defaults;
			}
	  });
	}

	togglePlay () {
		exec(this.dbusCommand('toggleplay'), (error, stdout, stderr) => {
			if (error) {
				console.log('toggleplay error:', error);
			} else {
				console.log('toggleplay result:', stdout);
			}
			if(error && (this.togglePlayTryCount < 4)){
				this.togglePlayTryCount++;
				this.togglePlay();
			} else {
				this.togglePlayTryCount = 0;
			}
	  });
	}

	seek (offset) {
		//seek offset in seconds; relative from current position; negative values will cause a jump back;
		exec(this.dbusCommand('seek ' +Math.round(offset*1000000)), (error, stdout, stderr) => {
			if(error && (seekTryCount < 4)){
				seekTryCount++;
				this.seek(offset);
			} else {
				seekTryCount = 0;
				this.update_position();
			}
	  });
	}

	setPosition (position) {
		//position in seconds from start; //positions larger than the duration will stop the player;
		exec(this.dbusCommand('setposition '+Math.round(position*1000000)), (error, stdout, stderr) => {
			if(error && (setPositionTryCount < 4)){
				setPositionTryCount++;
				this.setPosition(position);
			} else {
				setPositionTryCount = 0;
				this.update_position();
			}
	  });
	}

	setVolume (volume) {
		//volume should be set from 0.0 to 1.0; Above 1.0 is depreciated;
		exec(this.dbusCommand('setvolume '+volume), (error, stdout, stderr) => {
			if(error && (setPositionTryCount < 4)){
				setVolumeTryCount++;
				this.setVolume(volume);
			} else {
				setVolumeTryCount = 0;
				this.update_volume();
			}
	  });
	}

	setVisibility (visible) {
		let command = visible ? 'unhidevideo' : 'hidevideo';
		exec(this.dbusCommand(command), (err, stdout, stderr) => {
			console.log('result of setVisible:', command, ': error?', err);
		});
	}

	setAlpha (alpha) {
		exec(this.dbusCommand('setalpha ' + alpha), (err, stdout, stderr) => {
			console.log('result of setAlpha; error?', err);
		});
	}

	update_position () {
		exec(this.dbusCommand('getposition'), (error, stdout, stderr) => {
			if (error) return false;
			let position = parseInt(stdout);
			this.cache.position.value = position;
			this.cache.position.time = new Date();
			this.cache.position.valid = true;
	  });
	}

	update_status () {
		exec(this.dbusCommand('getplaystatus'), (error, stdout, stderr) => {
			if (error) return false;
			this.cache.isPlaying.value = ((stdout.indexOf("Playing")>-1) ? 1 : 0);
	 		this.cache.isPlaying.time = new Date();
			this.cache.isPlaying.valid = true;
	  });
	}

	update_duration () {
		exec( this.dbusCommand('getduration'), (error, stdout, stderr) => {
			if (error) return false;
    	let duration = Math.round(Math.max(0,Math.round(parseInt(stdout.substring((stdout.indexOf("int64")>-1 ? stdout.indexOf("int64")+6:0)))/10000)/100));
			this.cache.duration.value = duration;
			this.cache.duration.time = new Date();
			this.cache.duration.valid = true;
	  });
	}

	update_volume () {
		exec(this.dbusCommand('getvolume'), (error, stdout, stderr) => {
			if (error) return false;
    	let volume = parseFloat(stdout);
			this.cache.volume.value = volume;
			this.cache.volume.time = new Date();
			this.cache.volume.valid = true;
	  });
	}

	getCurrentPosition () {
		if((new Date()-this.cache.position.time)/1000 > 2) {
			this.cache.position.valid = false;
		}
		if(!this.cache.position.valid) {
			this.update_position();
		}
		if(this.cache.position.value > 0) {
			return Math.round(Math.max(0,Math.min(Math.round((this.cache.position.value + getCurrentStatus()*((new Date())-this.cache.position.time)*1000)/1000000),getCurrentDuration())));
		} else {
			return 0;
		}
	}

	getCurrentStatus () {
		if((new Date()-this.cache.isPlaying.time)/1000 > 2) {
			this.cache.isPlaying.valid = false;
		}
		if(!this.cache.isPlaying.valid) {
			this.update_status();
		}
		return this.cache.isPlaying.value;
	}

	getCurrentDuration () {
		if(this.cache.duration.value <= 0) {
			this.cache.duration.valid = false;
		}
		if(!this.cache.duration.valid) {
			this.update_duration();
		}
		return this.cache.duration.value;
	}

	getCurrentVolume () {
		if(!this.cache.volume.valid) {
			this.update_volume();
		}
		return this.cache.volume.value;
	}

	onProgress (callback) {
		console.log('add new progress handler')
		this.progressHandler = setInterval( () => {
			if(this.getCurrentStatus()){
				callback({position: this.getCurrentPosition(), duration: this.getCurrentDuration()});
			}
		}, 1000);
	}

	open (path, options) {
		console.log('OmxInterface open()');
		let settings = options || {};
		let args = [];
		let command = 'omxplayer';

		this.cache = this.setDefault();

		this.cache.path.value = path;
		this.cache.path.valid = true;

		args.push('"'+path+'"');

		if (['hdmi','local','both'].indexOf(settings.audioOutput) != -1) {
			args.push('-o');
			args.push(settings.audioOutput);
		}

		if (settings.blackBackground !== false) { // defaults to true
			args.push('-b');
		}

		if (settings.disableKeys === true) { //defaults to  false
			args.push('--no-keys')
		}

		if (settings.disableOnScreenDisplay === true) { //defaults to  false
			args.push('--no-osd')
		}

		if (settings.disableGhostbox === true) { //defaults to  false
			args.push('--no-ghost-box');
		}

		if (settings.loop === true) { // defaults to false
			args.push('--loop');
		}

		if (settings.subtitlePath && settings.subtitlePath != "" ){
			args.push('--subtitles');
			args.push('"'+settings.subtitlePath+'"');
		}

		if (settings.startAt){
			args.push('--pos');
			args.push(''+settings.startAt+'');
		}

		let dbusName = 'org.mpris.MediaPlayer2.omxplayer'; // default
		if (settings.layer) {
			args.push('--layer');
			args.push(settings.layer);
			dbusName = dbusName + '_layer' + settings.layer;
			console.log('setup for layered mode; player will be on layer', settings.layer, 'and dbus name will be', dbusName);
		}

		args.push('--dbus_name');
		args.push(dbusName);

		this.dbusDest = dbusName;

	  exec( command+' '+args.join(' ')+' < omxpipe', (error, stdout, stderr) => {
			this.update_duration();
			console.log('omxpipe done');
			setTimeout( () => {
				this.checkProgressHandler();
			}, 1000);
	  	console.log(stdout);
	  });
	  exec(' . > omxpipe');

	  this.update_duration();

	}

}

module.exports = OmxInterface;
<|endoftext|>


<commit_before>var fs = require("fs");
var _ = require('lodash');

//the league's average calculated each year.
//The ".011" added reflects the frequency that Groundball A++ will also become hits.
//2016 stats
const NLBA = 0.254 + 0.011;
const ALBA = 0.257 + 0.011;
const MLBBA = 0.255 + 0.011; // just use this for now
const testBA = 0.265 + 0.011; // for Cal Ripkin testing only

var content = fs.readFileSync("2016-standard-batting.json");
var batting_stats = JSON.parse(content);

var player_stats = _.find(batting_stats, { 'Name': "Mike Trout"});

//console.log(playerObj['2B']);
//console.log(somAst(playerObj));

var player = player_stats;

//format a stat block in the console
var testNumb = somW(player) + somHBP(player) + somH(player) + (somD(player)/20) + (somT(player)/20) + (somHR(player)/20) + somK(player) + somGBA(player) + somGBB(player);
console.log("\n" + player.Name, "\n===========================\n",
	"walk chances: " + somW(player) + "\n\n",
	"hit by pitch chances: " + somHBP(player) + "\n\n",
	"hit chances: " + somH(player) + "\n\n",
	"double chances: " + (somD(player)/20) + " | subchances: " + somD(player) + "\n\n",
	"triple chances: " + (somT(player)/20) + " | subchances: " + somT(player) + "\n\n",
	"home run chances: " + (somHR(player)/20) + " | subchances: " + somHR(player) + "\n\n",
	"strikeout chances: " + somK(player) + "\n\n",
	"ground ball A chances: " + somGBA(player) + "\n\n",
	"ground ball B chances: " + somGBB(player) + "\n\n"
	);
console.log(testNumb);

//som's own "plate appearance" number, testing only, not for use
function somPA(player) {
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	return ( AB + ( W - IW ) + HBP );
}

//batter's walk. returns chances
function somW(player) {
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var AB = _.toFinite(player.AB);
	var HBP = _.toFinite(player.HBP);

	var walk = (((W - IW) * 216) / (AB + ( W - IW) + HBP)) - 9;

	return walk;
}

//batter's hit by pitch. returns chances
function somHBP(player) {
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var AB = _.toFinite(player.AB);
	var HBP = _.toFinite(player.HBP);

	var hit_by_pitch = ((HBP * 216) / (AB + (W - IW) + HBP));

	return hit_by_pitch;
}

//batter's hit. returns chances
function somH(player) {
	var W = somW(player);
	var HBP = somHBP(player);
	var BA = _.toFinite(player.BA);
	var LG = player.Lg;
	var leagueBA = MLBBA;

	//find the right batting average
	if (LG == "NL") {
		leagueBA = NLBA;
	} else if (LG == "AL") {
		leagueBA = ALBA;
	}

	console.log("battin avg. ", LG, leagueBA);

	var hit = (( BA - leagueBA ) + BA ) * ( 108 - ( W + HBP ));

	return hit;
}

//batter's double. returns subchances
function somD(player) {
	var second_bases = _.toFinite(player['2B']);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var doubles = ( 4320 * second_bases ) / ( AB + ( W - IW ) + HBP ) - 90;

	//can't have negative chances on a card.
	if (doubles < 0) {
		doubles = 0;
	}

	return doubles;
}

//batter's triple. returns subchances
function somT(player) {
	var third_bases = _.toFinite(player['3B']);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var triples = ( 4320 * third_bases ) / ( AB + ( W - IW ) + HBP ) - 15;

	//can't have negative chances on a card.
	if (triples < 0) {
		triples = 0;
	}

	return triples;
}

//batter's home run. returns subchances
function somHR(player) {
	var HR = _.toFinite(player.HR);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var home_runs = ( 4320 * HR ) / ( AB + ( W - IW ) + HBP ) - 50;

	//can't have negative chances on a card.
	if (home_runs < 0) {
		home_runs = 0;
	}

	return home_runs;
}

//batter's strike out. returns chances
function somK(player) {
	var K = _.toFinite(player.SO);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var strike_out = (( K * 216 ) / ( AB + ( W - IW ) + HBP )) - 17;

	//can't have negative chances on a card.
	if (strike_out < 0) {
		strike_out = 0;
	}

	return strike_out;
}

//batter's ground ball A. returns chances
function somGBA(player) {
	var DP = _.toFinite(player.GDP);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var ground_ball_A = ( 1140 * DP ) / ( AB + ( W - IW ) + HBP );

	return ground_ball_A;
}

//batter's ground ball B. returns chances.
function somGBB(player) {
	var GBA = somGBA(player);

	var ground_ball_B = 31 - GBA;

	if (ground_ball_B < 0) {
		ground_ball_B = 0;
	}

	return ground_ball_B;
}

//runner's first stolen base. returns upper value of a d20 roll
function som1SB(player) {
	var SB = _.toFinite(player.SB);
	var CS = _.toFinite(player.CS);

	if (SB == 0 && CS == 0) {
		var first_stolen_base = 0.13 * 20;
	} else {
		var first_stolen_base = (( SB / ( SB + CS )) + 0.13 ) * 20;
	}

	//always room for error. 5% in fact
	if (first_stolen_base > 20) {
		first_stolen_base = 19;
	}

	first_stolen_base = _.round(first_stolen_base);

	//returns the ceiling of a 1d20 roll. e.g. 15 is a 1-15 success
	return first_stolen_base;
}

//runner's second stolen base. returns upper value of a d20 roll
function som2SB(player) {
	var SB1 = som1SB(player);

	var second_stolen_base = (SB1 - ( SB1 / 3 )) + 1;

	second_stolen_base = _.round(second_stolen_base);

	return second_stolen_base;
}

//runner's stolen base lead
function somSBLead(player) {
	var SB = _.toFinite(player.SB);
	var CS = _.toFinite(player.CS);
	var H = _.toFinite(player.H);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);
	var second_bases = _.toFinite(player['2B']);
	var third_bases = _.toFinite(player['3B']);
	var HR = _.toFinite(player.HR);

	var lead_chances = (36 * ( SB + CS )) / ((( H + ( W - IW ) + HBP ) * .85 ) - ( second_bases + third_bases + HR ));

	return lead_chances;
}

//runner's asterisk. returns boolean
function somAst(player) {
	var SB1 = som1SB(player);
	var SBLead = somSBLead(player);

	if ((SB1 + SBLead) > 24) {
		//console.log(SB1 + SBLead);
		return true;
	} else {
		//console.log(SB1 + SBLead);
		return false;
	}
}

<commit_msg>rounding for hits<commit_after>var fs = require("fs");
var _ = require('lodash');

//the league's average calculated each year.
//The ".011" added reflects the frequency that Groundball A++ will also become hits.
//2016 stats
const NLBA = 0.254 + 0.011;
const ALBA = 0.257 + 0.011;
const MLBBA = 0.255 + 0.011; // just use this for now
const testBA = 0.265 + 0.011; // for Cal Ripkin testing only

var content = fs.readFileSync("2016-standard-batting.json");
var batting_stats = JSON.parse(content);

var player_stats = _.find(batting_stats, { 'Name': "Cal Ripkin"});

//console.log(playerObj['2B']);
//console.log(somAst(playerObj));

var player = player_stats;

//format a stat block in the console
var testNumb = somW(player) + somHBP(player) + somH(player) + (somD(player)/20) + (somT(player)/20) + (somHR(player)/20) + somK(player) + somGBA(player) + somGBB(player);
console.log("\n" + player.Name, "\n===========================\n",
	"walk chances: " + somW(player) + "\n\n",
	"hit by pitch chances: " + somHBP(player) + "\n\n",
	"hit chances: " + somH(player) + "\n\n",
	"double chances: " + (somD(player)/20) + " | subchances: " + somD(player) + "\n\n",
	"triple chances: " + (somT(player)/20) + " | subchances: " + somT(player) + "\n\n",
	"home run chances: " + (somHR(player)/20) + " | subchances: " + somHR(player) + "\n\n",
	"strikeout chances: " + somK(player) + "\n\n",
	"ground ball A chances: " + somGBA(player) + "\n\n",
	"ground ball B chances: " + somGBB(player) + "\n\n"
	);
console.log(testNumb);

//som's own "plate appearance" number, testing only, not for use
function somPA(player) {
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	return ( AB + ( W - IW ) + HBP );
}

//batter's walk. returns chances
function somW(player) {
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var AB = _.toFinite(player.AB);
	var HBP = _.toFinite(player.HBP);

	var walk = (((W - IW) * 216) / (AB + ( W - IW) + HBP)) - 9;

	//can't have negative chances on a card.
	if (walk < 0) {
		walk = 0;
	}

	return _.round(walk);
}

//batter's hit by pitch. returns chances
function somHBP(player) {
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var AB = _.toFinite(player.AB);
	var HBP = _.toFinite(player.HBP);

	var hit_by_pitch = ((HBP * 216) / (AB + (W - IW) + HBP));

	//can't have negative chances on a card.
	if (hit_by_pitch < 0) {
		hit_by_pitch = 0;
	}

	return _.round(hit_by_pitch);
}

//batter's hit. returns chances
function somH(player) {
	var W = somW(player);
	var HBP = somHBP(player);
	var BA = _.toFinite(player.BA);
	var LG = player.Lg;
	var leagueBA = MLBBA;

	//find the right batting average
	if (LG == "NL") {
		leagueBA = NLBA;
	} else if (LG == "AL") {
		leagueBA = ALBA;
	}

	var hit = (( BA - leagueBA ) + BA ) * ( 108 - ( W + HBP ));

	//can't have negative chances on a card.
	if (hit < 0) {
		hit = 0;
	}

	return _.round(hit, 2);
}

//batter's double. returns subchances
function somD(player) {
	var second_bases = _.toFinite(player['2B']);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var doubles = ( 4320 * second_bases ) / ( AB + ( W - IW ) + HBP ) - 90;

	//can't have negative chances on a card.
	if (doubles < 0) {
		doubles = 0;
	}

	return _.round(doubles);
}

//batter's triple. returns subchances
function somT(player) {
	var third_bases = _.toFinite(player['3B']);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var triples = ( 4320 * third_bases ) / ( AB + ( W - IW ) + HBP ) - 15;

	//can't have negative chances on a card.
	if (triples < 0) {
		triples = 0;
	}

	return _.round(triples);
}

//batter's home run. returns subchances
function somHR(player) {
	var HR = _.toFinite(player.HR);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var home_runs = ( 4320 * HR ) / ( AB + ( W - IW ) + HBP ) - 50;

	//can't have negative chances on a card.
	if (home_runs < 0) {
		home_runs = 0;
	}

	return _.round(home_runs);
}

//batter's strike out. returns chances
function somK(player) {
	var K = _.toFinite(player.SO);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var strike_out = (( K * 216 ) / ( AB + ( W - IW ) + HBP )) - 17;

	//can't have negative chances on a card.
	if (strike_out < 0) {
		strike_out = 0;
	}

	return _.round(strike_out);
}

//batter's ground ball A. returns chances
function somGBA(player) {
	var DP = _.toFinite(player.GDP);
	var AB = _.toFinite(player.AB);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);

	var ground_ball_A = ( 1140 * DP ) / ( AB + ( W - IW ) + HBP );

	return _.round(ground_ball_A);
}

//batter's ground ball B. returns chances.
function somGBB(player) {
	var GBA = somGBA(player);

	var ground_ball_B = 31 - GBA;

	if (ground_ball_B < 0) {
		ground_ball_B = 0;
	}

	return _.round(ground_ball_B);
}

//runner's first stolen base. returns upper value of a d20 roll
function som1SB(player) {
	var SB = _.toFinite(player.SB);
	var CS = _.toFinite(player.CS);

	if (SB == 0 && CS == 0) {
		var first_stolen_base = 0.13 * 20;
	} else {
		var first_stolen_base = (( SB / ( SB + CS )) + 0.13 ) * 20;
	}

	//always room for error. 5% in fact
	if (first_stolen_base > 20) {
		first_stolen_base = 19;
	}

	first_stolen_base = _.round(first_stolen_base);

	//returns the ceiling of a 1d20 roll. e.g. 15 is a 1-15 success
	return first_stolen_base;
}

//runner's second stolen base. returns upper value of a d20 roll
function som2SB(player) {
	var SB1 = som1SB(player);

	var second_stolen_base = (SB1 - ( SB1 / 3 )) + 1;

	second_stolen_base = _.round(second_stolen_base);

	return second_stolen_base;
}

//runner's stolen base lead
function somSBLead(player) {
	var SB = _.toFinite(player.SB);
	var CS = _.toFinite(player.CS);
	var H = _.toFinite(player.H);
	var W = _.toFinite(player.BB);
	var IW = _.toFinite(player.IBB);
	var HBP = _.toFinite(player.HBP);
	var second_bases = _.toFinite(player['2B']);
	var third_bases = _.toFinite(player['3B']);
	var HR = _.toFinite(player.HR);

	var lead_chances = (36 * ( SB + CS )) / ((( H + ( W - IW ) + HBP ) * .85 ) - ( second_bases + third_bases + HR ));

	return lead_chances;
}

//runner's asterisk. returns boolean
function somAst(player) {
	var SB1 = som1SB(player);
	var SBLead = somSBLead(player);

	if ((SB1 + SBLead) > 24) {
		//console.log(SB1 + SBLead);
		return true;
	} else {
		//console.log(SB1 + SBLead);
		return false;
	}
}

<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var through = require('through2');
var duplexer = require('duplexer2');
var util = require('./lib/util');
var cache = require('./lib/cache');
var include = require('./lib/include');
var concat = require('./lib/concat');

function main(options){
  var input = through.obj({ objectMode: true });
  var output = through.obj({ objectMode: true });

  var monitor = function (stream){
    stream.on('error', function (error){
      output.emit('error', error);
    });

    return stream;
  };

  monitor(input)
    .pipe(monitor(include(options)))
    .pipe(monitor(concat()))
    .pipe(output);

  return duplexer(input, output);
}

main.cache = {};
main.cache.clean = cache.clean;
main.cwd = util.cwd;
main.debug = util.debug;
main.colors = util.colors;

/**
 * exports module.
 */
module.exports = main;
<commit_msg>bug fixed<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var through = require('through2');
var duplexer = require('duplexer2');
var util = require('./lib/util');
var cache = require('./lib/cache');
var include = require('./lib/include');
var concat = require('./lib/concat');

function main(options){
  var input = through.obj({ objectMode: true });
  var output = through.obj({ objectMode: true });

  var monitor = function (stream){
    stream.on('error', function (error){
      output.emit('error', error);
    });

    return stream;
  };

  monitor(input)
    .pipe(monitor(include(options)))
    .pipe(monitor(concat()))
    .pipe(output);

  return duplexer({ objectMode: true }, input, output);
}

main.cache = {};
main.cache.clean = cache.clean;
main.cwd = util.cwd;
main.debug = util.debug;
main.colors = util.colors;

/**
 * exports module.
 */
module.exports = main;
<|endoftext|>


<commit_before>var _ = require('lodash');
var debug = require('debug');

var transformers = require('./lib/rules');

var log = debug('e2e:log');
var warn = debug('e2e:warn');

module.exports = function (cfg) {
  log('conversion started...');

  var output = {};
  var eslintRules = cfg.rules || {};

  // TODO: may need to sort rules in a specific order
  Object.keys(transformers)
    .filter(function (rule) {
      var transformer = transformers[rule];

      if (!transformer || transformer.supported === false) {
        warn('%s is not currently supported.', rule);
        return false;
      }

      if (transformer.informative) {
        log('%s is informative.', rule);
        return false;
      }

      if (transformer.deprecated) {
        warn('%s is deprecated', rule);
        return false;
      }

      return true;
    })
    .forEach(function (rule) {
      var ruleValue = 0;
      if (eslintRules.hasOwnProperty(rule)) { ruleValue = eslintRules[rule]; }
      var ruleArgs = !Array.isArray(ruleValue) ? [ruleValue] : ruleValue;

      var transformer = transformers[rule];

      output = _.merge(output, transformer.apply(null, ruleArgs));
    });

  log('conversion finished!');

  return output;
};
<commit_msg>add option logging<commit_after>var util = require('util');

var _ = require('lodash');
var debug = require('debug');

var transformers = require('./lib/rules');

var log = debug('e2e:log');
var warn = debug('e2e:warn');

module.exports = function (cfg) {
  log('conversion started...');

  var output = {};
  var eslintRules = cfg.rules || {};

  // TODO: may need to sort rules in a specific order
  Object.keys(transformers)
    .filter(function (rule) {
      var transformer = transformers[rule];

      if (!transformer || transformer.supported === false) {
        warn('%s is not currently supported.', rule);
        return false;
      }

      if (transformer.informative) {
        log('%s is informative.', rule);
        return false;
      }

      if (transformer.deprecated) {
        warn('%s is deprecated', rule);
        return false;
      }

      return true;
    })
    .forEach(function (rule) {
      log('\t%s started...', rule);

      var ruleValue = 0;
      if (eslintRules.hasOwnProperty(rule)) { ruleValue = eslintRules[rule]; }
      var ruleArgs = !Array.isArray(ruleValue) ? [ruleValue] : ruleValue;

      var transformer = transformers[rule];

      output = _.merge(output, transformer.apply(null, ruleArgs));

      log('\t%s finished!\n', rule);
    });

  log('conversion finished!');
  log('output:\n%s', util.inspect(output, { showHidden: false, depth: null }));

  return output;
};
<|endoftext|>


<commit_before>
exports.Reader = require('./notes')
exports.Compiler = require('./compiler')

exports.BMSChart = require('./bms/chart')
exports.BMSHeaders = require('./bms/headers')
exports.BMSObjects = require('./bms/objects')

exports.Speedcore = require('./speedcore')
exports.TimeSignatures = require('./time-signatures')
exports.Notes = require('./notes')
exports.Timing = require('./timing')
exports.SongInfo = require('./song-info')
<commit_msg>fix(index): fix the wrong require for Reader<commit_after>
exports.Reader = require('./reader')
exports.Compiler = require('./compiler')

exports.BMSChart = require('./bms/chart')
exports.BMSHeaders = require('./bms/headers')
exports.BMSObjects = require('./bms/objects')

exports.Speedcore = require('./speedcore')
exports.TimeSignatures = require('./time-signatures')
exports.Notes = require('./notes')
exports.Timing = require('./timing')
exports.SongInfo = require('./song-info')
<|endoftext|>


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

var app = express();

var http = require('http').Server(app);
var io   = require('socket.io')(http);
var fs   = require('fs');
var path = require('path');

var RaspiCam = require('raspicam');

// Public directory
app.use('/', express.static(path.join(__dirname, 'public')));

// Error handling
app.use(function(err, req, res, next) {
    if (!err) return next();

    console.log("error!!!");
    res.send("error!!!");

    http.close();

    // Kill the process if it doesn't close normally
    setTimeout(function () {
        process.exit(1);
    }, 3*1000);
});

// Display User Interface
app.get('/', function(req, res) {
    res.sendFile('public/index.html');
});

var sockets = {};

// Manage connections of the clients
io.on('connection', function (socket) {
    sockets[socket.id] = socket;
    console.log("Total clients connected : ", Object.keys(sockets).length);

    // Take a snapshot
    var camera = new RaspiCam({
        mode: 'photo',
        output: 'public/camera/tmp/snapshot.jpg',
        encoding: 'jpg',
        timeout: 0 // take the picture immediately
    });

    camera.on('started', function (err, timestamp) {
        console.log("photo started at " + timestamp);
    });

    camera.on('read', function (err, timestamp, filename) {
        console.log("photo image captured with filename: " + filename);

        // Send image to clients
        io.sockets.emit('snapshot', 'camera/tmp/snapshot.jpg?_t=' + (Math.random() * 100000));
    });

    camera.on('stop', function () {
        console.log('camera stopped');
    });

    camera.on('exit', function (timestamp) {
        console.log("photo child process has exited at " + timestamp);
    });

    /*camera.start();*/

    // Bind events to socket
    socket.on('disconnect', function() {
        console.log('Client disconnect...');

        var snapshotFile = 'public/camera/tmp/snapshot.jpg';

        /*if (fs.existsSync(snapshotFile)) {
            // There is a snapshot for this client => delete it
            fs.unlink(snapshotFile, function (err) {
                if (err) throw err;
                console.log('delete "public/camera/tmp/snapshot.jpg"');
            });
        }*/

        delete sockets[socket.id];
        console.log('disconnected');
    });
});

http.listen(3000, function() {
    console.log('listening on *:3000');
});
<commit_msg>move files<commit_after>var express = require('express');

var app = express();

var http = require('http').Server(app);
var io   = require('socket.io')(http);
var fs   = require('fs');
var path = require('path');

var RaspiCam = require('raspicam');

// Public directory
app.use('/', express.static(path.join(__dirname, 'public')));

// Error handling
app.use(function(err, req, res, next) {
    if (!err) return next();

    console.log("error!!!");
    res.send("error!!!");

    http.close();

    // Kill the process if it doesn't close normally
    setTimeout(function () {
        process.exit(1);
    }, 3*1000);
});

// Display User Interface
app.get('/', function(req, res) {
    res.sendFile('public/index.html');
});

var sockets = {};

// Manage connections of the clients
io.on('connection', function (socket) {
    sockets[socket.id] = socket;
    console.log("Total clients connected : ", Object.keys(sockets).length);

    // Take a snapshot
    var camera = new RaspiCam({
        mode: 'photo',
        output: 'public/files/camera/tmp/snapshot.jpg',
        encoding: 'jpg',
        timeout: 0 // take the picture immediately
    });

    camera.on('started', function (err, timestamp) {
        console.log("photo started at " + timestamp);
    });

    camera.on('read', function (err, timestamp, filename) {
        console.log("photo image captured with filename: " + filename);

        // Send image to clients
        io.sockets.emit('snapshot', 'files/camera/tmp/snapshot.jpg?_t=' + (Math.random() * 100000));
    });

    camera.on('stop', function () {
        console.log('camera stopped');
    });

    camera.on('exit', function (timestamp) {
        console.log("photo child process has exited at " + timestamp);
    });

    /*camera.start();*/

    // Bind events to socket
    socket.on('disconnect', function() {
        console.log('Client disconnect...');

        var snapshotFile = 'public/files/camera/tmp/snapshot.jpg';

        /*if (fs.existsSync(snapshotFile)) {
            // There is a snapshot for this client => delete it
            fs.unlink(snapshotFile, function (err) {
                if (err) throw err;
                console.log('delete "public/camera/tmp/snapshot.jpg"');
            });
        }*/

        delete sockets[socket.id];
        console.log('disconnected');
    });
});

http.listen(3000, function() {
    console.log('listening on *:3000');
});
<|endoftext|>


<commit_before>/**
 * Created by achim on 31.07.2017.
 */
/*jslint node: true, es6: true, white: true */
/*jshint esversion: 6 */

"use strict";

const NodePromise = require("promise");
const https = require("https");
const url = require("url");
const querystring = require("querystring");
const fs = require("fs");
const crypto = require("crypto");

//parameter files:
const auth = require("./auth.json");
const config = require("./config.json");
if (config.targetPath.charAt(config.targetPath.length -1) !== "/") {
    config.targetPath += "/";
}

function debug(...msgs) {
    if (config.debugging) {
        console.log(...msgs);
    }
}

//denodifications:
const readFilePromise = NodePromise.denodeify(fs.readFile);
const writeFilePromise = NodePromise.denodeify(fs.writeFile);

let authHeader;
let refreshToken;
function requestPromise(options, postData, decode = true, retry = 0) {
    //add auth header.
    if (authHeader) {
        if (options.headers) {
            options.headers.Authorization = authHeader;
        } else {
            options.headers = {"Authorization": authHeader};
        }
    }
    let promise = new NodePromise(function resolver(resolve, reject) {
        //debug("Sending request", options);
        let req = https.request(options, function callback(res) {
            let data = "";
            res.setEncoding("utf8");
            //debug("Headers:", res.headers);
            res.on("data", function (chunk) { data += chunk; });
            res.on("end", function () {
                //debug("Body: ", data);
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    if (decode) {
                        resolve(JSON.parse(data));
                    } else {
                        resolve(data);
                    }
                } else if (res.statusCode === 401 && !retry) {
                    //need to refresh token.
                    let innerPromise = refreshToken(true);
                    innerPromise = innerPromise.then(function retryRequest() { //retry request.
                        return requestPromise(options, postData, decode, retry + 1);
                    });
                    resolve(innerPromise);
                } else {
                    reject({msg: "Status code not 200: " + res.statusCode, data: data});
                }
            });
        });
        req.on("error", (err) => reject(err));
        //debug("Writing:", postData);
        req.end(postData);
    });

    return promise;
}

//request from metadata server
function requestMetadata(path, jsonData, decode) {
    let options = url.parse(auth.metadataUrl + path);
    let postData;
    if (jsonData) {
        postData = JSON.stringify(jsonData);
        options.headers = {"Content-Length": Buffer.byteLength(postData)};
        options.method = "POST";
    }
    return requestPromise(options, postData, decode);
}
//request from content server
function requestContent(path, decode) {
    let options = url.parse(auth.contentUrl + path);
    return requestPromise(options, undefined, decode);
}
//handle all token stuff. will also update authorization header.
refreshToken = function(realRefresh) {
    let promise;
    authHeader = "";
    if (!realRefresh) {
        promise = readFilePromise(config.accessTokenPath, "utf8");

        promise = promise.then(function gotToken(data) {
            let token = JSON.parse(data);
            debug("Got token from file");
            authHeader = "Bearer " + token.access_token;
            return token;
        }, function needToRefresh() {
            debug("No token file. Get new token.");
            return refreshToken(true);
        });
    } else {
        let options = url.parse(config.refreshProxyUrl);
        options.method = "POST";
        let postData = querystring.stringify({refresh_token: auth.refresh_token});
        options.headers = {"Content-Length": Buffer.byteLength(postData)};

        promise = requestPromise(options, postData, true);

        promise = promise.then(function storeToken(token) {
            debug("Got token from refresh.");
            authHeader = "Bearer " + token.access_token;
            return writeFilePromise(config.accessTokenPath, JSON.stringify(token, null, 4), "utf8");
        });
    }
    return promise;
};

function nodesFromData(data) {
    if (data.data.length >= 0) {
        return data.data;
    }
    if (data.length >= 0) {
        return data;
    }
    throw "No nodes found in data.";
}

function createFolder(parentNode, name) {
    debug("Creating " + name + " in " + (parentNode.name || "root"));
    let createUrl = "nodes?localId=GarfonsoImageSync";
    let jsonData = {
        name: name,
        kind: "FOLDER",
        parents: [parentNode.id]
    };
    return requestMetadata(createUrl, jsonData);
}

function listChildren(node, filter, children = [], nextToken = undefined) {
    let childrenUrl = "nodes/" + node.id + "/children";
    if (filter) {
        childrenUrl += "?filters=" + filter;
    }
    if (nextToken) {
        if (!filter) {
            childrenUrl += "?";
        } else {
            childrenUrl += "&";
        }
        childrenUrl += "startToken=" + nextToken;
    }
    let promise = requestMetadata(childrenUrl);

    promise = promise.then(function (res) {
        children = children.concat(nodesFromData(res));
        //debug("Got children: ", children);
        if (res.nextToken) {
            return listChildren(node, filter, children, res.nextToken);
        } else {
            return children;
        }
    });

    return promise;
}

//create md5 hash of a file for did change check:
function md5Hash(filename) {
    let promise = new NodePromise(function resolver(resolve, reject) {
        let md5sum = crypto.createHash("md5");
        const input = fs.createReadStream(filename);
        input.on("readable", function () { //using readable should increase throughput.
            const data = input.read();
            if (data) {
                md5sum.update(data);
            } else {
                const d = md5sum.digest("hex");
                resolve(d);
            }
        });
        input.on("error", function (err) {
            reject(err);
        });
    });
    return promise;
}

//first get access_token:
let promise = refreshToken();

promise = promise.then(function getRootNode() {
    return requestMetadata("nodes?filters=isRoot:true");
});

promise = promise.then(function hangleToTargetPath(data) {
    let root = nodesFromData(data)[0]; //can we have multiple root nodes?
    let currentNode = root;
    let currentPath = "/";
    let remainingPathItems = config.targetPath.split("/");
    remainingPathItems.pop();
    remainingPathItems.shift();

    function getDown() {
        //debug("remainingPath: ", remainingPathItems);
        if (remainingPathItems.length === 0) {
            if (currentPath !== config.targetPath) {
                throw currentPath + " != " + config.targetPath + ". Somehow path hangling went wrong.";
            }
            return currentNode;
        }
        let innerPromise = listChildren(currentNode, "kind:FOLDER");
        innerPromise = innerPromise.then(function (children) {
            let found = false;
            children.forEach(function (child) {
                if (child.name === remainingPathItems[0]) {
                    //debug("Found next part: ", child);
                    currentNode = child;
                    currentPath += child.name + "/";
                    found = true;
                }
            });
            if (!found) {
                return createFolder(currentNode, remainingPathItems[0]);
            }
            remainingPathItems.shift();
            return getDown();
        });

        return innerPromise;
    }

    return getDown();
});

promise = promise.then(function allgood(result) {
    console.log("All good:", result);
}, function haderror(err) {
    console.log("Had error:", err);
});
<commit_msg>augment source path<commit_after>/**
 * Created by achim on 31.07.2017.
 */
/*jslint node: true, es6: true, white: true */
/*jshint esversion: 6 */

"use strict";

const NodePromise = require("promise");
const https = require("https");
const url = require("url");
const querystring = require("querystring");
const fs = require("fs");
const crypto = require("crypto");

//parameter files:
const auth = require("./auth.json");
const config = require("./config.json");
if (config.targetPath.charAt(config.targetPath.length -1) !== "/") {
    config.targetPath += "/";
}
if (config.sourcePath.charAt(config.sourcePath.length -1) !== "/") {
    config.sourcePath += "/";
}

function debug(...msgs) {
    if (config.debugging) {
        console.log(...msgs);
    }
}

//denodifications:
const readFilePromise = NodePromise.denodeify(fs.readFile);
const writeFilePromise = NodePromise.denodeify(fs.writeFile);

let authHeader;
let refreshToken;
function requestPromise(options, postData, decode = true, retry = 0) {
    //add auth header.
    if (authHeader) {
        if (options.headers) {
            options.headers.Authorization = authHeader;
        } else {
            options.headers = {"Authorization": authHeader};
        }
    }
    let promise = new NodePromise(function resolver(resolve, reject) {
        //debug("Sending request", options);
        let req = https.request(options, function callback(res) {
            let data = "";
            res.setEncoding("utf8");
            //debug("Headers:", res.headers);
            res.on("data", function (chunk) { data += chunk; });
            res.on("end", function () {
                //debug("Body: ", data);
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    if (decode) {
                        resolve(JSON.parse(data));
                    } else {
                        resolve(data);
                    }
                } else if (res.statusCode === 401 && !retry) {
                    //need to refresh token.
                    let innerPromise = refreshToken(true);
                    innerPromise = innerPromise.then(function retryRequest() { //retry request.
                        return requestPromise(options, postData, decode, retry + 1);
                    });
                    resolve(innerPromise);
                } else {
                    reject({msg: "Status code not 200: " + res.statusCode, data: data});
                }
            });
        });
        req.on("error", (err) => reject(err));
        //debug("Writing:", postData);
        req.end(postData);
    });

    return promise;
}

//request from metadata server
function requestMetadata(path, jsonData, decode) {
    let options = url.parse(auth.metadataUrl + path);
    let postData;
    if (jsonData) {
        postData = JSON.stringify(jsonData);
        options.headers = {"Content-Length": Buffer.byteLength(postData)};
        options.method = "POST";
    }
    return requestPromise(options, postData, decode);
}
//request from content server
function requestContent(path, decode) {
    let options = url.parse(auth.contentUrl + path);
    return requestPromise(options, undefined, decode);
}
//handle all token stuff. will also update authorization header.
refreshToken = function(realRefresh) {
    let promise;
    authHeader = "";
    if (!realRefresh) {
        promise = readFilePromise(config.accessTokenPath, "utf8");

        promise = promise.then(function gotToken(data) {
            let token = JSON.parse(data);
            debug("Got token from file");
            authHeader = "Bearer " + token.access_token;
            return token;
        }, function needToRefresh() {
            debug("No token file. Get new token.");
            return refreshToken(true);
        });
    } else {
        let options = url.parse(config.refreshProxyUrl);
        options.method = "POST";
        let postData = querystring.stringify({refresh_token: auth.refresh_token});
        options.headers = {"Content-Length": Buffer.byteLength(postData)};

        promise = requestPromise(options, postData, true);

        promise = promise.then(function storeToken(token) {
            debug("Got token from refresh.");
            authHeader = "Bearer " + token.access_token;
            return writeFilePromise(config.accessTokenPath, JSON.stringify(token, null, 4), "utf8");
        });
    }
    return promise;
};

function nodesFromData(data) {
    if (data.data.length >= 0) {
        return data.data;
    }
    if (data.length >= 0) {
        return data;
    }
    throw "No nodes found in data.";
}

function createFolder(parentNode, name) {
    debug("Creating " + name + " in " + (parentNode.name || "root"));
    let createUrl = "nodes?localId=GarfonsoImageSync";
    let jsonData = {
        name: name,
        kind: "FOLDER",
        parents: [parentNode.id]
    };
    return requestMetadata(createUrl, jsonData);
}

function listChildren(node, filter, children = [], nextToken = undefined) {
    let childrenUrl = "nodes/" + node.id + "/children";
    if (filter) {
        childrenUrl += "?filters=" + filter;
    }
    if (nextToken) {
        if (!filter) {
            childrenUrl += "?";
        } else {
            childrenUrl += "&";
        }
        childrenUrl += "startToken=" + nextToken;
    }
    let promise = requestMetadata(childrenUrl);

    promise = promise.then(function (res) {
        children = children.concat(nodesFromData(res));
        //debug("Got children: ", children);
        if (res.nextToken) {
            return listChildren(node, filter, children, res.nextToken);
        } else {
            return children;
        }
    });

    return promise;
}

//create md5 hash of a file for did change check:
function md5Hash(filename) {
    let promise = new NodePromise(function resolver(resolve, reject) {
        let md5sum = crypto.createHash("md5");
        const input = fs.createReadStream(filename);
        input.on("readable", function () { //using readable should increase throughput.
            const data = input.read();
            if (data) {
                md5sum.update(data);
            } else {
                const d = md5sum.digest("hex");
                resolve(d);
            }
        });
        input.on("error", function (err) {
            reject(err);
        });
    });
    return promise;
}

//first get access_token:
let promise = refreshToken();

promise = promise.then(function getRootNode() {
    return requestMetadata("nodes?filters=isRoot:true");
});

promise = promise.then(function hangleToTargetPath(data) {
    let root = nodesFromData(data)[0]; //can we have multiple root nodes?
    let currentNode = root;
    let currentPath = "/";
    let remainingPathItems = config.targetPath.split("/");
    remainingPathItems.pop();
    remainingPathItems.shift();

    function getDown() {
        //debug("remainingPath: ", remainingPathItems);
        if (remainingPathItems.length === 0) {
            if (currentPath !== config.targetPath) {
                throw currentPath + " != " + config.targetPath + ". Somehow path hangling went wrong.";
            }
            return currentNode;
        }
        let innerPromise = listChildren(currentNode, "kind:FOLDER");
        innerPromise = innerPromise.then(function (children) {
            let found = false;
            children.forEach(function (child) {
                if (child.name === remainingPathItems[0]) {
                    //debug("Found next part: ", child);
                    currentNode = child;
                    currentPath += child.name + "/";
                    found = true;
                }
            });
            if (!found) {
                return createFolder(currentNode, remainingPathItems[0]);
            }
            remainingPathItems.shift();
            return getDown();
        });

        return innerPromise;
    }

    return getDown();
});

promise = promise.then(function allgood(result) {
    console.log("All good:", result);
}, function haderror(err) {
    console.log("Had error:", err);
});
<|endoftext|>


<commit_before>
/*!
 * Connect - responseTime
 * Copyright(c) 2011 TJ Holowaychuk
 * MIT Licensed
 */

/**
 * Module dependencies
 */

var onHeaders = require('on-headers')

/**
 * Reponse time:
 *
 * Adds the `X-Response-Time` header displaying the response
 * duration in milliseconds.
 *
 * @return {Function}
 * @api public
 */

module.exports = function responseTime(){
  return function(req, res, next){
    next = next || noop;
    if (res._responseTime) return next();
    var start = Date.now();
    res._responseTime = true;

    onHeaders(res, function () {
      var duration = Date.now() - start
      this.setHeader('X-Response-Time', duration + 'ms')
    })

    next();
  };
};

function noop() {}
<commit_msg>make timer immune to clock drift and more precise<commit_after>
/*!
 * Connect - responseTime
 * Copyright(c) 2011 TJ Holowaychuk
 * MIT Licensed
 */

/**
 * Module dependencies
 */

var onHeaders = require('on-headers')

/**
 * Reponse time:
 *
 * Adds the `X-Response-Time` header displaying the response
 * duration in milliseconds.
 *
 * @return {Function}
 * @api public
 */

module.exports = function responseTime(){
  return function(req, res, next){
    next = next || noop;
    if (res._responseTime) return next();
    res._responseTime = true;

    var startAt = process.hrtime()

    onHeaders(res, function () {
      var diff = process.hrtime(startAt)
      var ms = diff[0] * 1e3 + diff[1] * 1e-6
      this.setHeader('X-Response-Time', ms.toFixed(3) + 'ms')
    })

    next();
  };
};

function noop() {}
<|endoftext|>


<commit_before>'use strict';

var argv = require('minimist')(process.argv.slice(2), {
  alias: {
    b: ['database', 'db'],
    s: ['db-size', 'size'],
    d: ['duration'],
    o: ['options'],
    l: ['db-list', 'list']
  },
  default: {
    s: 5000,
    d: 5
  }
});

if (argv.list) {
  var path    = require('path');
  var fs      = require('fs');
  var plugDir = path.join(__dirname, 'plug');

  fs.readdir(plugDir, function (err, items) {
    if (err) { throw err; }

    (function list() {
      var item = items.pop();
      if (!item) { return; }

      fs.stat(path.join(plugDir, item), function (err, stat) {
        if (err) { console.error(err); }
        if (stat && stat.isDirectory()) { console.log(item); }
        list();
      });
    })();
  });
  return;
}

if (!argv.db) {
  console.error('No database provided');
  process.exit(1);
}

var faker = require('faker');
var db    = require('./plug/' + argv.db + '/index.js');

var id = 0;

function generate(callback) {
  var startTime = process.hrtime();
  var inserted  = 0;
  var errors    = 0;

  (function insert() {
    if (id >= argv.size) {
      var elapsed = process.hrtime(startTime);

      return callback(null, {
        elapsed: Math.round((elapsed[0] * 1e9 + elapsed[1]) / 1e6),
        inserted: inserted,
        errors: errors
      });
    }

    db.insert('identifier' + id++, {
      firstname: faker.name.firstName(),
      lastname: faker.name.lastName(),
      zipcode: faker.address.zipCode(),
      city: faker.address.city(),
      country: faker.address.country()
    }, function (err) {
      if (err) { errors++; }
      else     { inserted++; }

      setImmediate(insert);
    });
  })();
};

function bench(callback) {
  var stop        = false;
  var nbQueries   = 0;
  var nbErrors    = 0;
  var maxTime     = 0;
  var minTime     = Infinity;
  var averageTime = 0;
  var maxMemory   = 0;
  var minMemory   = Infinity;

  (function query() {
    var id = 'identifier' + (Math.floor(Math.random() * argv.size));
    var startTime = process.hrtime();

    var memoryUsage = process.memoryUsage().rss;
    minMemory = Math.min(minMemory, memoryUsage);
    maxMemory = Math.max(maxMemory, memoryUsage);

    db.get(id, function (err, entry) {
      var elapsed = process.hrtime(startTime);
      elapsed = elapsed[0] * 1e9 + elapsed[1];

      minTime = Math.min(minTime, elapsed);
      maxTime = Math.max(maxTime, elapsed);
      averageTime = averageTime ? (averageTime + elapsed) / 2 : elapsed;

      if (err) { nbErrors++; }
      else     { nbQueries++ }

      if (stop) {
        callback(null, {
          queries: nbQueries,
          errors: nbErrors,
          time: {
            min: Math.round(minTime / 1e3) / 1e3,
            max: Math.round(maxTime / 1e3) / 1e3,
            average: Math.round(averageTime / 1e3) / 1e3
          },
          memory: {
            min: Math.round(minMemory / 1024 / 1024 * 100) / 100,
            max: Math.round(maxMemory / 1024 / 1024 * 100) / 100
          }
        });
      } else {
        setImmediate(query);
      }
    });
  })();

  setTimeout(function() { stop = true; }, argv.duration * 1000);
};

console.log('[ %s ]', db.name);
console.log('Initializing database...');
db.init(argv.options ? JSON.parse(argv.options) : {}, function (err) {
  if (err) { throw err; }

  var startTime = process.hrtime();
  console.log('Generating dataset...');
  generate(function (err, res) {

    console.log('Starting bench');
    bench(function (err, result) {
      console.log('Bench finished\n');

      var queriesPerSecond = Math.round(result.queries / argv.duration);

      var min = Math.floor(res.elapsed / 60000).toString();
      var sec = Math.floor(res.elapsed / 1000 % 60000).toString();

      if (min.length == 1) { min = '0' + min; }
      if (sec.length == 1) { sec = '0' + sec; }

      console.log('Dataset');
      console.log('  Inserted: \t%d', res.inserted);
      console.log('  Failed: \t%d', res.errors);
      console.log('  Time: \t%s:%s', min, sec);

      console.log('Queries');
      console.log('  Successful: \t%d (%d per second)', result.queries, queriesPerSecond);
      console.log('  Failed: \t%d', result.errors);

      console.log('Queries time')
      console.log('  Minimum: \t%d ms', result.time.min);
      console.log('  Maximum: \t%d ms', result.time.max);
      console.log('  Average: \t%d ms', result.time.average);

      console.log('Memory usage')
      console.log('  Minimum: \t%d MiB', result.memory.min);
      console.log('  Maximum: \t%d MiB', result.memory.max);
    });
  });
});<commit_msg>add bench time<commit_after>'use strict';

var argv = require('minimist')(process.argv.slice(2), {
  alias: {
    b: ['database', 'db'],
    s: ['db-size', 'size'],
    d: ['duration'],
    o: ['options'],
    l: ['db-list', 'list']
  },
  default: {
    s: 5000,
    d: 5
  }
});

if (argv.list) {
  var path    = require('path');
  var fs      = require('fs');
  var plugDir = path.join(__dirname, 'plug');

  fs.readdir(plugDir, function (err, items) {
    if (err) { throw err; }

    (function list() {
      var item = items.pop();
      if (!item) { return; }

      fs.stat(path.join(plugDir, item), function (err, stat) {
        if (err) { console.error(err); }
        if (stat && stat.isDirectory()) { console.log(item); }
        list();
      });
    })();
  });
  return;
}

if (!argv.db) {
  console.error('No database provided');
  process.exit(1);
}

var faker = require('faker');
var db    = require('./plug/' + argv.db + '/index.js');

var id = 0;

function generate(callback) {
  var inserted  = 0;
  var errors    = 0;

  (function insert() {
    if (id >= argv.size) {
      return callback(null, {
        inserted: inserted,
        errors: errors
      });
    }

    db.insert('identifier' + id++, {
      firstname: faker.name.firstName(),
      lastname: faker.name.lastName(),
      zipcode: faker.address.zipCode(),
      city: faker.address.city(),
      country: faker.address.country()
    }, function (err) {
      if (err) { errors++; }
      else     { inserted++; }

      setImmediate(insert);
    });
  })();
};

function bench(callback) {
  var stop        = false;
  var nbQueries   = 0;
  var nbErrors    = 0;
  var maxTime     = 0;
  var minTime     = Infinity;
  var averageTime = 0;
  var maxMemory   = 0;
  var minMemory   = Infinity;

  (function query() {
    var id = 'identifier' + (Math.floor(Math.random() * argv.size));
    var startTime = process.hrtime();

    var memoryUsage = process.memoryUsage().rss;
    minMemory = Math.min(minMemory, memoryUsage);
    maxMemory = Math.max(maxMemory, memoryUsage);

    db.get(id, function (err, entry) {
      var elapsed = process.hrtime(startTime);
      elapsed = elapsed[0] * 1e9 + elapsed[1];

      minTime = Math.min(minTime, elapsed);
      maxTime = Math.max(maxTime, elapsed);
      averageTime = averageTime ? (averageTime + elapsed) / 2 : elapsed;

      if (err) { nbErrors++; }
      else     { nbQueries++ }

      if (stop) {
        callback(null, {
          queries: nbQueries,
          errors: nbErrors,
          time: {
            min: Math.round(minTime / 1e3) / 1e3,
            max: Math.round(maxTime / 1e3) / 1e3,
            average: Math.round(averageTime / 1e3) / 1e3
          },
          memory: {
            min: Math.round(minMemory / 1024 / 1024 * 100) / 100,
            max: Math.round(maxMemory / 1024 / 1024 * 100) / 100
          }
        });
      } else {
        setImmediate(query);
      }
    });
  })();

  setTimeout(function() { stop = true; }, argv.duration * 1000);
};

console.log('[ %s ]', db.name);
console.log('Initializing database...');
db.init(argv.options ? JSON.parse(argv.options) : {}, function (err) {
  if (err) { throw err; }

  var startTime = process.hrtime();
  console.log('Generating dataset...');

  generate(function (err, res) {

    var elapsed = process.hrtime(startTime);
    elapsed = (elapsed[0] * 1e9 + elapsed[1]) / 1e6;

    var genMin = Math.floor(elapsed / 60000).toString();
    var genSec = Math.floor(elapsed / 1000 % 60000).toString();
    if (genMin.length == 1) { genMin = '0' + genMin; }
    if (genSec.length == 1) { genSec = '0' + genSec; }

    startTime = process.hrtime();
    console.log('Starting bench');

    bench(function (err, result) {

      elapsed = process.hrtime(startTime);
      elapsed = (elapsed[0] * 1e9 + elapsed[1]) / 1e6;
      var benchMin = Math.floor(elapsed / 60000).toString();
      var benchSec = Math.floor(elapsed / 1000 % 60000).toString();
      if (benchMin.length == 1) { benchMin = '0' + benchMin; }
      if (benchSec.length == 1) { benchSec = '0' + benchSec; }

      console.log('Bench finished in %d minutes and %d seconds\n', benchMin, benchSec);

      var queriesPerSecond = Math.round(result.queries / argv.duration);

      console.log('Dataset');
      console.log('  Inserted: \t%d', res.inserted);
      console.log('  Failed: \t%d', res.errors);
      console.log('  Time: \t%s:%s', genMin, genSec);

      console.log('Queries');
      console.log('  Successful: \t%d (%d per second)', result.queries, queriesPerSecond);
      console.log('  Failed: \t%d', result.errors);

      console.log('Queries time')
      console.log('  Minimum: \t%d ms', result.time.min);
      console.log('  Maximum: \t%d ms', result.time.max);
      console.log('  Average: \t%d ms', result.time.average);

      console.log('Memory usage')
      console.log('  Minimum: \t%d MiB', result.memory.min);
      console.log('  Maximum: \t%d MiB', result.memory.max);
    });
  });
});<|endoftext|>


<commit_before>var _methods = require('http').METHODS

module.exports = function(routes, methods) {

  if (typeof methods == "undefined") {
    methods = _methods
  } else if (typeof methods == "string") {
    methods = methods.toUpperCase()
    if (_methods.indexOf(methods) === -1) {
      console.log("")
      return
    }
  } else if (typeof methods == "object" && Array.isArray(methods)) {
    var errors = [];
    var initialCount = methods.length
    methods = methods.map(function(method) {
      method = method.toUpperCase()
      if (_methods.indexOf(method) === -1) {
        errors.push(method)
        return
      }
      return method
    })

    if (errors.length > 0) {
      console.log("The following Methods that were provided are not supported and have been omitted: " + errors.join(", "))
      if (errors.length == initialCount) {
        console.log("")
        return
      }
    }
  } else {
    // ERROR
    return
  }

  var list = [],
    route

  routes.forEach(function(middleware) {
    if (middleware.route) {
      var associatedMethod = Object.keys(middleware.route.methods)[0].toUpperCase() //object should only have one key - the method
      if (methods.indexOf(associatedMethod) !== -1) {
        route = {}
        route.method = associatedMethod
        route.path = middleware.route.path

        list.push(route)
      }
    } else if (middleware.name === "router") {

      /** gets the first part of the uri that app._router.stack forgets
       * for example:
       *     app.use('/users', users)
       * would ommit the '/users' part in the uris - not giving you the full path
       */
      var mount = middleware.regexp.toString().match(/([\/\\A-Za-z0-9-_]+)\?/)[1]
      mount = mount.replace(/\\/g, "")
      mount = mount.replace(/\/$/, "")

      middleware.handle.stack.forEach(function(handler) {
        var associatedMethod = Object.keys(handler.route.methods)[0].toUpperCase() //object should only have one key - the method
        if (methods.indexOf(associatedMethod) !== -1) {
          route = {}
          route.method = associatedMethod
          route.path = mount + handler.route.path

          list.push(route)
        } else {
          return
        }
      })
    }
  })

  return list
}
<commit_msg>added error throws<commit_after>var _methods = require('http').METHODS

module.exports = function(routes, methods) {

  if (typeof methods == "undefined") {
    methods = _methods
  } else if (typeof methods == "string") {
    methods = methods.toUpperCase()
    if (_methods.indexOf(methods) === -1) {
      throw new Error("The method you have provided: '" + methods + "' is not supported. Please use one of the following methods:\r\n\r\n" + _methods.join(", "))
      return
    }
  } else if (typeof methods == "object" && Array.isArray(methods)) {
    var errors = [];
    var initialCount = methods.length
    methods = methods.map(function(method) {
      method = method.toUpperCase()
      if (_methods.indexOf(method) === -1) {
        errors.push(method)
        return
      }
      return method
    })

    if (errors.length > 0) {
      console.log("The following Methods that were provided are not supported and have been omitted: " + errors.join(", "))
      if (errors.length == initialCount) {
        throw new Error("None of the provided methods are supported.")
        return
      }
    }
  } else {
    throw new TypeError("The methods parameter must provide either a String, or an Array of Strings.")
    return
  }

  var list = [],
    route

  routes.forEach(function(middleware) {
    if (middleware.route) {
      var associatedMethod = Object.keys(middleware.route.methods)[0].toUpperCase() //object should only have one key - the method
      if (methods.indexOf(associatedMethod) !== -1) {
        route = {}
        route.method = associatedMethod
        route.path = middleware.route.path

        list.push(route)
      }
    } else if (middleware.name === "router") {

      /** gets the first part of the uri that app._router.stack forgets
       * for example:
       *     app.use('/users', users)
       * would ommit the '/users' part in the uris - not giving you the full path
       */
      var mount = middleware.regexp.toString().match(/([\/\\A-Za-z0-9-_]+)\?/)[1]
      mount = mount.replace(/\\/g, "")
      mount = mount.replace(/\/$/, "")

      middleware.handle.stack.forEach(function(handler) {
        var associatedMethod = Object.keys(handler.route.methods)[0].toUpperCase() //object should only have one key - the method
        if (methods.indexOf(associatedMethod) !== -1) {
          route = {}
          route.method = associatedMethod
          route.path = mount + handler.route.path

          list.push(route)
        } else {
          return
        }
      })
    }
  })

  return list
}
<|endoftext|>


<commit_before>Concrete.UI.Workbench = {

  // Toplevel setup of an editor workbench.
  // Creates editor views and connects event and command handlers.
  //
  // Options:
  //
  // moduleBrowser: if set to true, add module browser in side pane, default: true
  // moduleBrowserOptions: options passed to the module browser, default: none
  // moduleEditorOptions: options passed to the module editor, default: none
  //
  setup: function(options) {
    options = options || {};

    var layoutManager = new Concrete.UI.LayoutManager();

    var toolbar = new Concrete.UI.Toolbar(layoutManager.toolbar);

    var mp = new Concrete.MetamodelProvider(Metamodel);

    var index = [];
    var eip = new Concrete.IndexBasedExternalIdentifierProvider(index, mp);

    var editorOptions = options.moduleEditorOptions || {};
    editorOptions.onFollowReference = function(module, ident) {
      jumpReference(module, ident);
    };
    var moduleEditor = new Concrete.UI.ModuleEditor(layoutManager.main, eip, mp, editorOptions);

    var browserOptions = options.moduleBrowserOptions || {};
    browserOptions.onOpenModule = function(module, ident) {
      jumpReference(module, ident);
    };
    var moduleBrowser = new Concrete.UI.ModuleBrowser(layoutManager.sidebar, IndexMetamodel, browserOptions);

    var openElementDialog = new Concrete.UI.OpenElementDialog(eip, {
      onOpenReference: function(module, ident) {
        jumpReference(module, ident);
      }
    });

    var searchReplaceDialog = new Concrete.UI.SearchReplaceDialog({
      metamodelProvider: mp
      });

    // Event Handler

    Event.observe(window, 'click', function(event) {
      moduleEditor.handleEvent(event);
      moduleBrowser.handleEvent(event);
    });
    Event.observe(window, 'dblclick', function(event) {
      moduleBrowser.handleEvent(event);
    });
    Event.observe(window, 'keydown', function(event) {
      if (toolbar.handleEvent(event)) {}
      else {
        moduleEditor.handleEvent(event);
        moduleBrowser.handleEvent(event);
      }
    });
    Event.observe(window, 'mousedown', function(event) {
      layoutManager.handleEvent(event);
    });
    Event.observe(window, 'mouseup', function(event) {
      layoutManager.handleEvent(event);
    });
    Event.observe(window, 'mousemove', function(event) {
      if (layoutManager.handleEvent(event)) {}
      else {
        moduleEditor.handleEvent(event);
        moduleBrowser.handleEvent(event);
      }
    });

    // Commands

    toolbar.addCommand({buttonClass: "ct_save_button", hotkey: "ctrl+shift+S"}, function() {
      moduleEditor.save({
        onSuccess: function() {
          loadIndex();
        },
        onFailure: function() {
          alert("Save failed");
        }
      });
    });

    toolbar.addCommand({buttonClass: "ct_open_element_button", hotkey: "ctrl+shift+E"}, function() {
      openElementDialog.open(eip.getAllElementInfo());
    });

    toolbar.addCommand({buttonClass: "ct_search_replace_button", hotkey: "ctrl+shift+F"}, function() {
      searchReplaceDialog.open(moduleEditor.editor);
    });

    toolbar.addCommand({buttonClass: "ct_stop_server_button"}, function() {
      new Ajax.Request("/exit");
    });

    function jumpReference(module, ident) {
      var href = "#"+module+((ident && ":"+ident) || "");
      var lastm = window.location.href.match(/#.*/);
      if (href == lastm && lastm[0]) {
        // href doesn't change, call editor anyway to update selection in case it has changed
        moduleEditor.select(module, ident);
      }
      else {
        window.location.href = href;
      }
    }

    function loadIndex(options) {
      new Ajax.Request("/loadIndex", {
        method: "get",
        onSuccess: function(transport) {
          index.clear();
          var indexJson = transport.responseText.evalJSON();
          indexJson.sortBy(function(m) {return m.name}).each(function(m) {
            index.push(m);
          });
          moduleBrowser.loadIndex(index);
          if (options && options.onIndexLoaded) options.onIndexLoaded();
        }
      });
    }

    window.onresize = function() {
      layoutManager.layout();
    };

    window.onhashchange = function() {
      var match = window.location.href.match(/#([^:]+):?(.*)/)
      var module = match && match[1];
      var ident = match && match[2];
      moduleEditor.select(module, ident);
    };

    // first update after loading
    window.onresize();
    loadIndex({onIndexLoaded: function() {
      window.onhashchange();
    }});
  }
};

<commit_msg>explicitly pass metamodels<commit_after>Concrete.UI.Workbench = {

  // Toplevel setup of an editor workbench.
  // Creates editor views and connects event and command handlers.
  //
  // Options:
  //
  // moduleBrowserOptions: options passed to the module browser, default: none
  // moduleEditorOptions: options passed to the module editor, default: none
  //
  setup: function(metamodel, indexMetamodel, options) {
    options = options || {};

    var layoutManager = new Concrete.UI.LayoutManager();

    var toolbar = new Concrete.UI.Toolbar(layoutManager.toolbar);

    var mp = new Concrete.MetamodelProvider(metamodel);

    var index = [];
    var eip = new Concrete.IndexBasedExternalIdentifierProvider(index, mp);

    var editorOptions = options.moduleEditorOptions || {};
    editorOptions.onFollowReference = function(module, ident) {
      jumpReference(module, ident);
    };
    var moduleEditor = new Concrete.UI.ModuleEditor(layoutManager.main, eip, mp, editorOptions);

    var browserOptions = options.moduleBrowserOptions || {};
    browserOptions.onOpenModule = function(module, ident) {
      jumpReference(module, ident);
    };
    var moduleBrowser = new Concrete.UI.ModuleBrowser(layoutManager.sidebar, indexMetamodel, browserOptions);

    var openElementDialog = new Concrete.UI.OpenElementDialog(eip, {
      onOpenReference: function(module, ident) {
        jumpReference(module, ident);
      }
    });

    var searchReplaceDialog = new Concrete.UI.SearchReplaceDialog({
      metamodelProvider: mp
      });

    // Event Handler

    Event.observe(window, 'click', function(event) {
      moduleEditor.handleEvent(event);
      moduleBrowser.handleEvent(event);
    });
    Event.observe(window, 'dblclick', function(event) {
      moduleBrowser.handleEvent(event);
    });
    Event.observe(window, 'keydown', function(event) {
      if (toolbar.handleEvent(event)) {}
      else {
        moduleEditor.handleEvent(event);
        moduleBrowser.handleEvent(event);
      }
    });
    Event.observe(window, 'mousedown', function(event) {
      layoutManager.handleEvent(event);
    });
    Event.observe(window, 'mouseup', function(event) {
      layoutManager.handleEvent(event);
    });
    Event.observe(window, 'mousemove', function(event) {
      if (layoutManager.handleEvent(event)) {}
      else {
        moduleEditor.handleEvent(event);
        moduleBrowser.handleEvent(event);
      }
    });

    // Commands

    toolbar.addCommand({buttonClass: "ct_save_button", hotkey: "ctrl+shift+S"}, function() {
      moduleEditor.save({
        onSuccess: function() {
          loadIndex();
        },
        onFailure: function() {
          alert("Save failed");
        }
      });
    });

    toolbar.addCommand({buttonClass: "ct_open_element_button", hotkey: "ctrl+shift+E"}, function() {
      openElementDialog.open(eip.getAllElementInfo());
    });

    toolbar.addCommand({buttonClass: "ct_search_replace_button", hotkey: "ctrl+shift+F"}, function() {
      searchReplaceDialog.open(moduleEditor.editor);
    });

    toolbar.addCommand({buttonClass: "ct_stop_server_button"}, function() {
      new Ajax.Request("/exit");
    });

    function jumpReference(module, ident) {
      var href = "#"+module+((ident && ":"+ident) || "");
      var lastm = window.location.href.match(/#.*/);
      if (href == lastm && lastm[0]) {
        // href doesn't change, call editor anyway to update selection in case it has changed
        moduleEditor.select(module, ident);
      }
      else {
        window.location.href = href;
      }
    }

    function loadIndex(options) {
      new Ajax.Request("/loadIndex", {
        method: "get",
        onSuccess: function(transport) {
          index.clear();
          var indexJson = transport.responseText.evalJSON();
          indexJson.sortBy(function(m) {return m.name}).each(function(m) {
            index.push(m);
          });
          moduleBrowser.loadIndex(index);
          if (options && options.onIndexLoaded) options.onIndexLoaded();
        }
      });
    }

    window.onresize = function() {
      layoutManager.layout();
    };

    window.onhashchange = function() {
      var match = window.location.href.match(/#([^:]+):?(.*)/)
      var module = match && match[1];
      var ident = match && match[2];
      moduleEditor.select(module, ident);
    };

    // first update after loading
    window.onresize();
    loadIndex({onIndexLoaded: function() {
      window.onhashchange();
    }});
  }
};

<|endoftext|>