<commit_before>#! /usr/bin/env node

import { exec } from 'child_process';
import path from 'path';
import program from 'commander';
import pkg from '../package.json';

import gulp from 'gulp';
import gulpLogEvents from './gulpLogEvents';
import changed from 'gulp-changed';
import babel from 'gulp-babel';
import sourcemaps from 'gulp-sourcemaps';
import gulpif from 'gulp-if';
import notify from 'gulp-notify';
import nodemon from 'gulp-nodemon';

/**
 * Specify gulp tasks
 */

// since we are calling gulp tasks from node scripts
// instead of `gulp` command, we use the logging
// function extracted from gulp's source code
// to keep logs working properly
gulpLogEvents(gulp);

// watching source files
gulp.task('watch', () => {
  return gulp
    .watch('./src/**/*.js', ['build']);
});

// build source files
gulp.task('build', () => {
  return gulp
    .src('./src/**/*.js')
    .pipe(changed('./build/debug'))
    .pipe(gulpif(env.d, sourcemaps.init()))
      .pipe(babel({
        presets: [
          'es2015',
          'stage-0',
          'stage-1',
        ],
      }))
      .on('error', notify.onError({
        title: 'babel fail',
        message: '<%= error.message %>',
      }))
    .pipe(gulpif(env.d, sourcemaps.write({
      includeContent: false,
      sourceRoot: (file) => {
        return path.join(process.cwd(), 'src');
      },
    })))
    .pipe(gulp.dest('./build/debug'));
});

gulp.task('nodemon', (cb) => {
  if (env.d) {
    let started = false;

    return nodemon({
      script: 'build/debug/app.js',
      ext: 'js',
      env: {
        NODE_ENV: program.env,
      },
      ignore: [
        'gulpfile.js',
        'node_modules/**/*',
        'src/**/*',
        'build/debug/public/js/*/bundle.js',
        'build/debug/public/js/common.js',
        'build/release/**/*',
        'build/test/**/*',
      ],
    })
    .on('start', () => {
      if (!started) {
        cb();
        started = true;
      }
    })
    .on('restart', () => {
    });
  } else {
    cb();
  }
});

// run gulp tasks
gulp.task('default', () => {
  gulp.start('build', 'nodemon', 'watch');
});

/**
 * Definition of commands
 */

program
  .version(pkg.version)
  .usage('[options]')
  .option(
    '-e, --env <env>',
    'specify NODE_ENV (development|test|production)',
    'development')
  .option(
    '-w, --watch',
    'watching the changes of files',
    false);

const env = {
  d: program.env === 'development',
  t: program.env === 'test',
  p: program.env === 'production',
};

// to customize command name in help information
// ref: https://github.com/tj/commander.js/issues/466
process.argv[1] = 'sd';
program.parse(process.argv);

if (!program.args.length) {
  gulp.start('default');
}<commit_msg>Get `--watch` switch working<commit_after>#! /usr/bin/env node

import { exec } from 'child_process';
import path from 'path';
import program from 'commander';
import pkg from '../package.json';

import gulp from 'gulp';
import gulpLogEvents from './gulpLogEvents';
import changed from 'gulp-changed';
import babel from 'gulp-babel';
import sourcemaps from 'gulp-sourcemaps';
import gulpif from 'gulp-if';
import notify from 'gulp-notify';
import nodemon from 'gulp-nodemon';

/**
 * Specify gulp tasks
 */

// since we are calling gulp tasks from node scripts
// instead of `gulp` command, we use the logging
// function extracted from gulp's source code
// to keep logs working properly
gulpLogEvents(gulp);

// watching source files
gulp.task('watch', () => {
  if (program.watch) {
    return gulp
      .watch('./src/**/*.js', ['build']);
  }
});

// build source files
gulp.task('build', () => {
  return gulp
    .src('./src/**/*.js')
    .pipe(gulpif(program.watch, changed('./build/debug')))
    .pipe(gulpif(env.d, sourcemaps.init()))
      .pipe(babel({
        presets: [
          'es2015',
          'stage-0',
          'stage-1',
        ],
      }))
      .on('error', notify.onError({
        title: 'babel fail',
        message: '<%= error.message %>',
      }))
    .pipe(gulpif(env.d, sourcemaps.write({
      includeContent: false,
      sourceRoot: (file) => {
        return path.join(process.cwd(), 'src');
      },
    })))
    .pipe(gulp.dest('./build/debug'));
});

gulp.task('nodemon', (cb) => {
  if (env.d) {
    let started = false;

    return nodemon({
      script: 'build/debug/app.js',
      ext: 'js',
      env: {
        NODE_ENV: program.env,
      },
      ignore: [
        'gulpfile.js',
        'node_modules/**/*',
        'src/**/*',
        'build/debug/public/js/*/bundle.js',
        'build/debug/public/js/common.js',
        'build/release/**/*',
        'build/test/**/*',
      ],
    })
    .on('start', () => {
      if (!started) {
        cb();
        started = true;
      }
    })
    .on('restart', () => {
    });
  } else {
    cb();
  }
});

// run gulp tasks
gulp.task('default', () => {
  gulp.start('build', 'nodemon', 'watch');
});

/**
 * Definition of commands
 */

program
  .version(pkg.version)
  .usage('[options]')
  .option(
    '-e, --env <env>',
    'specify NODE_ENV (development|test|production)',
    'development')
  .option(
    '-w, --watch',
    'watching the changes of files',
    false);

const env = {
  d: program.env === 'development',
  t: program.env === 'test',
  p: program.env === 'production',
};

// to customize command name in help information
// ref: https://github.com/tj/commander.js/issues/466
process.argv[1] = 'sd';
program.parse(process.argv);

if (!program.args.length) {
  gulp.start('default');
}<|endoftext|>


<commit_before>/* Magic Mirror
 * Fetcher
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var FeedMe = require("feedme");
var request = require("request");
var iconv = require("iconv-lite");

/* Fetcher
 * Responsible for requesting an update on the set interval and broadcasting the data.
 *
 * attribute url string - URL of the news feed.
 * attribute reloadInterval number - Reload interval in milliseconds.
 */

var Fetcher = function(url, reloadInterval, encoding) {
	var self = this;
	if (reloadInterval < 1000) {
		reloadInterval = 1000;
	}

	var reloadTimer = null;
	var items = [];

	var fetchFailedCallback = function() {};
	var itemsReceivedCallback = function() {};

	/* private methods */

	/* fetchNews()
	 * Request the new items.
	 */

	var fetchNews = function() {
		clearTimeout(reloadTimer);
		reloadTimer = null;
		items = [];

		var parser = new FeedMe();

		parser.on("item", function(item) {

			var title = item.title;
			var description = item.description || item.summary || item.content || '';
			var pubdate = item.pubdate || item.published || item.updated;

			if (title && description && pubdate) {

				var regex = /(<([^>]+)>)/ig;
				description = description.replace(regex, "");

				items.push({
					title: title,
					description: description,
					pubdate: pubdate,
				});

			} else {

				console.log("Can't parse feed item:");
				console.log(item);

			}
		});

		parser.on("end", function() {
			self.broadcastItems();
			scheduleTimer();
		});

		parser.on("error", function(error) {
			fetchFailedCallback(self, error);
			scheduleTimer();
		});

		request({uri: url, encoding: null}).pipe(iconv.decodeStream(encoding)).pipe(parser);

	};

	/* scheduleTimer()
	 * Schedule the timer for the next update.
	 */

	var scheduleTimer = function() {
		//console.log('Schedule update timer.');
		clearTimeout(reloadTimer);
		reloadTimer = setTimeout(function() {
			fetchNews();
		}, reloadInterval);
	};

	/* public methods */

	/* setReloadInterval()
	 * Update the reload interval, but only if we need to increase the speed.
	 *
	 * attribute interval number - Interval for the update in milliseconds.
	 */
	this.setReloadInterval = function(interval) {
		if (interval > 1000 && interval < reloadInterval) {
			reloadInterval = interval;
		}
	};

	/* startFetch()
	 * Initiate fetchNews();
	 */
	this.startFetch = function() {
		fetchNews();
	};

	/* broadcastItems()
	 * Broadcast the exsisting items.
	 */
	this.broadcastItems = function() {
		if (items.length <= 0) {
			//console.log('No items to broadcast yet.');
			return;
		}
		//console.log('Broadcasting ' + items.length + ' items.');
		itemsReceivedCallback(self);
	};

	this.onReceive = function(callback) {
		itemsReceivedCallback = callback;
	};

	this.onError = function(callback) {
		fetchFailedCallback = callback;
	};

	this.url = function() {
		return url;
	};

	this.items = function() {
		return items;
	};
};

module.exports = Fetcher;
<commit_msg>Add user agent to request. Fix: 231<commit_after>/* Magic Mirror
 * Fetcher
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var FeedMe = require("feedme");
var request = require("request");
var iconv = require("iconv-lite");

/* Fetcher
 * Responsible for requesting an update on the set interval and broadcasting the data.
 *
 * attribute url string - URL of the news feed.
 * attribute reloadInterval number - Reload interval in milliseconds.
 */

var Fetcher = function(url, reloadInterval, encoding) {
	var self = this;
	if (reloadInterval < 1000) {
		reloadInterval = 1000;
	}

	var reloadTimer = null;
	var items = [];

	var fetchFailedCallback = function() {};
	var itemsReceivedCallback = function() {};

	/* private methods */

	/* fetchNews()
	 * Request the new items.
	 */

	var fetchNews = function() {
		clearTimeout(reloadTimer);
		reloadTimer = null;
		items = [];

		var parser = new FeedMe();

		parser.on("item", function(item) {

			var title = item.title;
			var description = item.description || item.summary || item.content || '';
			var pubdate = item.pubdate || item.published || item.updated;

			if (title && description && pubdate) {

				var regex = /(<([^>]+)>)/ig;
				description = description.replace(regex, "");

				items.push({
					title: title,
					description: description,
					pubdate: pubdate,
				});

			} else {

				console.log("Can't parse feed item:");
				console.log(item);

			}
		});

		parser.on("end", function() {
			self.broadcastItems();
			scheduleTimer();
		});

		parser.on("error", function(error) {
			fetchFailedCallback(self, error);
			scheduleTimer();
		});

		var headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A'};
		request({uri: url, encoding: null, headers: headers}).pipe(iconv.decodeStream(encoding)).pipe(parser);

	};

	/* scheduleTimer()
	 * Schedule the timer for the next update.
	 */

	var scheduleTimer = function() {
		//console.log('Schedule update timer.');
		clearTimeout(reloadTimer);
		reloadTimer = setTimeout(function() {
			fetchNews();
		}, reloadInterval);
	};

	/* public methods */

	/* setReloadInterval()
	 * Update the reload interval, but only if we need to increase the speed.
	 *
	 * attribute interval number - Interval for the update in milliseconds.
	 */
	this.setReloadInterval = function(interval) {
		if (interval > 1000 && interval < reloadInterval) {
			reloadInterval = interval;
		}
	};

	/* startFetch()
	 * Initiate fetchNews();
	 */
	this.startFetch = function() {
		fetchNews();
	};

	/* broadcastItems()
	 * Broadcast the exsisting items.
	 */
	this.broadcastItems = function() {
		if (items.length <= 0) {
			//console.log('No items to broadcast yet.');
			return;
		}
		//console.log('Broadcasting ' + items.length + ' items.');
		itemsReceivedCallback(self);
	};

	this.onReceive = function(callback) {
		itemsReceivedCallback = callback;
	};

	this.onError = function(callback) {
		fetchFailedCallback = callback;
	};

	this.url = function() {
		return url;
	};

	this.items = function() {
		return items;
	};
};

module.exports = Fetcher;
<|endoftext|>


<commit_before>var expect = require('chai').expect;

function toNumber(word){
  if ( word === "zero" ){
    return 0;
  }
  if ( word === "one" ){
    return 1;
  }
  if ( word === "two" ){
    return 2;
  }
  if ( word === "three" ){
    return 3;
  }
  if ( word === "four" ){
    return 4;
  }
  if ( word === "five" ){
    return 5;
  }
  if ( word === "six" ){
    return 6;
  }
  if ( word === "seven" ){
    return 7;
  }
  if ( word === "eight" ){
    return 8;
  }
  if ( word === "nine" ){
    return 9;
  }

}

function add(a, b){
  if ( a === "zero" && b === "zero"){
    var a = 0;
    var b = 0;
    return a + b;
  }
  if ( a === "zero" && b === "one"){
    var a = 0;
    var b = 1;
    return a + b;
  }
  if ( a === "zero" && b === "two"){
    var a = 0;
    var b = 2;
    return a + b;
  }
  if ( a === "zero" && b === "three"){
    return 3;
  }
  if ( a === "zero" && b === "four"){
    return 4;
  }
  if ( a === "zero" && b === "five"){
    return 5;
  }
  if ( a === "zero" && b === "six"){
    return 6;
  }
  if ( a === "zero" && b === "seven"){
    return 7;
  }
  if ( a === "zero" && b === "eight"){
    return 8;
  }
  if ( a === "zero" && b === "nine"){
    return 9;
  }
  if ( a === "one" && b === "zero"){
    var a = 1;
    var b = 0;
    return a + b;
  }
  if ( a === "one" && b === "one"){
    var a = 1;
    var b = 1;
    return a + b;
  }
  if ( a === "one" && b === "two"){
    var a = 1;
    var b = 2;
    return a + b;
  }
  if ( a === "one" && b === "three"){
    var a = 1;
    var b = 3;
    return a + b;
  }
  if ( a === "one" && b === "four"){
    var a = 1;
    var b = 4;
  }
  if ( a === "one" && b === "five"){
    var a = 1;
    var b = 5;
  }
  if ( a === "one" && b === "six"){
    var a = 1;
    var b = 6;
  }
  if ( a === "one" && b === "seven"){
    var a = 1;
    var b = 7;
  }
  if ( a === "one" && b === "eight"){
    var a = 1;
    var b = 8;
  }
  if ( a === "one" && b === "nine"){
    var a = 1;
    var b = 9;
  }
  if ( a === "two" && b === "zero"){
    var a = 2;
    var b = 0;
  }
  if ( a === "two" && b === "one"){
    var a = 2;
    var b = 1;
  }
  if ( a === "two" && b === "two"){
    var a = 2;
    var b = 2;
  }
  if ( a === "two" && b === "three"){
    var a = 2;
    var b = 3;
  }
  if ( a === "two" && b === "four"){
    var a = 2;
    var b = 4;
  }
  if ( a === "two" && b === "five"){
    var a = 2;
    var b = 5;
  }
  if ( a === "two" && b === "six"){
    var a = 2;
    var b = 6;
  }
  if ( a === "two" && b === "seven"){
    var a = 2;
    var b = 7;
  }
  if ( a === "two" && b === "eight"){
    var a = 2;
    var b = 8;
  }
  if ( a === "two" && b === "nine"){
    var a = 2;
    var b = 9;
  }
  if ( a === "three" && b === "zero"){
    var a = 3;
    var b = 0;
  }
  if ( a === "three" && b === "one"){
    var a = 3;
    var b = 1;
  }
  if ( a === "three" && "two"){
    var a = 3;
    var b = 2;
  }
  if ( a === "three" && "three"){
    var a = 3;
    var b = 3;
  }
  if ( a === "three" && "four"){
    var a = 3;
    var b = 4;
  }
  if ( a === "three" && "five"){
    var a = 3;
    var b = 5;
  }
  if ( a === "three" && "six"){
    var a = 3;
    var b = 6;
  }
  if ( a === "three" && "seven"){
    var a = 3;
    var b = 7;
  }
  if ( a === "three" && "eight"){
    var a = 3;
    var b = 8;
  }
  if ( a === "three" && "nine"){
    var a = 3;
    var b = 9;
  }
  if ( a === "four" && "zero"){
    var a = 4;
    var b = 0;
  }
  if ( a === "four" && "one"){
    var a = 4;
    var b = 1;
  }
  if ( a === "four" && b === "two"){
    var a = 4;
    var b = 2;
  }
  if ( a === "four" && b === "three"){
    var a = 4;
    var b = 3;
  }
  if ( a === "four" && b === "four"){
    var a = 4;
    var b = 4;
  }
  if ( a === "four" && b === "five"){
    var a = 4;
    var b = 5;
  }
  if (a === "four" && b === "six"){
    var a = 4;
    var b = 6;
  }
  if (a === "four" && b === "seven"){
    var a = 4;
    var b = 7;
  }
  if (a === "four" && b === "eight"){
    var a = 4;
    var b = 8;
  }
  if ( a === "four" && b === "nine"){
    var a = 4;
    var b = 9;
  }
  if ( a === "five" && b === "zero"){
    var a = 5;
    var b = 0;
  }
  if ( a === "five" && b === "one"){
    var a = 5;
    var b = 1;
  }
  if ( a === "five" && b === "two"){
    var a = 5;
    var b = 2;
  }
  if ( a === "five" && b === "three"){
    var a = 5;
    var b = 3;
  }
  if ( a === "five" && b === "four"){
    var a = 5;
    var b = 4;
  }
  if ( a === "five" && b === "five"){
    var a = 5;
    var b = 5;
  }
  if ( a === "five" && b === "six"){
    var a = 5;
    var b = 6;
  }
  if ( a === "five" && b === "seven"){
    var a = 5;
    var b = 7;
  }
  if ( a === "five" && b === "eight"){
    var a = 5;
    var b = 8;
  }
  if ( a === "five" && b === "nine"){
    var a = 5;
    var b = 9;
  }
  if ( a === "six" && b === "zero"){
    var a = 6;
    var b = 0;
  }
  if ( a === "six" && b === "one"){
    var a = 6;
    var b = 1;
  }
  if ( a === "six" && b === "two"){
    var a = 6;
    var b = 2;
  }
  if ( a === "six" && b === "three"){
    var a = 6;
    var b = 3;
  }
  if ( a === "six" && b === "four"){
    var a = 6;
    var b = 4;
  }
  if ( a === "six" && b === "five"){
    var a = 6;
    var b = 5;
  }
  if ( a === "six" && b === "six"){
    var a = 6;
    var b = 6;
  }
  if ( a === "six" && b === "seven"){
    var a = 6;
    var b = 7;
  }
  if ( a === "six" && b === "eight"){
    var a = 6;
    var b = 8;
  }
  if ( a === "six" && b === "nine"){
    var a = 6;
    var b = 9;
  }
  if ( a === "seven" && b === "zero"){
    var a = 7;
    var b = 0;
  }
  if ( a === "seven" && b === "one"){
    var a = 7;
    var b = 1;
  }
  if ( a === "seven" && b === "two"){
    var a = 7;
    var b = 2;
  }
  if ( a === "seven" && b === "three"){
    var a = 7;
    var b = 3;
  }
  if ( a === "seven" && b === "four"){
    var a = 7;
    var b = 4;
  }
  if ( a === "seven" && b === "five"){
    var a = 7;
    var b = 4;
  }
  if ( a === "seven" && b === "six"){
    var a = 7;
    var b = 5;
  }
  if ( a === "seven" && b === "seven"){
    var a = 7;
    var b = 7;
  }
  if ( a === "seven" && b === "seven"){
    var a = 7;
    var b = 8;
  }
  if ( a === "seven" && b === "eight"){
    var a = 7;
    var b = 8;
  }
  if ( a === "seven" && b === "nine"){
    var a = 7;
    var b = 9;
  }
  if ( a === "eight" && b === "zero"){
    var a = 8;
    var b = 0;
  }
  if ( a === "eight" && b === "one"){
    var a = 8;
    var b = 1;
  }
  if ( a === "eight" && b === "two"){
    var a = 8;
    var b = 2;
  }
  if ( a === "eight" && b === "three"){
    var a = 8;
    var b = 3;
  }
  if ( a === "eight" && b === "four"){
    var a = 8;
    var b = 4;
  }
  if ( a === "eight" && b === "five"){
    var a = 8;
    var b = 5;
  }
  if ( a === "eight" && b === "six"){
    var a = 8;
    var b = 6;
  }
  if ( a === "eight" && b === "seven"){
    var a = 8;
    var b = 7;
  }
  if ( a === "eight" && b === "eight"){
    var a = 8;
    var b = 8;
  }
  if ( a === "eight" && b === "nine"){
    var a = 8;
    var b = 9;
  }
  if ( a === "nine" && b === "zero"){
    var a = 9;
    var b = 0;
  }
  if ( a === "nine" && b === "one"){
    var a = 9;
    var b = 1;
  }
  if ( a === "nine" && b === "two"){
    var a = 9;
    var b = 2;
  }
  if ( a === "nine" && b === "three"){
    var a = 9;
    var b = 3;
  }
  if ( a === "nine" && b === "four"){
    var a = 9;
    var b = 4;
  }
  if ( a === "nine" && b === "five"){
    var a = 9;
    var b = 5;
  }
  if ( a === "nine" && b === "six"){
    var a = 9;
    var b = 6;
  }
  if ( a === "nine" && b === "seven"){
    var a = 9;
    var b = 7;
  }
  if ( a === "nine" && b === "eight"){
    var a = 9;
    var b = 8;
  }
  if ( a === "nine" && b === "nine"){
    var a = 9;
    var b = 9;
  }
  return a + b
}

// expect(toNumber).to.exist;
expect(add).to.exist;
expect(add("zero", "zero")).to.equal(0);
expect(add("zero", "one")).to.equal(1);
expect(add("zero", "two")).to.equal(2);
expect(add("zero", "three")).to.equal(3);
expect(add("zero", "four")).to.equal(4);
expect(add("zero", "five")).to.equal(5);
expect(add("zero", "six")).to.equal(6);
expect(add("zero", "seven")).to.equal(7);
expect(add("zero", "eight")).to.equal(8);
expect(add("zero", "nine")).to.equal(9);

expect(add("one", "four")).to.equal(5);
expect(add("one", "five")).to.equal(6);

console.log(add("zero", "one"))

function div(a, b){
  if ( a === "zero" && b === "zero"){
    var a = 0;
    var b = 0;
    return (a/b);
  }
  if ( a === "zero" && b === "one"){
    return 0;
  }
  if ( a === "zero" && b === "two"){
    return 0;
  }
  if ( a === "zero" && b === "three"){
    return 0;
  }
  if ( a === "zero" && b === "four"){
    return 0;
  }
  if ( a === "zero" && b === "five"){
    return 0;
  }
  if ( a === "zero" && b === "six"){
    var a = 0;
    var b = 6;
    return (a/b)
  }

}

expect(div).to.exist;
console.log(div("zero","six"));

/* function addd(a, b){
  return (toNumber(a) + toNumber(b))

}

function minus(a, b){
  return (toNumber(a) - toNumber(b))
}

function multiply(a, b){
  return (toNumber(a) * toNumber(b))
}

function divide(a, b){
  return (toNumber(a) / toNumber(b))
}

expect(toNumber("zero")).to.equal(0);
expect(toNumber("one")).to.equal(1); */
<commit_msg>two's done<commit_after>var expect = require('chai').expect;

function toNumber(word){
  if ( word === "zero" ){
    return 0;
  }
  if ( word === "one" ){
    return 1;
  }
  if ( word === "two" ){
    return 2;
  }
  if ( word === "three" ){
    return 3;
  }
  if ( word === "four" ){
    return 4;
  }
  if ( word === "five" ){
    return 5;
  }
  if ( word === "six" ){
    return 6;
  }
  if ( word === "seven" ){
    return 7;
  }
  if ( word === "eight" ){
    return 8;
  }
  if ( word === "nine" ){
    return 9;
  }

}

/* function add(a, b){
  return (toNumber(a) + toNumber(b))

}

function minus(a, b){
  return (toNumber(a) - toNumber(b))
}

function multiply(a, b){
  return (toNumber(a) * toNumber(b))
}

function divide(a, b){
  return (toNumber(a) / toNumber(b))
}

expect(toNumber("zero")).to.equal(0);
expect(toNumber("one")).to.equal(1); */

function add(a, b){
  if ( a === "zero" && b === "zero"){
    var a = 0;
    var b = 0;
    return a + b;
  }
  if ( a === "zero" && b === "one"){
    var a = 0;
    var b = 1;
    return a + b;
  }
  if ( a === "zero" && b === "two"){
    var a = 0;
    var b = 2;
    return a + b;
  }
  if ( a === "zero" && b === "three"){
    return 3;
  }
  if ( a === "zero" && b === "four"){
    return 4;
  }
  if ( a === "zero" && b === "five"){
    return 5;
  }
  if ( a === "zero" && b === "six"){
    return 6;
  }
  if ( a === "zero" && b === "seven"){
    return 7;
  }
  if ( a === "zero" && b === "eight"){
    return 8;
  }
  if ( a === "zero" && b === "nine"){
    return 9;
  }
  if ( a === "one" && b === "zero"){
    var a = 1;
    var b = 0;
    return a + b;
  }
  if ( a === "one" && b === "one"){
    var a = 1;
    var b = 1;
    return a + b;
  }
  if ( a === "one" && b === "two"){
    var a = 1;
    var b = 2;
    return a + b;
  }
  if ( a === "one" && b === "three"){
    var a = 1;
    var b = 3;
    return a + b;
  }
  if ( a === "one" && b === "four"){
    var a = 1;
    var b = 4;
  }
  if ( a === "one" && b === "five"){
    var a = 1;
    var b = 5;
  }
  if ( a === "one" && b === "six"){
    var a = 1;
    var b = 6;
  }
  if ( a === "one" && b === "seven"){
    var a = 1;
    var b = 7;
  }
  if ( a === "one" && b === "eight"){
    var a = 1;
    var b = 8;
  }
  if ( a === "one" && b === "nine"){
    var a = 1;
    var b = 9;
  }
  if ( a === "two" && b === "zero"){
    var a = 2;
    var b = 0;
  }
  if ( a === "two" && b === "one"){
    var a = 2;
    var b = 1;
  }
  if ( a === "two" && b === "two"){
    var a = 2;
    var b = 2;
  }
  if ( a === "two" && b === "three"){
    var a = 2;
    var b = 3;
  }
  if ( a === "two" && b === "four"){
    var a = 2;
    var b = 4;
  }
  if ( a === "two" && b === "five"){
    var a = 2;
    var b = 5;
  }
  if ( a === "two" && b === "six"){
    var a = 2;
    var b = 6;
  }
  if ( a === "two" && b === "seven"){
    var a = 2;
    var b = 7;
  }
  if ( a === "two" && b === "eight"){
    var a = 2;
    var b = 8;
  }
  if ( a === "two" && b === "nine"){
    var a = 2;
    var b = 9;
  }
  if ( a === "three" && b === "zero"){
    var a = 3;
    var b = 0;
  }
  if ( a === "three" && b === "one"){
    var a = 3;
    var b = 1;
  }
  if ( a === "three" && "two"){
    var a = 3;
    var b = 2;
  }
  if ( a === "three" && "three"){
    var a = 3;
    var b = 3;
  }
  if ( a === "three" && "four"){
    var a = 3;
    var b = 4;
  }
  if ( a === "three" && "five"){
    var a = 3;
    var b = 5;
  }
  if ( a === "three" && "six"){
    var a = 3;
    var b = 6;
  }
  if ( a === "three" && "seven"){
    var a = 3;
    var b = 7;
  }
  if ( a === "three" && "eight"){
    var a = 3;
    var b = 8;
  }
  if ( a === "three" && "nine"){
    var a = 3;
    var b = 9;
  }
  if ( a === "four" && "zero"){
    var a = 4;
    var b = 0;
  }
  if ( a === "four" && "one"){
    var a = 4;
    var b = 1;
  }
  if ( a === "four" && b === "two"){
    var a = 4;
    var b = 2;
  }
  if ( a === "four" && b === "three"){
    var a = 4;
    var b = 3;
  }
  if ( a === "four" && b === "four"){
    var a = 4;
    var b = 4;
  }
  if ( a === "four" && b === "five"){
    var a = 4;
    var b = 5;
  }
  if (a === "four" && b === "six"){
    var a = 4;
    var b = 6;
  }
  if (a === "four" && b === "seven"){
    var a = 4;
    var b = 7;
  }
  if (a === "four" && b === "eight"){
    var a = 4;
    var b = 8;
  }
  if ( a === "four" && b === "nine"){
    var a = 4;
    var b = 9;
  }
  if ( a === "five" && b === "zero"){
    var a = 5;
    var b = 0;
  }
  if ( a === "five" && b === "one"){
    var a = 5;
    var b = 1;
  }
  if ( a === "five" && b === "two"){
    var a = 5;
    var b = 2;
  }
  if ( a === "five" && b === "three"){
    var a = 5;
    var b = 3;
  }
  if ( a === "five" && b === "four"){
    var a = 5;
    var b = 4;
  }
  if ( a === "five" && b === "five"){
    var a = 5;
    var b = 5;
  }
  if ( a === "five" && b === "six"){
    var a = 5;
    var b = 6;
  }
  if ( a === "five" && b === "seven"){
    var a = 5;
    var b = 7;
  }
  if ( a === "five" && b === "eight"){
    var a = 5;
    var b = 8;
  }
  if ( a === "five" && b === "nine"){
    var a = 5;
    var b = 9;
  }
  if ( a === "six" && b === "zero"){
    var a = 6;
    var b = 0;
  }
  if ( a === "six" && b === "one"){
    var a = 6;
    var b = 1;
  }
  if ( a === "six" && b === "two"){
    var a = 6;
    var b = 2;
  }
  if ( a === "six" && b === "three"){
    var a = 6;
    var b = 3;
  }
  if ( a === "six" && b === "four"){
    var a = 6;
    var b = 4;
  }
  if ( a === "six" && b === "five"){
    var a = 6;
    var b = 5;
  }
  if ( a === "six" && b === "six"){
    var a = 6;
    var b = 6;
  }
  if ( a === "six" && b === "seven"){
    var a = 6;
    var b = 7;
  }
  if ( a === "six" && b === "eight"){
    var a = 6;
    var b = 8;
  }
  if ( a === "six" && b === "nine"){
    var a = 6;
    var b = 9;
  }
  if ( a === "seven" && b === "zero"){
    var a = 7;
    var b = 0;
  }
  if ( a === "seven" && b === "one"){
    var a = 7;
    var b = 1;
  }
  if ( a === "seven" && b === "two"){
    var a = 7;
    var b = 2;
  }
  if ( a === "seven" && b === "three"){
    var a = 7;
    var b = 3;
  }
  if ( a === "seven" && b === "four"){
    var a = 7;
    var b = 4;
  }
  if ( a === "seven" && b === "five"){
    var a = 7;
    var b = 4;
  }
  if ( a === "seven" && b === "six"){
    var a = 7;
    var b = 5;
  }
  if ( a === "seven" && b === "seven"){
    var a = 7;
    var b = 7;
  }
  if ( a === "seven" && b === "seven"){
    var a = 7;
    var b = 8;
  }
  if ( a === "seven" && b === "eight"){
    var a = 7;
    var b = 8;
  }
  if ( a === "seven" && b === "nine"){
    var a = 7;
    var b = 9;
  }
  if ( a === "eight" && b === "zero"){
    var a = 8;
    var b = 0;
  }
  if ( a === "eight" && b === "one"){
    var a = 8;
    var b = 1;
  }
  if ( a === "eight" && b === "two"){
    var a = 8;
    var b = 2;
  }
  if ( a === "eight" && b === "three"){
    var a = 8;
    var b = 3;
  }
  if ( a === "eight" && b === "four"){
    var a = 8;
    var b = 4;
  }
  if ( a === "eight" && b === "five"){
    var a = 8;
    var b = 5;
  }
  if ( a === "eight" && b === "six"){
    var a = 8;
    var b = 6;
  }
  if ( a === "eight" && b === "seven"){
    var a = 8;
    var b = 7;
  }
  if ( a === "eight" && b === "eight"){
    var a = 8;
    var b = 8;
  }
  if ( a === "eight" && b === "nine"){
    var a = 8;
    var b = 9;
  }
  if ( a === "nine" && b === "zero"){
    var a = 9;
    var b = 0;
  }
  if ( a === "nine" && b === "one"){
    var a = 9;
    var b = 1;
  }
  if ( a === "nine" && b === "two"){
    var a = 9;
    var b = 2;
  }
  if ( a === "nine" && b === "three"){
    var a = 9;
    var b = 3;
  }
  if ( a === "nine" && b === "four"){
    var a = 9;
    var b = 4;
  }
  if ( a === "nine" && b === "five"){
    var a = 9;
    var b = 5;
  }
  if ( a === "nine" && b === "six"){
    var a = 9;
    var b = 6;
  }
  if ( a === "nine" && b === "seven"){
    var a = 9;
    var b = 7;
  }
  if ( a === "nine" && b === "eight"){
    var a = 9;
    var b = 8;
  }
  if ( a === "nine" && b === "nine"){
    var a = 9;
    var b = 9;
  }
  return a + b
}

// expect(toNumber).to.exist;
expect(add).to.exist;
expect(add("zero", "zero")).to.equal(0);
expect(add("zero", "one")).to.equal(1);
expect(add("zero", "two")).to.equal(2);
expect(add("zero", "three")).to.equal(3);
expect(add("zero", "four")).to.equal(4);
expect(add("zero", "five")).to.equal(5);
expect(add("zero", "six")).to.equal(6);
expect(add("zero", "seven")).to.equal(7);
expect(add("zero", "eight")).to.equal(8);
expect(add("zero", "nine")).to.equal(9);

expect(add("one", "zero")).to.equal(1);
expect(add("one", "one")).to.equal(2);
expect(add("one", "two")).to.equal(3);
expect(add("one", "three")).to.equal(4);
expect(add("one", "four")).to.equal(5);
expect(add("one", "five")).to.equal(6);
expect(add("one", "six")).to.equal(7);
expect(add("one", "seven")).to.equal(8);
expect(add("one", "eight")).to.equal(9);
expect(add("one", "nine")).to.equal(10);

expect(add("two", "zero")).to.equal(2);
expect(add("two", "one")).to.equal(3);
expect(add("two", "two")).to.equal(4);
expect(add("two", "three")).to.equal(5);
expect(add("two", "four")).to.equal(6);
expect(add("two", "five")).to.equal(7);
expect(add("two", "six")).to.equal(8);
expect(add("two", "seven")).to.equal(9);
expect(add("two", "eight")).to.equal(10);
expect(add("two", "nine")).to.equal(11);

console.log(add("zero", "one"))

function div(a, b){
  if ( a === "zero" && b === "zero"){
    var a = 0;
    var b = 0;
    return (a/b);
  }
  if ( a === "zero" && b === "one"){
    return 0;
  }
  if ( a === "zero" && b === "two"){
    return 0;
  }
  if ( a === "zero" && b === "three"){
    return 0;
  }
  if ( a === "zero" && b === "four"){
    return 0;
  }
  if ( a === "zero" && b === "five"){
    return 0;
  }
  if ( a === "zero" && b === "six"){
    var a = 0;
    var b = 6;
    return (a/b)
  }

}

expect(div).to.exist;
console.log(div("zero","six"));
<|endoftext|>


<commit_before>/*! resol-vbus | Copyright (c) 2013-2018, Daniel Wippermann | MIT license */
'use strict';

const fs = require('fs');
const os = require('os');

const express = require('express');
const winston = require('winston');

const {
    HeaderSet,
    HeaderSetConsolidator,
    Specification,
    SerialConnection,
    TcpConnection,
} = require('../resol-vbus');

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

const logger = winston.createLogger({
    transports: [
        new winston.transports.Console({
            level: 'debug',
            format: winston.format.combine(
                winston.format.colorize(),
                winston.format.simple()
            ),
        }),
    ],
});

const connectionClassByName = {
    SerialConnection,
    TcpConnection,
};

const spec = Specification.getDefaultSpecification();

const headerSet = new HeaderSet();

const generateJsonData = async function() {
    const packetFields = spec.getPacketFieldsForHeaders(headerSet.getSortedHeaders());

    const data = packetFields.map((pf) => {
        return {
            id: pf.id,
            name: pf.name,
            rawValue: pf.rawValue,
        };
    });

    return JSON.stringify(data, null, 4);
};

const generatePrometheusResponse = async function() {
    const packetFields = spec.getPacketFieldsForHeaders(headerSet.getSortedHeaders());

    const data = packetFields.map((pf) => {
        return {
            id: pf.id,
            name: pf.name,
            rawValue: pf.rawValue,
        };
    });

		var response = "";
		response = response.concat("# HELP resol Values as retreived from Resol Solar", '\n');
		response = response.concat("# TYPE resol gauge", '\n');

    for(var i = 0; i < data.length; i++) {
        var obj = data[i];

				logger.debug(obj.id);
				logger.debug(obj.name);
				logger.debug(obj.rawValue);

				response = response.concat('resol{id="', obj.id, '",name="', obj.name, '"} ', obj.rawValue, '\n')
    }

    return response;
};

const writeHeaderSet = async (filename) => {
    logger.debug('HeaderSet complete');

    const data = await generateJsonData();

    await new Promise((resolve, reject) => {
        fs.writeFile(filename, data, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
};

const main = async () => {
    logger.debug('Starting server...');

    const app = express();

    app.get('/api/v1/live-data', (req, res) => {
        generateJsonData().then(data => {
            res.status(200).type('application/json').end(data);
        }).then(null, (err) => {
            logger.error(err);
            res.status(500).type('text/plain').end(err.toString());
        });
    });

    app.get('/api/v1/monitor', (req, res) => {
        generatePrometheusResponse().then(data => {
            res.status(200).type('text/plain').end(data);
        }).then(null, (err) => {
            logger.error(err);
            res.status(500).type('text/plain').end(err.toString());
        });
    });

    await new Promise((resolve, reject) => {
        app.listen(config.httpPort, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });

    logger.debug('Connect to VBus data source...');

    const hsc = new HeaderSetConsolidator({
        interval: config.loggingInterval,
    });

    const ConnectionClass = connectionClassByName [config.connectionClassName];

    const connection = new ConnectionClass(config.connectionOptions);

    connection.on('packet', (packet) => {
        headerSet.addHeader(packet);
        hsc.addHeader(packet);
    });

    hsc.on('headerSet', (headerSet) => {
        writeHeaderSet(config.loggingFilename).then(null, err => {
            logger.error(err);
        });
    });

    await connection.connect();

    logger.info('Ready to serve from the following URLs:');
    for (const iface of Object.values(os.networkInterfaces())) {
        for (const ifaceConfig of iface) {
            if (ifaceConfig.family === 'IPv4') {
                logger.info('    - http://' + ifaceConfig.address + ':' + config.httpPort + '/api/v1/live-data' + (ifaceConfig.internal ? ' (internal)' : ''));
            }
        }
    }

    hsc.startTimer();

    return new Promise((resolve, reject) => {
        // nop, just run forever
    });
};

if (require.main === module) {
    main(process.argv.slice(2)).then(null, err => {
        logger.error(err);
    });
} else {
    module.exports = main;
}
<commit_msg>Make file-based logging optional.<commit_after>/*! resol-vbus | Copyright (c) 2013-2018, Daniel Wippermann | MIT license */
'use strict';

const fs = require('fs');
const os = require('os');

const express = require('express');
const winston = require('winston');

const {
    HeaderSet,
    HeaderSetConsolidator,
    Specification,
    SerialConnection,
    TcpConnection,
} = require('../resol-vbus');

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

const logger = winston.createLogger({
    transports: [
        new winston.transports.Console({
            level: 'debug',
            format: winston.format.combine(
                winston.format.colorize(),
                winston.format.simple()
            ),
        }),
    ],
});

const connectionClassByName = {
    SerialConnection,
    TcpConnection,
};

const spec = Specification.getDefaultSpecification();

const headerSet = new HeaderSet();

const generateJsonData = async function() {
    const packetFields = spec.getPacketFieldsForHeaders(headerSet.getSortedHeaders());

    const data = packetFields.map((pf) => {
        return {
            id: pf.id,
            name: pf.name,
            rawValue: pf.rawValue,
        };
    });

    return JSON.stringify(data, null, 4);
};

const generatePrometheusResponse = async function() {
    const packetFields = spec.getPacketFieldsForHeaders(headerSet.getSortedHeaders());

    const data = packetFields.map((pf) => {
        return {
            id: pf.id,
            name: pf.name,
            rawValue: pf.rawValue,
        };
    });

		var response = "";
		response = response.concat("# HELP resol Values as retreived from Resol Solar", '\n');
		response = response.concat("# TYPE resol gauge", '\n');

    for(var i = 0; i < data.length; i++) {
        var obj = data[i];

				logger.debug(obj.id);
				logger.debug(obj.name);
				logger.debug(obj.rawValue);

				response = response.concat('resol{id="', obj.id, '",name="', obj.name, '"} ', obj.rawValue, '\n')
    }

    return response;
};

const writeHeaderSet = async (filename) => {
    logger.debug('HeaderSet complete');

    const data = await generateJsonData();

    await new Promise((resolve, reject) => {
        fs.writeFile(filename, data, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
};

const main = async () => {
    logger.debug('Starting server...');

    const app = express();

    app.get('/api/v1/live-data', (req, res) => {
        generateJsonData().then(data => {
            res.status(200).type('application/json').end(data);
        }).then(null, (err) => {
            logger.error(err);
            res.status(500).type('text/plain').end(err.toString());
        });
    });

    app.get('/api/v1/monitor', (req, res) => {
        generatePrometheusResponse().then(data => {
            res.status(200).type('text/plain').end(data);
        }).then(null, (err) => {
            logger.error(err);
            res.status(500).type('text/plain').end(err.toString());
        });
    });

    await new Promise((resolve, reject) => {
        app.listen(config.httpPort, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });

    logger.debug('Connect to VBus data source...');

    const hsc = new HeaderSetConsolidator({
        interval: config.loggingInterval,
    });

    const ConnectionClass = connectionClassByName [config.connectionClassName];

    const connection = new ConnectionClass(config.connectionOptions);

    connection.on('packet', (packet) => {
        headerSet.addHeader(packet);
        hsc.addHeader(packet);
    });

    hsc.on('headerSet', (headerSet) => {
        if (config.loggingFilename) {
            writeHeaderSet(config.loggingFilename).then(null, err => {
                logger.error(err);
            });
        }
    });

    await connection.connect();

    logger.info('Ready to serve from the following URLs:');
    for (const iface of Object.values(os.networkInterfaces())) {
        for (const ifaceConfig of iface) {
            if (ifaceConfig.family === 'IPv4') {
                logger.info('    - http://' + ifaceConfig.address + ':' + config.httpPort + '/api/v1/live-data' + (ifaceConfig.internal ? ' (internal)' : ''));
            }
        }
    }

    hsc.startTimer();

    return new Promise((resolve, reject) => {
        // nop, just run forever
    });
};

if (require.main === module) {
    main(process.argv.slice(2)).then(null, err => {
        logger.error(err);
    });
} else {
    module.exports = main;
}
<|endoftext|>


<commit_before>app.controller("AngularFormController", ["$http", "$scope", function($http, $scope) {
	/**
	 * State variable to store alerts generated from submit event
	 * @type {Array}
	 **/
	$scope.alerts = [];

	/**
	 * State variable that keeps track of data entered
	 * @type {Object}
	 **/
	$scope.formData = {name:null, email:null, subject: null, message:null};

	/**
	 * Method to reset form data when submit and cancel buttons are pressed
	 **/
	$scope.reset = function() {
		$scope.formData = {name:null, email:null, subject: null, message:null};
		$scope.quoteForm.$setUntouched();
		$scope.quoteForm.$setPristine();
	};

	/**
	 * Method to process action from submit button
	 *
	 * @param formData object containing submitted form data
	 * @param validated true if pressed validation, false if not
	 **/
	$scope.submit = function(formData, validated) {
		if(validated === true){
			$http.post("../../php/mailer.php", formData)
				.then(function(reply) {
					$scope.alerts[0] = {
						type: "danger",
						msg: reply.data.message
					};
					if(reply.data.status === 200) {
						$scope.alerts[0].type = "Your message has been sent successfully";
					}
				});
		} else {
			$scope.alerts[0] = {
				type: "danger",
				msg: "Please review your information and try again."
			};
		}
		$scope.reset();
	};
}]);

<commit_msg>changed controller<commit_after>app.controller("AngularFormController", ["$http", "$scope", function($http, $scope) {
	/**
	 * State variable to store alerts generated from submit event
	 * @type {Array}
	 **/
	$scope.alerts = [];

	/**
	 * State variable that keeps track of data entered
	 * @type {Object}
	 **/
	$scope.formData = {name:null, email:null, subject: null, message:null};

	/**
	 * Method to reset form data when submit and cancel buttons are pressed
	 **/
	$scope.reset = function() {
		$scope.formData = {name:null, email:null, subject: null, message:null};
		$scope.quoteForm.$setUntouched();
		$scope.quoteForm.$setPristine();
	};

	/**
	 * Method to process action from submit button
	 *
	 * @param formData object containing submitted form data
	 * @param validated true if pressed validation, false if not
	 **/
	$scope.submit = function(formData, validated) {
		if(validated === true){
			$http.post("../../php/mailer.php", formData)
				.then(function(reply) {
					$scope.alerts[0] = {
						type: "danger",
						msg: reply.data.message
					};
					if(reply.data.status === 200) {
						$scope.alerts[0].type = "Your message has been sent successfully";
					}
				});
		} else {
			$scope.alerts[0] = {
				type: "danger",
				msg: "Please review your information and try again."
			};
		}
		$scope.reset();
	};
}]);

<|endoftext|>


<commit_before>import SPELLS from 'common/SPELLS';

import EventsNormalizer from 'parser/core/EventsNormalizer';

const debug = false;

class ApplyBuff extends EventsNormalizer {
  // We need to track `combatantinfo` events this way since they aren't included in the `events` passed to `normalize` due to technical reasons (it's a different API call). We still need `combatantinfo` for all players, so cache it manually.
  _combatantInfoEvents = [];
  constructor(...args) {
    super(...args);
    this._combatantInfoEvents = this.owner.combatantInfoEvents;
  }

  _buffsAppliedByPlayerId = {};

  /**
   * Some buffs like Bloodlust and Holy Avenger when they are applied pre-combat it doesn't show up as an `applybuff` event nor in the `combatantinfo` buffs array. It can still be detected by looking for a `removebuff` event, this uses that to detect it and then fabricates an `applybuff` event at the start of the log.
   * @param {Array} events
   * @returns {Array}
   */
  normalize(events) {
    const firstEventIndex = this.getFightStartIndex(events);
    const firstStartTimestamp = this.owner.fight.start_time;
    const playersById = this.owner.playersById;
    const playerId = this.owner.playerId;

    // region Buff event based detection
    // This catches most relevant buffs and is most accurate. If a player is good at juggling certain buffs they can achieve 100% uptime, if that happens `removebuff` is never called, so we also check for other indicators that are just as reliable, such as `applybuffstack`, `removebuffstack` and `refreshbuff`.
    for (let i = 0; i < events.length; i += 1) {
      const event = events[i];
      const targetId = event.targetID;
      const sourceId = event.sourceID;

      // A player can have the same buff twice given that the buff was applied by someone else. Because we only want to fabricate buffs once, we use `_buffsAppliedByPlayerId` to ensure we don't do it twice, but because it doesn't track a source we can't track other people's buffs. And that's fine too since we only care about stuff by/to the player.
      if (![targetId, sourceId].includes(playerId)) {
        continue;
      }

      this._buffsAppliedByPlayerId[targetId] = this._buffsAppliedByPlayerId[targetId] || [];

      if (event.type === 'applybuff') {
        const spellId = event.ability.guid;
        this._buffsAppliedByPlayerId[targetId].push(spellId);
      }
      if (['removebuff', 'applybuffstack', 'removebuffstack', 'refreshbuff'].includes(event.type)) {
        const spellId = event.ability.guid;
        if (this._buffsAppliedByPlayerId[targetId].includes(spellId)) {
          // This buff has an `applybuff` event and so isn't broken :D
          continue;
        }

        debug && this.warn('Found a buff on', ((playersById[targetId] && playersById[targetId].name) || '???'), 'that was applied before the pull:', event.ability.name, spellId, '! Fabricating an `applybuff` event so you don\'t have to do anything special to take this into account.');
        const targetInfo = this._combatantInfoEvents.find(combatantInfoEvent => combatantInfoEvent.sourceID === targetId);
        const applybuff = {
          // These are all the properties a normal `applybuff` event would have.
          timestamp: firstStartTimestamp,
          type: 'applybuff',
          ability: event.ability,
          sourceID: sourceId,
          sourceIsFriendly: event.sourceIsFriendly,
          targetID: targetId,
          targetIsFriendly: event.targetIsFriendly,
          // Custom properties:
          prepull: true,
          __fabricated: true,
          // If we see a prepull buff from both its removebuff and in combatantinfo, we populate fabricated applybuff from the removebuff because this requires us to make up fewer fields. We still need to mark it as in the combatantinfo.
          __fromCombatantinfo: targetInfo && targetInfo.auras && targetInfo.auras.some(aura => aura.ability === spellId),
        };

        events.splice(firstEventIndex, 0, applybuff);
        // It shouldn't happen twice, but better be safe than sorry.
        this._buffsAppliedByPlayerId[targetId].push(spellId);
      }
    }
    // endregion

    // region `combatantinfo` based detection
    // This catches buffs that never drop, such as Flasks and more importantly Atonements, Beacons and Vantus runes.
    this._combatantInfoEvents.forEach(event => {
      const targetId = event.sourceID;
      // event.auras can be undefined if combatantinfo for any player in the fight errored
      event.auras && event.auras.forEach(aura => {
        const spellId = aura.ability;
        const sourceId = aura.source;

        // A player can have the same buff twice given that the buff was applied by someone else. Because we only want to fabricate buffs once, we use `_buffsAppliedByPlayerId` to ensure we don't do it twice, but because it doesn't track a source we can't track other people's buffs. And that's fine too since we only care about stuff by/to the player.
        if (![targetId, sourceId].includes(playerId)) {
          return;
        }

        this._buffsAppliedByPlayerId[targetId] = this._buffsAppliedByPlayerId[targetId] || [];

        if (this._buffsAppliedByPlayerId[targetId].includes(spellId)) {
          // This buff has an `applybuff` event and so isn't broken :D
          return;
        }

        debug && console.warn('Found a buff on', ((playersById[targetId] && playersById[targetId].name) || '???'), 'in the combatantinfo that was applied before the pull and never dropped:', (SPELLS[spellId] && SPELLS[spellId].name) || '???', spellId, '! Fabricating an `applybuff` event so you don\'t have to do anything special to take this into account.');
        const applybuff = {
          // These are all the properties a normal `applybuff` event would have.
          timestamp: firstStartTimestamp,
          type: 'applybuff',
          ability: {
            guid: spellId,
            name: SPELLS[spellId] ? SPELLS[spellId].name : 'Unknown',
            abilityIcon: aura.icon,
          },
          sourceID: sourceId,
          sourceIsFriendly: true,
          targetID: targetId,
          targetIsFriendly: true,
          // Custom properties:
          prepull: true,
          __fabricated: true,
          __fromCombatantinfo: true,
        };
        events.splice(firstEventIndex, 0, applybuff);
        // It shouldn't happen twice, but better be safe than sorry.
        this._buffsAppliedByPlayerId[targetId].push(spellId);
      });
    });
    // We don't need it anymore, this might introduce a crash if this method is ever called twice, but we're under the presumption that never happens so if it does crash we might have to verify if everything works properly with this behavior.
    this._combatantInfoEvents = undefined;
    // endregion

    return events;
  }
}

export default ApplyBuff;
<commit_msg>Revert "Fabricate applybuffs at fight start instead of a fraction of a second after"<commit_after>import SPELLS from 'common/SPELLS';

import EventsNormalizer from 'parser/core/EventsNormalizer';

const debug = false;

class ApplyBuff extends EventsNormalizer {
  // We need to track `combatantinfo` events this way since they are included in the `events` passed to `normalize` due to technical reasons (it's a different API call). We still need `combatantinfo` for all players, so cache it manually.
  _combatantInfoEvents = [];
  constructor(...args) {
    super(...args);
    this._combatantInfoEvents = this.owner.combatantInfoEvents;
  }

  _buffsAppliedByPlayerId = {};

  /**
   * Some buffs like Bloodlust and Holy Avenger when they are applied pre-combat it doesn't show up as an `applybuff` event nor in the `combatantinfo` buffs array. It can still be detected by looking for a `removebuff` event, this uses that to detect it and then fabricates an `applybuff` event at the start of the log.
   * @param {Array} events
   * @returns {Array}
   */
  normalize(events) {
    const firstEventIndex = this.getFightStartIndex(events);
    const playersById = this.owner.playersById;
    const playerId = this.owner.playerId;

    // region Buff event based detection
    // This catches most relevant buffs and is most accurate. If a player is good at juggling certain buffs they can achieve 100% uptime, if that happens `removebuff` is never called, so we also check for other indicators that are just as reliable, such as `applybuffstack`, `removebuffstack` and `refreshbuff`.
    for (let i = 0; i < events.length; i += 1) {
      const event = events[i];
      const targetId = event.targetID;
      const sourceId = event.sourceID;

      // A player can have the same buff twice given that the buff was applied by someone else. Because we only want to fabricate buffs once, we use `_buffsAppliedByPlayerId` to ensure we don't do it twice, but because it doesn't track a source we can't track other people's buffs. And that's fine too since we only care about stuff by/to the player.
      if (![targetId, sourceId].includes(playerId)) {
        continue;
      }

      this._buffsAppliedByPlayerId[targetId] = this._buffsAppliedByPlayerId[targetId] || [];

      if (event.type === 'applybuff') {
        const spellId = event.ability.guid;
        this._buffsAppliedByPlayerId[targetId].push(spellId);
      }
      if (['removebuff', 'applybuffstack', 'removebuffstack', 'refreshbuff'].includes(event.type)) {
        const spellId = event.ability.guid;
        if (this._buffsAppliedByPlayerId[targetId].includes(spellId)) {
          // This buff has an `applybuff` event and so isn't broken :D
          continue;
        }

        debug && this.warn('Found a buff on', ((playersById[targetId] && playersById[targetId].name) || '???'), 'that was applied before the pull:', event.ability.name, spellId, '! Fabricating an `applybuff` event so you don\'t have to do anything special to take this into account.');
        const targetInfo = this._combatantInfoEvents.find(combatantInfoEvent => combatantInfoEvent.sourceID === targetId);
        const applybuff = {
          // These are all the properties a normal `applybuff` event would have.
          timestamp: events[firstEventIndex].timestamp,
          type: 'applybuff',
          ability: event.ability,
          sourceID: sourceId,
          sourceIsFriendly: event.sourceIsFriendly,
          targetID: targetId,
          targetIsFriendly: event.targetIsFriendly,
          // Custom properties:
          prepull: true,
          __fabricated: true,
          // If we see a prepull buff from both its removebuff and in combatantinfo, we populate fabricated applybuff from the removebuff because this requires us to make up fewer fields. We still need to mark it as in the combatantinfo.
          __fromCombatantinfo: targetInfo && targetInfo.auras && targetInfo.auras.some(aura => aura.ability === spellId),
        };

        events.splice(firstEventIndex, 0, applybuff);
        // It shouldn't happen twice, but better be safe than sorry.
        this._buffsAppliedByPlayerId[targetId].push(spellId);
      }
    }
    // endregion

    // region `combatantinfo` based detection
    // This catches buffs that never drop, such as Flasks and more importantly Atonements and Beacons.
    this._combatantInfoEvents.forEach(event => {
      const targetId = event.sourceID;
      // event.auras can be undefined if combatantinfo for any player in the fight errored
      event.auras && event.auras.forEach(aura => {
        const spellId = aura.ability;
        const sourceId = aura.source;

        // A player can have the same buff twice given that the buff was applied by someone else. Because we only want to fabricate buffs once, we use `_buffsAppliedByPlayerId` to ensure we don't do it twice, but because it doesn't track a source we can't track other people's buffs. And that's fine too since we only care about stuff by/to the player.
        if (![targetId, sourceId].includes(playerId)) {
          return;
        }

        this._buffsAppliedByPlayerId[targetId] = this._buffsAppliedByPlayerId[targetId] || [];

        if (this._buffsAppliedByPlayerId[targetId].includes(spellId)) {
          // This buff has an `applybuff` event and so isn't broken :D
          return;
        }

        debug && console.warn('Found a buff on', ((playersById[targetId] && playersById[targetId].name) || '???'), 'in the combatantinfo that was applied before the pull and never dropped:', (SPELLS[spellId] && SPELLS[spellId].name) || '???', spellId, '! Fabricating an `applybuff` event so you don\'t have to do anything special to take this into account.');
        const applybuff = {
          // These are all the properties a normal `applybuff` event would have.
          timestamp: events[firstEventIndex].timestamp,
          type: 'applybuff',
          ability: {
            guid: spellId,
            name: SPELLS[spellId] ? SPELLS[spellId].name : 'Unknown',
            abilityIcon: aura.icon,
          },
          sourceID: sourceId,
          sourceIsFriendly: true,
          targetID: targetId,
          targetIsFriendly: true,
          // Custom properties:
          prepull: true,
          __fabricated: true,
          __fromCombatantinfo: true,
        };
        events.splice(firstEventIndex, 0, applybuff);
        // It shouldn't happen twice, but better be safe than sorry.
        this._buffsAppliedByPlayerId[targetId].push(spellId);
      });
    });
    // We don't need it anymore, this might introduce a crash if this method is ever called twice, but we're under the presumption that never happens so if it does crash we might have to verify if everything works properly with this behavior.
    this._combatantInfoEvents = undefined;
    // endregion

    return events;
  }
}

export default ApplyBuff;
<|endoftext|>


<commit_before>define(['dojo/_base/declare','dojo/_base/json','JBrowse/Util'], function(declare,json,Util) {
return declare('JBrowse.ConfigAdaptor.JB_json_v1',null,

    /**
     * @lends JBrowse.ConfigAdaptor.JB_json_v1.prototype
     */
    {

        /**
         * Configuration adaptor for JBrowse JSON version 1 configuration
         * files (formerly known as trackList.json files).
         * @constructs
         */
        constructor: function() {},

        /**
         * Load the configuration file from a URL.
         *
         * @param args.config.url {String} URL for fetching the config file.
         * @param args.onSuccess {Function} callback for a successful config fetch
         * @param args.onFailure {Function} optional callback for a
         *   config fetch failure
         * @param args.context {Object} optional context in which to
         *   call the callbacks, defaults to the config object itself
         */
        load: function( /**Object*/ args ) {
            var that = this;
            if( args.config.url ) {
                dojo.xhrGet({
                                url: Util.resolveUrl( args.baseUrl || window.location.href, args.config.url ),
                                handleAs: 'text',
                                load: function( o ) {
                                    o = that.parse_conf( o, args );
                                    o = that.regularize_conf( o, args );
                                    args.onSuccess.call( args.context || this, o );
                                },
                                error: function( i ) {
                                    console.error( ''+i );
                                    if( args.onFailure )
                                        args.onFailure.call( args.context || this, i);
                                }
                            });
            }
            else if( args.config.data ) {
                var conf = this.regularize_conf( args.config.data, args );
                args.onSuccess.call( args.context || this, conf );
            }
        },

        /**
         * In this adaptor, just evals the conf text to parse the JSON, but
         * other conf adaptors might want to inherit and override this.
         * @param {String} conf_text the configuration text
         * @param {Object} load_args the arguments that were passed to load()
         * @returns {Object} the parsed JSON
         */
        parse_conf: function( conf_text, load_args ) {
            return json.fromJson( conf_text );
        },

        /**
         * Applies defaults and any other necessary tweaks to the loaded JSON
         * configuration.  Called by load() on the JSON
         * configuration before it calls the onSuccess callback.
         * @param {Object} o the object containing the configuration, which it
         *                   modifies in-place
         * @param {Object} load_args the arguments that were passed to load()
         * @returns the same object it was passed
         */
        regularize_conf: function( o, load_args ) {
            o.sourceUrl = o.sourceUrl || load_args.config.url;
            o.baseUrl   = o.baseUrl || Util.resolveUrl( o.sourceUrl, '.' );
            if( ! /\/$/.test( o.baseUrl ) )
                o.baseUrl += "/";

            return this._evalHooks( o );
        },

        _evalHooks: function( conf ) {
            for( var x in conf ) {
                if( typeof conf[x] == 'object' )
                    // recur
                    conf[x] = this._evalHooks( conf[x] );
                else if( typeof conf[x] == 'string' ) {
                    // compile
                    var spec = conf[x];
                    if( /^function\s*\(/.test(spec) && /\}[\s;]*$/.test(spec) ) {
                        conf[x] = this._evalHook(spec);
                    }
                }
            }
            return conf;
        },
        _evalHook: function() {
            // can't bind arguments because the closure compiler
            // renames variables, and we need to assign in the eval
            if ( "string" != typeof arguments[0])
                return arguments[0];
            try {
                eval("arguments[0]="+arguments[0]+";");
            } catch (e) {
                console.error("eval failed for callback '"+arguments[0]+"': "+e);
            }
            return arguments[0];
        }
});
});<commit_msg>don't force an empty baseUrl to be '/'<commit_after>define(['dojo/_base/declare','dojo/_base/json','JBrowse/Util'], function(declare,json,Util) {
return declare('JBrowse.ConfigAdaptor.JB_json_v1',null,

    /**
     * @lends JBrowse.ConfigAdaptor.JB_json_v1.prototype
     */
    {

        /**
         * Configuration adaptor for JBrowse JSON version 1 configuration
         * files (formerly known as trackList.json files).
         * @constructs
         */
        constructor: function() {},

        /**
         * Load the configuration file from a URL.
         *
         * @param args.config.url {String} URL for fetching the config file.
         * @param args.onSuccess {Function} callback for a successful config fetch
         * @param args.onFailure {Function} optional callback for a
         *   config fetch failure
         * @param args.context {Object} optional context in which to
         *   call the callbacks, defaults to the config object itself
         */
        load: function( /**Object*/ args ) {
            var that = this;
            if( args.config.url ) {
                dojo.xhrGet({
                                url: Util.resolveUrl( args.baseUrl || window.location.href, args.config.url ),
                                handleAs: 'text',
                                load: function( o ) {
                                    window.setTimeout( dojo.hitch(this, function() {
                                    o = that.parse_conf( o, args );
                                    o = that.regularize_conf( o, args );
                                    args.onSuccess.call( args.context || this, o );
                                                                  }, 10 ));
                                },
                                error: function( i ) {
                                    console.error( ''+i );
                                    if( args.onFailure )
                                        args.onFailure.call( args.context || this, i);
                                }
                            });
            }
            else if( args.config.data ) {
                var conf = this.regularize_conf( args.config.data, args );
                args.onSuccess.call( args.context || this, conf );
            }
        },

        /**
         * In this adaptor, just evals the conf text to parse the JSON, but
         * other conf adaptors might want to inherit and override this.
         * @param {String} conf_text the configuration text
         * @param {Object} load_args the arguments that were passed to load()
         * @returns {Object} the parsed JSON
         */
        parse_conf: function( conf_text, load_args ) {
            return json.fromJson( conf_text );
        },

        /**
         * Applies defaults and any other necessary tweaks to the loaded JSON
         * configuration.  Called by load() on the JSON
         * configuration before it calls the onSuccess callback.
         * @param {Object} o the object containing the configuration, which it
         *                   modifies in-place
         * @param {Object} load_args the arguments that were passed to load()
         * @returns the same object it was passed
         */
        regularize_conf: function( o, load_args ) {
            o.sourceUrl = o.sourceUrl || load_args.config.url;
            o.baseUrl   = o.baseUrl || Util.resolveUrl( o.sourceUrl, '.' );
            if( o.baseUrl.length && ! /\/$/.test( o.baseUrl ) )
                o.baseUrl += "/";

            return this._evalHooks( o );
        },

        _evalHooks: function( conf ) {
            for( var x in conf ) {
                if( typeof conf[x] == 'object' )
                    // recur
                    conf[x] = this._evalHooks( conf[x] );
                else if( typeof conf[x] == 'string' ) {
                    // compile
                    var spec = conf[x];
                    if( /^function\s*\(/.test(spec) && /\}[\s;]*$/.test(spec) ) {
                        conf[x] = this._evalHook(spec);
                    }
                }
            }
            return conf;
        },
        _evalHook: function() {
            // can't bind arguments because the closure compiler
            // renames variables, and we need to assign in the eval
            if ( "string" != typeof arguments[0])
                return arguments[0];
            try {
                eval("arguments[0]="+arguments[0]+";");
            } catch (e) {
                console.error("eval failed for callback '"+arguments[0]+"': "+e);
            }
            return arguments[0];
        }
});
});<|endoftext|>


<commit_before>export default (type) => {
  const { attributes } = type;

  return attributes.reduce((prev, { field, type: attrType }) => ({
    ...prev,
    [field]: {
      type: attrType,
    },
  }), {});
};
<commit_msg>Ensure that attributes are valid leaf types<commit_after>import { isLeafType } from 'graphql';

export default (type) => {
  const { name, attributes } = type;

  return attributes.reduce((prev, { field, type: attrType }) => {
    if (!isLeafType(attrType)) {
      throw new TypeError(
        `The ${field} attribute of the ${name} type is not a valid GraphQL leaf type. All ` +
        'attributes must be a valid leaf type'
      );
    }

    return {
      ...prev,
      [field]: {
        type: attrType,
      },
    };
  }, {});
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs-extra'),
    os = require('os'),
    isWindows = require('os').platform().indexOf('win') === 0,
    path = require('path'),
    thisPackage = require('../package.json'),
    version = process.env.MB_VERSION || thisPackage.version,
    run = require('./run').run;

function rmdirRecursiveSync (dir) {
    if (isWindows) {
        if (!fs.existsSync(dir)) {
            return;
        }

        fs.readdirSync(dir).forEach(function (file) {
            var filePath = path.join(dir, file);

            if (fs.lstatSync(filePath).isDirectory()) {
                rmdirRecursiveSync(filePath);
            } else {
                fs.unlinkSync(filePath);
            }
        });

        fs.rmdirSync(dir);
    }
    else {
        // This doesn't appear to work on Windows
        fs.removeSync(dir);
    }
}

module.exports = function (grunt) {

    function failTask (task) {
        return function (exitCode) {
            grunt.warn(task + ' failed', exitCode);
        };
    }

    grunt.registerTask('dist', 'Create trimmed down distribution directory', function () {
        var done = this.async(),
            newPackage = JSON.parse(JSON.stringify(thisPackage)),
            failed = failTask('dist');

        // This doesn't work on Windows
        rmdirRecursiveSync('dist');
        fs.mkdirSync('dist');
        fs.mkdirSync('dist/mountebank');
        ['bin', 'src', 'package.json', 'releases.json', 'README.md', 'LICENSE'].forEach(function (source) {
            fs.copySync(source, 'dist/mountebank/' + source);
        });
        rmdirRecursiveSync('dist/mountebank/src/public/images/sources');

        // removing devDependencies so the standard npm install (without --production) is smooth
        // in all cases.  The jsdom dependency gets tricky otherwise, since we need different versions
        // based on different versions of node
        delete newPackage.devDependencies;
        delete newPackage.devDependenciesBasedOnNodeVersion;
        fs.writeFileSync('dist/mountebank/package.json', JSON.stringify(newPackage, null, 2));

        run('npm', ['install', '--production'], { cwd: 'dist/mountebank' }).done(function () {
            // Switch tests to use the mb from the dist directory to test what actually gets published
            process.env.MB_EXECUTABLE = 'dist/mountebank/bin/mb';
            done();
        }, failed);
    });

    grunt.registerTask('version', 'Set the version number', function () {
        var newPackage = require('../dist/mountebank/package.json');

        newPackage.version = version;
        console.log('Using version ' + version);
        fs.writeFileSync('./dist/mountebank/package.json', JSON.stringify(newPackage, null, 2) + '\n');
    });

    grunt.registerTask('dist:tarball', 'Create OS-specific tarballs', function (arch) {
        run('scripts/dist/createSelfContainedTarball', [os.platform(), arch || os.arch(), version]).done(
            this.async(), failTask('dist:tarball'));
    });

    grunt.registerTask('dist:zip', 'Create OS-specific zips', function (arch) {
        run('scripts/dist/createWindowsZip', [arch, version]).done(this.async(), failTask('dist:zip'));
    });

    grunt.registerTask('dist:npm', 'Create npm tarball', function () {
        var filename = 'mountebank-v' + version + '-npm.tar.gz';

        run('tar', ['czf', filename, 'mountebank'], { cwd: 'dist' }).done(this.async(), failTask('dist:npm'));
    });

    grunt.registerTask('dist:package', 'Create OS-specific package', function (type) {
        run('scripts/dist/createPackage', [os.platform(), type, version]).done(this.async(), failTask('dist:package'));
    });
};
<commit_msg>Trying to improve Windows MAX_PATH issues with zip files<commit_after>'use strict';

var fs = require('fs-extra'),
    os = require('os'),
    isWindows = require('os').platform().indexOf('win') === 0,
    path = require('path'),
    thisPackage = require('../package.json'),
    version = process.env.MB_VERSION || thisPackage.version,
    run = require('./run').run;

function rmdirRecursiveSync (dir) {
    if (isWindows) {
        if (!fs.existsSync(dir)) {
            return;
        }

        fs.readdirSync(dir).forEach(function (file) {
            var filePath = path.join(dir, file);

            if (fs.lstatSync(filePath).isDirectory()) {
                rmdirRecursiveSync(filePath);
            } else {
                fs.unlinkSync(filePath);
            }
        });

        fs.rmdirSync(dir);
    }
    else {
        // This doesn't appear to work on Windows
        fs.removeSync(dir);
    }
}

module.exports = function (grunt) {

    function failTask (task) {
        return function (exitCode) {
            grunt.warn(task + ' failed', exitCode);
        };
    }

    grunt.registerTask('dist', 'Create trimmed down distribution directory', function () {
        var done = this.async(),
            newPackage = JSON.parse(JSON.stringify(thisPackage)),
            failed = failTask('dist');

        // This doesn't work on Windows
        rmdirRecursiveSync('dist');
        fs.mkdirSync('dist');
        fs.mkdirSync('dist/mountebank');
        ['bin', 'src', 'package.json', 'releases.json', 'README.md', 'LICENSE'].forEach(function (source) {
            fs.copySync(source, 'dist/mountebank/' + source);
        });
        rmdirRecursiveSync('dist/mountebank/src/public/images/sources');

        // removing devDependencies so the standard npm install (without --production) is smooth
        // in all cases.  The jsdom dependency gets tricky otherwise, since we need different versions
        // based on different versions of node
        delete newPackage.devDependencies;
        delete newPackage.devDependenciesBasedOnNodeVersion;
        fs.writeFileSync('dist/mountebank/package.json', JSON.stringify(newPackage, null, 2));

        run('npm', ['install', '--production'], { cwd: 'dist/mountebank' }).then(function () {
            // This helps trim the package size, but more importantly it reduces the longest path
            // (from 176 -> 109 when I wrote this), which is critical to getting this to run on Windows
            // with its MAX_PATH of 260 characters.  It's unusable as a zip file without this.
            return run('npm', ['dedupe'], {cwd: 'dist/mountebank'});
        }).done(function () {
            // Switch tests to use the mb from the dist directory to test what actually gets published
            process.env.MB_EXECUTABLE = 'dist/mountebank/bin/mb';
            done();
        }, failed);
    });

    grunt.registerTask('version', 'Set the version number', function () {
        var newPackage = require('../dist/mountebank/package.json');

        newPackage.version = version;
        console.log('Using version ' + version);
        fs.writeFileSync('./dist/mountebank/package.json', JSON.stringify(newPackage, null, 2) + '\n');
    });

    grunt.registerTask('dist:tarball', 'Create OS-specific tarballs', function (arch) {
        run('scripts/dist/createSelfContainedTarball', [os.platform(), arch || os.arch(), version]).done(
            this.async(), failTask('dist:tarball'));
    });

    grunt.registerTask('dist:zip', 'Create OS-specific zips', function (arch) {
        run('scripts/dist/createWindowsZip', [arch, version]).done(this.async(), failTask('dist:zip'));
    });

    grunt.registerTask('dist:npm', 'Create npm tarball', function () {
        var filename = 'mountebank-v' + version + '-npm.tar.gz';

        run('tar', ['czf', filename, 'mountebank'], { cwd: 'dist' }).done(this.async(), failTask('dist:npm'));
    });

    grunt.registerTask('dist:package', 'Create OS-specific package', function (type) {
        run('scripts/dist/createPackage', [os.platform(), type, version]).done(this.async(), failTask('dist:package'));
    });
};
<|endoftext|>


<commit_before>let config = Space.configuration;

if (Meteor.isServer) {
  winston = Npm.require('winston');
}

Space.Logger = Space.Object.extend(Space, 'Logger', {

  _logger: null,
  _minLevel: 6,
  _state: 'stopped',

  Constructor() {
    if (Meteor.isServer) {
      this._logger = new (winston.Logger)({
        transports: [
          new (winston.transports.Console)({
            colorize: true,
            prettyPrint: true
          })
        ]
      });
      this._logger.setLevels(winston.config.syslog.levels);
    }
    if (Meteor.isClient) {
      this._logger = console;
    }
  },

  setMinLevel(name) {
    let newCode = this._levelCode(name)
    if (this._minLevel !== newCode) {
      this._minLevel = newCode;
      if (Meteor.isServer) {
        this._logger.transports.Console.level = name;
      }
    }
  },

  start() {
    if (this._state === 'stopped') {
      this._state = 'running';
    }
  },

  stop() {
    if (this._state === 'running') {
      this._state = 'stopped';
    }
  },

  debug(message, meta) {
    check(message, String);
    if (this._isRunning()) this._logger.debug.apply(this, arguments);
  },

  info(message, meta) {
    check(message, String);
    if (this._isRunning()) this._logger.info.apply(this, arguments);
  },

  notice(message, meta) {
    check(message, String);
    if (this._isRunning()) this._logger.notice.apply(this, arguments);
  },

  warning(message, meta) {
    check(message, String);
    if (this._isRunning()) this._logger.warning.apply(this, arguments);
  },

  error(message, meta) {
    check(message, String);
    if (this._isRunning()) this._logger.error.apply(this, arguments);
  },

  crit(message, meta) {
    check(message, String);
    if (this._isRunning()) this._logger.crit.apply(this, arguments);
  },

  alert(message, meta) {
    check(message, String);
    if (this._isRunning()) this._logger.alert.apply(this, arguments);
  },

  emerg(message, meta) {
    check(message, String);
    if (this._isRunning()) this._logger.emerg.apply(this, arguments);
  },

  _levelCode(name) {
    let code = {
      'emerg': 0,
      'alert': 1,
      'crit': 2,
      'error': 3,
      'warning': 4,
      'notice': 5,
      'info':6,
      'debug': 7
    }
    return code[name];
  },

  _isRunning() {
    if (this._state === 'running') return true;
  }

});

// System log
Space.log = new Space.Logger();

if (config.log.enabled) {
  Space.log.setMinLevel(config.log.minLevel);
  Space.log.start();
}
<commit_msg>fixes style guide issues in logger file<commit_after>let config = Space.configuration;

if (Meteor.isServer) {
  winston = Npm.require('winston');
}

Space.Object.extend(Space, 'Logger', {

  _logger: null,
  _minLevel: 6,
  _state: 'stopped',

  Constructor() {
    if (Meteor.isServer) {
      this._logger = new winston.Logger({
        transports: [
          new (winston.transports.Console)({
            colorize: true,
            prettyPrint: true
          })
        ]
      });
      this._logger.setLevels(winston.config.syslog.levels);
    }
    if (Meteor.isClient) {
      this._logger = console;
    }
  },

  setMinLevel(name) {
    let newCode = this._levelCode(name);
    if (this._minLevel !== newCode) {
      this._minLevel = newCode;
      if (Meteor.isServer) {
        this._logger.transports.console.level = name;
      }
    }
  },

  start() {
    if (this._state === 'stopped') {
      this._state = 'running';
    }
  },

  stop() {
    if (this._state === 'running') {
      this._state = 'stopped';
    }
  },

  debug(message) {
    check(message, String);
    if (this._isRunning()) this._logger.debug.apply(this, arguments);
  },

  info(message) {
    check(message, String);
    if (this._isRunning()) this._logger.info.apply(this, arguments);
  },

  notice(message) {
    check(message, String);
    if (this._isRunning()) this._logger.notice.apply(this, arguments);
  },

  warning(message) {
    check(message, String);
    if (this._isRunning()) this._logger.warning.apply(this, arguments);
  },

  error(message) {
    check(message, String);
    if (this._isRunning()) this._logger.error.apply(this, arguments);
  },

  crit(message) {
    check(message, String);
    if (this._isRunning()) this._logger.crit.apply(this, arguments);
  },

  alert(message) {
    check(message, String);
    if (this._isRunning()) this._logger.alert.apply(this, arguments);
  },

  emerg(message) {
    check(message, String);
    if (this._isRunning()) this._logger.emerg.apply(this, arguments);
  },

  _levelCode(name) {
    let code = {
      'emerg': 0,
      'alert': 1,
      'crit': 2,
      'error': 3,
      'warning': 4,
      'notice': 5,
      'info': 6,
      'debug': 7
    };
    return code[name];
  },

  _isRunning() {
    if (this._state === 'running') return true;
  }

});

// System log
Space.log = new Space.Logger();

if (config.log.enabled) {
  Space.log.setMinLevel(config.log.minLevel);
  Space.log.start();
}
<|endoftext|>


<commit_before>'use babel'
import fs from 'fs-plus'

export default function(file) {
  const basePath = file.path.replace(/src\/.*$/, 'node_modules/lodash')
  const paths = fs.listSync(basePath)
  const names = paths.filter(fileName => fileName.endsWith('.js')).map(path => {
    return {
      // docs: fs.readFileSync(path).toString(),
      name: path.replace(/.*\//, '').replace('.js', '')
    }
  })
  return names
}
<commit_msg>uses rootPath for lodash<commit_after>'use babel'
/* global atom */
import fs from 'fs-plus'

export default function(file) {
  const rootPath = atom.project.rootDirectories[0].path

  const basePath = rootPath + '/node_modules/lodash'
  const paths = fs.listSync(basePath)
  const names = paths.filter(fileName => fileName.endsWith('.js')).map(path => {
    return {
      // docs: fs.readFileSync(path).toString(),
      name: path.replace(/.*\//, '').replace('.js', '')
    }
  })
  return names
}
<|endoftext|>


<commit_before>/* ***************************************
 * CLASS: DOM -> OUTSITE
 * ***************************************/
class Dom_OUTSITE extends Dom_INSITE
{
	constructor ()
	{
		let self = super();

		self.after 				= ( content ) => {

			// Start timing now
			console.time("EXECUTION_TIME_AFTER");

		 	(self.element.length >= 1) &&
		 	self.element.forEach(( element ) => {

		 		element.insertAdjacentHTML('afterend',content);

		 	});

		 	return self;

		 	// Start timing now
			console.timeEnd("EXECUTION_TIME_AFTER");
		} //afterend

		self.before 			= ( content ) => {

			// Start timing now
			console.time("EXECUTION_TIME_BEFORE");

			(self.element.length >= 1) &&
		 	self.element.forEach(( element ) => {

		 		element.insertAdjacentHTML('beforebegin',content);

		 	});

		 	return self;

		 	// Start timing now
			console.timeEnd("EXECUTION_TIME_BEFORE");

		} //beforebegin

		self.insertAfter 		= ( content ) => {

			// Start timing now
			console.time("EXECUTION_TIME_INSERTAFTER");

			let cacheContent 	= $(content);
			let html 			= cacheContent.html();
			cacheContent.remove();

			(self.element.length >= 1) &&
		 	self.element.forEach(( element ) => {

		 		element.insertAdjacentHTML('beforebegin',html);

		 	});

			// Start timing now
			console.timeEnd("EXECUTION_TIME_INSERTAFTER");
		}

		self.insertBefore 		= ( content ) => {

			// Start timing now
			console.time("EXECUTION_TIME_INSERTBEFORE");

			let cacheContent 	= $(content);
			let html 			= cacheContent.html();
			cacheContent.remove();

			(self.element.length >= 1) &&
		 	self.element.forEach(( element ) => {

		 		element.insertAdjacentHTML('afterend',html);

		 	});

			// Start timing now
			console.timeEnd("EXECUTION_TIME_INSERTBEFORE");
		}

		return self;
	}
}<commit_msg>Delete 07_4_Dom_OUTSITE.js<commit_after><|endoftext|>


<commit_before>import { parseLocation } from 'routes/location';
import Handler from 'routes/route-handler';
import { getRouteMap, mapRoutes, resetRouteMap, setNotFound } from 'routes/route-map';
import History from './routes/history';
import { addAfterEach, addBeforeEach, resetHooks } from './routes/global-hooks';
import pjax from './routes/pjax';
import { $ready } from 'core/dom';

export let history = new History();
let hasPjax = false;

/**
 * Set base configurations for router
 *
 * @param {Object} config
 * @returns {router}
 */
function router(config = {}) {
	return router;
}

/**
 * Register global after hook
 *
 * @param {Function} fn
 * @returns {router}
 */
router.afterEach = function registerAfterEach(fn) {
	addAfterEach(fn);

	return this;
}

/**
 * Register global before hook
 *
 * @param {Function} fn
 * @returns {router}
 */
router.beforeEach = function registerBeforeEach(fn) {
	addBeforeEach(fn);

	return this;
};

/**
 * Retrieve current route
 *
 * @returns {Object}
 */
router.currentRoute = function currentRoute() {
	return history.current;
}

// TODO: Change map to register
/**
 * Register routes
 *
 * @param {Array} routes
 * @returns {router}
 */
router.map = function routerMap(routes) {
	mapRoutes(routes);

	return this;
}

/**
 * Set the catch all route that is matched if no other routes match
 *
 * @param {Object} route
 * @returns {router}
 */
router.notFound = function notFound(route) {
	route.path = '*';
	route.name = 'notFound';

	setNotFound(route);

	return this;
}

/**
 * Configure and initialize pjax navigation
 *
 * @param {Object} config
 * @returns {router}
 */
router.pjax = function initPjax(config = {}) {
	// Prevent initializing pjax multiple times
	if (! hasPjax) {
		hasPjax = pjax.init(config);

		if (hasPjax) {
			// Prep pjax after initialization of routes
			this.onReady(() => {
				pjax.onTrigger = function onPjaxTrigger(destination) {
					// TODO: Handle PJAX specific errors here? history.push returns promise
					history.push(destination);
				};

				history.begin = pjax.go;
				history.replacePage = pjax.replace;
			});
		}
	}

	return this;
}

/**
 * Register callbacks to be executed on ready
 *
 * @param {Function} success
 * @param {Function} [error]
 */
router.onReady = function onReady(success, error) {
	history.onReady(success, error);
}

/**
 * Navigate to URL and add item to history
 *
 * @param {string|Object} path
 * @returns {*}
 */
router.push = function push(path) {
	return history.push(path);
}

/**
 * Navigate to URL and add item to history
 *
 * @param {string|Object} path
 * @returns {*}
 */
router.replace = function replace(path) {
	return history.replace(path);
}

/**
 * Reset all routes - mainly for testing purposes
 */
router.reset = function reset() {
	resetRouteMap();
	resetHooks();
	hasPjax = false;
	pjax.reset();
	window.removeEventListener('popstate', history.popstate);
	history = new History();
}

/**
 * Retrieve all routes or specific route by name/path
 *
 * @param {string} [value]
 * @param {string} keyType
 * @returns {Object|Array}
 */
router.routes = function routes(key, keyType = 'path') {
	let routeMaps = getRouteMap();
	let map;

	if (key) {
		if (routeMaps.pathMap.hasOwnProperty(key)) {
			return routeMaps.pathMap[key];
		} else if (routeMaps.nameMap.hasOwnProperty(key)) {
			return routeMaps.nameMap[key];
		} else {
			return null;
		}
	}

	if (keyType === 'path') {
		map = routeMaps.pathMap;
	} else if (keyType === 'name') {
		map = routeMaps.nameMap;
	} else if (keyType === 'list') {
		map = routeMaps.pathList;
	}

	return map;
}

/**
 * Evaluate mapped routes against current or provided URL
 *
 * @param {string} value
 * @returns {router}
 */
router.run = function runRoutes(value) {
	if (! value) {
		// Process routes when document is loaded
		$ready(() => {
			history.navigate(this.uri().full);
		});

		return this;
	}

	// TODO: This is going to set the state of the current route in history
	// TODO: I don't think that will be desirable
	// TODO: Do we need a way to evaluate routes without changing history state?
	// const { pathMap, nameMap } = getRouteMap();
	//
	// if (pathMap[value]) {
	// 	history.navigate(value);
	// } else if (nameMap[value]) {
	// 	history.navigate(value);
	// }
}

// TODO: Perhaps break out location methods into own module
/**
 * Retrieve the current path's segments as an array or segment by index
 *
 * @param index
 * @returns {Array|string}
 */
router.segments = function uriSegments(index) {
	const segments = this.uri().segments;

	if (index >= 0 && segments[index]) {
		return segments[index];
	}

	return segments;
}

/**
 * Retrieve information about current location
 *
 * @param {string} [value]
 * @returns {Object}
 */
router.uri = function uri(value) {
	return parseLocation(value);
}

export default router;
export const RouteHandler = Handler;<commit_msg>Return router in onReady function<commit_after>import { parseLocation } from 'routes/location';
import Handler from 'routes/route-handler';
import { getRouteMap, mapRoutes, resetRouteMap, setNotFound } from 'routes/route-map';
import History from './routes/history';
import { addAfterEach, addBeforeEach, resetHooks } from './routes/global-hooks';
import pjax from './routes/pjax';
import { $ready } from 'core/dom';

export let history = new History();
let hasPjax = false;

/**
 * Set base configurations for router
 *
 * @param {Object} config
 * @returns {router}
 */
function router(config = {}) {
	return router;
}

/**
 * Register global after hook
 *
 * @param {Function} fn
 * @returns {router}
 */
router.afterEach = function registerAfterEach(fn) {
	addAfterEach(fn);

	return this;
}

/**
 * Register global before hook
 *
 * @param {Function} fn
 * @returns {router}
 */
router.beforeEach = function registerBeforeEach(fn) {
	addBeforeEach(fn);

	return this;
};

/**
 * Retrieve current route
 *
 * @returns {Object}
 */
router.currentRoute = function currentRoute() {
	return history.current;
}

// TODO: Change map to register
/**
 * Register routes
 *
 * @param {Array} routes
 * @returns {router}
 */
router.map = function routerMap(routes) {
	mapRoutes(routes);

	return this;
}

/**
 * Set the catch all route that is matched if no other routes match
 *
 * @param {Object} route
 * @returns {router}
 */
router.notFound = function notFound(route) {
	route.path = '*';
	route.name = 'notFound';

	setNotFound(route);

	return this;
}

/**
 * Configure and initialize pjax navigation
 *
 * @param {Object} config
 * @returns {router}
 */
router.pjax = function initPjax(config = {}) {
	// Prevent initializing pjax multiple times
	if (! hasPjax) {
		hasPjax = pjax.init(config);

		if (hasPjax) {
			// Prep pjax after initialization of routes
			this.onReady(() => {
				pjax.onTrigger = function onPjaxTrigger(destination) {
					// TODO: Handle PJAX specific errors here? history.push returns promise
					history.push(destination);
				};

				history.begin = pjax.go;
				history.replacePage = pjax.replace;
			});
		}
	}

	return this;
}

/**
 * Register callbacks to be executed on ready
 *
 * @param {Function} success
 * @param {Function} [error]
 */
router.onReady = function onReady(success, error) {
	history.onReady(success, error);

	return this;
}

/**
 * Navigate to URL and add item to history
 *
 * @param {string|Object} path
 * @returns {*}
 */
router.push = function push(path) {
	return history.push(path);
}

/**
 * Navigate to URL and add item to history
 *
 * @param {string|Object} path
 * @returns {*}
 */
router.replace = function replace(path) {
	return history.replace(path);
}

/**
 * Reset all routes - mainly for testing purposes
 */
router.reset = function reset() {
	resetRouteMap();
	resetHooks();
	hasPjax = false;
	pjax.reset();
	window.removeEventListener('popstate', history.popstate);
	history = new History();
}

/**
 * Retrieve all routes or specific route by name/path
 *
 * @param {string} [value]
 * @param {string} keyType
 * @returns {Object|Array}
 */
router.routes = function routes(key, keyType = 'path') {
	let routeMaps = getRouteMap();
	let map;

	if (key) {
		if (routeMaps.pathMap.hasOwnProperty(key)) {
			return routeMaps.pathMap[key];
		} else if (routeMaps.nameMap.hasOwnProperty(key)) {
			return routeMaps.nameMap[key];
		} else {
			return null;
		}
	}

	if (keyType === 'path') {
		map = routeMaps.pathMap;
	} else if (keyType === 'name') {
		map = routeMaps.nameMap;
	} else if (keyType === 'list') {
		map = routeMaps.pathList;
	}

	return map;
}

/**
 * Evaluate mapped routes against current or provided URL
 *
 * @param {string} value
 * @returns {router}
 */
router.run = function runRoutes(value) {
	if (! value) {
		// Process routes when document is loaded
		$ready(() => {
			history.navigate(this.uri().full);
		});

		return this;
	}

	// TODO: This is going to set the state of the current route in history
	// TODO: I don't think that will be desirable
	// TODO: Do we need a way to evaluate routes without changing history state?
	// const { pathMap, nameMap } = getRouteMap();
	//
	// if (pathMap[value]) {
	// 	history.navigate(value);
	// } else if (nameMap[value]) {
	// 	history.navigate(value);
	// }
}

// TODO: Perhaps break out location methods into own module
/**
 * Retrieve the current path's segments as an array or segment by index
 *
 * @param index
 * @returns {Array|string}
 */
router.segments = function uriSegments(index) {
	const segments = this.uri().segments;

	if (index >= 0 && segments[index]) {
		return segments[index];
	}

	return segments;
}

/**
 * Retrieve information about current location
 *
 * @param {string} [value]
 * @returns {Object}
 */
router.uri = function uri(value) {
	return parseLocation(value);
}

export default router;
export const RouteHandler = Handler;<|endoftext|>


<commit_before>/*
 Copyright (c) 2015, Kotaro Endo.
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.

 3. Neither the name of the copyright holder nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

'use strict';

var binding = process.binding('udp_wrap');
//var basePort = new IOPort('udp_wrap');
<commit_msg>implements udp_wrap bridge<commit_after>/*
 Copyright (c) 2015, Kotaro Endo.
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.

 3. Neither the name of the copyright holder nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

'use strict';

var binding = process.binding('udp_wrap');
var basePort = new IOPort('udp_wrap');

binding.SendWrap = function() {
	this.domain = process.domain;
};

binding.UDP = UDP;

function UDP() {
	var self = this;
	self._state = {};
	self._port = basePort.open('UDP', function(event, args) {
		if (event instanceof IOPortError) {
			if (event.message === 'restart') {
				args.asyncIO('restart', [ self._state ]);
			}
			return;
		}
		self[event].apply(self, args);
	});
}

UDP.prototype.close = function() {
	return this._port.syncIO('close', []);
};

UDP.prototype.ref = function() {
	this._port.syncIO('ref', []);
	this._state.unref = false;
};

UDP.prototype.unref = function() {
	this._port.syncIO('unref', []);
	this._state.unref = true;
};

UDP.prototype.recvStart = function() {
	return this._port.syncIO('recvStart', []);
};

UDP.prototype.recvStop = function() {
	return this._port.syncIO('recvStop', []);
};

UDP.prototype.bind = function() {
	var err = this._port.syncIO('bind', arguments);
	if (!err) {
		this._state.bindArgs = arguments;
	}
	return err;
};

UDP.prototype.bind6 = function() {
	var err = this._port.syncIO('bind6', arguments);
	if (!err) {
		this._state.bind6Args = arguments;
	}
	return err;
};

UDP.prototype.getsockname = function(out) {
	var res = this._port.syncIO('getsockname', []);
	for ( var n in res.out) {
		out[n] = res.out[n];
	}
	return res.err;
};

UDP.prototype.setBroadcast = function() {
	return this._port.syncIO('setBroadcast', arguments);
};

UDP.prototype.setTTL = function() {
	return this._port.syncIO('setTTL', arguments);
};

UDP.prototype.addMembership = function() {
	return this._port.syncIO('addMembership', arguments);
};

UDP.prototype.dropMembership = function() {
	return this._port.syncIO('dropMembership', arguments);
};

UDP.prototype.setMulticastTTL = function() {
	return this._port.syncIO('setMulticastTTL', arguments);
};

UDP.prototype.setMulticastLoopback = function() {
	return this._port.syncIO('setMulticastLoopback', arguments);
};

function sendCall(self, req, func, buffer, offset, length, port, ip) {
	var data = buffer.slice(offset, length - offset);
	self._port.asyncIO('send', [ func, data, port, ip ], function(err) {
		if (err instanceof IOPortError) {
			err = -1;
		}
		process._MakeCallback(req.domain, function() {
			req.oncomplete(err);
		});
	});
	return 0;
};

UDP.prototype.send = function(req, buffer, offset, length, port, ip, isCallback) {
	return sendCall(this, req, 'send', buffer, offset, length, port, ip);
};

UDP.prototype.send6 = function(req, buffer, offset, length, port, ip, isCallback) {
	return sendCall(this, req, 'send6', buffer, offset, length, port, ip);
};
<|endoftext|>


<commit_before>export function clockwise(polygon) {

    var _polygon = polygon.slice(0), sum = 0;

    _polygon.push(_polygon[0]);

    for (var i = polygon.length - 1; i >= 0; i--) {

        var p1 = _polygon[i].rotated;
        var p2 = _polygon[i + 1].rotated;

        sum += (p2.x - p1.x)*(p2.y + p1.y);
    }

    return sum > 0 ? true : false;
}
<commit_msg>rename vars<commit_after>export function clockwise(polygon) {

    var _polygon = polygon.slice(0), sum = 0;

    _polygon.push(_polygon[0]);

    for (var i = polygon.length - 1; i >= 0; i--) {
        var j  = i + 1;
        var p1 = _polygon[i].rotated;
        var p2 = _polygon[j].rotated;

        sum += (p2.x - p1.x) * (p2.y + p1.y);
    }

    return sum > 0 ? true : false;
}
<|endoftext|>