<commit_before>'use strict';

var bench = require('./index');

var expect = require('chai').expect;
var File = require('gulp-util').File;
var Benchmark = require('benchmark');

var globalTestSuite;

it('load - single benchmark', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/benchmark-single.js'}));
  stream.end();
});

it('load - benchmark suite', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/benchmark-suite.js'}));
  stream.end();
});

it('load - grunt-benchmark - single function', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-single-function.js'}));
  stream.end();
});

it('load - grunt-benchmark - single test with options', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-single-test-with-options.js'}));
  stream.end();
});

it('load - grunt-benchmark - test suite with array of functions', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-test-suite-with-array-of-functions.js'}));
  stream.end();
});

it('load - grunt-benchmark - test suite with array of objects', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-test-suite-with-array-of-objects.js'}));
  stream.end();
});

it('load - grunt-benchmark - test suite with object', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-test-suite-with-object.js'}));
  stream.end();
});

it('run', function (cb) {
  this.timeout(20000);

  var runStream = bench.run()

  runStream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      expect(output).to.not.have.property('error');
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  var loadStream = bench.load();

  loadStream.on('data', function(output) {
    runStream.write(output);
    runStream.end();
  });

  loadStream.write(new File({path: './test-data/grunt-benchmark-single-test-with-options.js'}));
  loadStream.end();
});

it('report - etalon', function () {
  var stream = bench.report(bench.reporters.etalon('RegExp#test'));
  stream.write(require('./test-data/run-statistic'));
  stream.end();
});

it('report - fastest', function () {
  var stream = bench.report(bench.reporters.fastest());
  stream.write(require('./test-data/run-statistic'));
  stream.end();
});
<commit_msg>Test more than one reporter<commit_after>'use strict';

var bench = require('./index');

var expect = require('chai').expect;
var File = require('gulp-util').File;
var Benchmark = require('benchmark');

var globalTestSuite;

it('load - single benchmark', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/benchmark-single.js'}));
  stream.end();
});

it('load - benchmark suite', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/benchmark-suite.js'}));
  stream.end();
});

it('load - grunt-benchmark - single function', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-single-function.js'}));
  stream.end();
});

it('load - grunt-benchmark - single test with options', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-single-test-with-options.js'}));
  stream.end();
});

it('load - grunt-benchmark - test suite with array of functions', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-test-suite-with-array-of-functions.js'}));
  stream.end();
});

it('load - grunt-benchmark - test suite with array of objects', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-test-suite-with-array-of-objects.js'}));
  stream.end();
});

it('load - grunt-benchmark - test suite with object', function (cb) {
  this.timeout(20000);

  var stream = bench.load();

  stream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  stream.write(new File({path: './test-data/grunt-benchmark-test-suite-with-object.js'}));
  stream.end();
});

it('run', function (cb) {
  this.timeout(20000);

  var runStream = bench.run()

  runStream.on('data', function (output) {
    try {
      expect(output).to.be.instanceof(Benchmark.Suite);
      expect(output).to.not.have.property('error');
      cb();
    }
    catch (err) {
      cb(err);
    }
  });

  var loadStream = bench.load();

  loadStream.on('data', function(output) {
    runStream.write(output);
    runStream.end();
  });

  loadStream.write(new File({path: './test-data/grunt-benchmark-single-test-with-options.js'}));
  loadStream.end();
});

it('report - etalon', function () {
  var stream = bench.report(bench.reporters.etalon('RegExp#test'));
  stream.write(require('./test-data/run-statistic'));
  stream.end();
});

it('report - fastest', function () {
  var stream = bench.report(bench.reporters.fastest());
  stream.write(require('./test-data/run-statistic'));
  stream.end();
});

it('report - etalon and fastest', function () {
  var stream = bench.report([bench.reporters.etalon('RegExp#test'), bench.reporters.fastest()]);
  stream.write(require('./test-data/run-statistic'));
  stream.end();
});
<|endoftext|>


<commit_before>/**
 * Activates typeahead behavior for given element.
 * @param element The DOM element to modify.
 */
Meteor.typeahead = function(element){
	var $e = $(element);
	var name = $e.attr('name') || $e.attr('id') || 'dataset';
	var limit = $e.data('limit') || 5;
	var template = $e.data('template'); // specifies name of custom template
	var data = $e.data('source');

	var dataset = {
		name: name,
		limit: limit,
		local: data
	};

	// support for custom templates
	if (template && Template[template]) {
		dataset.template = template;
		// meet typeahead template engine API to be Hogan compatible
		dataset.engine = {
			compile: function(){
				var tmpl = Template[template];
				return {
					render: function(context){
						return tmpl(context);
					}
				};
			}
		};
	}

	$e.typeahead(dataset);

	// fix to apply bootstrap form-control to tt-hint
	// TODO support other classes if needed
	if ($e.hasClass('form-control')){
		$e.parent('.twitter-typeahead').find('.tt-hint').addClass('form-control');
	}
};<commit_msg>support multiple datasets<commit_after>function fixstyles($e){
	// fix to apply bootstrap form-control to tt-hint
	// TODO support other classes if needed
	if ($e.hasClass('form-control')){
		$e.parent('.twitter-typeahead').find('.tt-hint').addClass('form-control');
	}
}

/**
 * Activates typeahead behavior for given element.
 * @param element The DOM element to modify.
 */
Meteor.typeahead = function(element){
	var $e = $(element);

	var datasets = $e.data('sets');
	if (datasets){
		$e.typeahead(datasets);
		fixstyles($e);
		return;
	}

	var name = $e.attr('name') || $e.attr('id') || 'dataset';
	var limit = $e.data('limit') || 5;
	var template = $e.data('template'); // specifies name of custom template
	var data = $e.data('source');

	var dataset = {
		name: name,
		limit: limit,
		local: data
	};

	// support for custom templates
	if (template && Template[template]) {
		dataset.template = template;
		// meet typeahead template engine API to be Hogan compatible
		dataset.engine = {
			compile: function(){
				var tmpl = Template[template];
				return {
					render: function(context){
						return tmpl(context);
					}
				};
			}
		};
	}

	$e.typeahead(dataset);
	fixstyles($e);
};<|endoftext|>


<commit_before>var tape = require('tape')
var plaintemplate = require('./')

tape('without tags', function(test) {
  plaintemplate()(
    'Just text. No templating.',
    { },
    function(error, result) {
      test.error(error)
      test.equal(result, 'Just text. No templating.')
      test.end() }) })

tape('one insert', function(test) {
  plaintemplate()(
    'Hello, <% insert name %>!',
    { name: 'John' },
    function(error, result) {
      test.equal(result, 'Hello, John!')
      test.end() }) })

tape('error on insert nonexistent', function(test) {
  plaintemplate()(
    'Hello, <% insert name %>!',
    { },
    function(error) {
      test.assert(
        /No variable "name" at line 1, column 8/
          .test(error.message))
      test.end() }) })

tape('two inserts', function(test) {
  plaintemplate()(
    'Hello, <% insert first %> <%insert last%>.',
    { first: 'John', last: 'Doe' },
    function(error, result) {
      test.error(error)
      test.equal(result, 'Hello, John Doe.')
      test.end() }) })

tape('two inserts across lines', function(test) {
  plaintemplate()(
    'Hello, <% insert name%>!\nHow is <% insert state %>?',
    { name: 'John', state: 'Kentucky' },
    function(error, result) {
      test.error(error)
      test.equal(result, 'Hello, John!\nHow is Kentucky?')
      test.end() }) })

tape('if then insert', function(test) {
  plaintemplate()(
    '<% if onsale { %>Price: $<% insert price %><% } %>',
    { onsale: true, price: '100' },
    function(error, result) {
      test.equal(result, 'Price: $100')
      test.end() }) })

tape('if nonexistent error', function(test) {
  plaintemplate()(
    '<% if onsale { %>x<% } %>',
    { },
    function(error) {
      test.assert(
        /No variable "onsale" at line 1, column 1/
          .test(error.message))
      test.end() }) })

tape('unless then insert', function(test) {
  plaintemplate()(
    '<% unless onsale { %>Price: $<% insert price %><% } %>',
    { onsale: true, price: '100' },
    function(error, result) {
      test.error(error)
      test.equal(result, '')
      test.end() }) })

tape('unless nonexistent error', function(test) {
  plaintemplate()(
    '<% unless onsale { %>x<% } %>',
    { },
    function(error) {
      test.assert(
        /No variable "onsale" at line 1, column 1/
          .test(error.message))
      test.end() }) })

tape('custom parser delimiters', function(test) {
  var processor = plaintemplate(
    undefined,
    { open: '{{',
      close: '}}',
      start: 'start',
      end: 'end' })
  processor(
    '{{ if onsale start }}Price: ${{ insert price }}{{ end }}',
    { onsale: true, price: '100' },
    function(error, result) {
      test.error(error)
      test.equal(result, 'Price: $100')
      test.end() }) })

tape('each', function(test) {
  plaintemplate()(
    ( '<% each people { %>' +
        '<% unless first { %>' +
          '<% if last { %>, and <% } %>' +
          '<% unless last { %>, <% } %>' +
        '<% } %>' +
        '<% insert element %>' +
      '<% } %>' ),
    { people: [ 'John', 'Paul', 'George', 'Ringo' ] },
    function(error, result) {
      test.error(error)
      test.equal(result, 'John, Paul, George, and Ringo')
      test.end() }) })

tape('each nonexistent error', function(test) {
  plaintemplate()(
    '<% each items { %>x<% } %>',
    { },
    function(error) {
      test.assert(
        /No variable "items" at line 1, column 1/
          .test(error.message))
      test.end() }) })

tape('each non-Array errors', function(test) {
  plaintemplate()(
    '<% each items { %>x<% } %>',
    { items: false },
    function(error) {
      test.assert(
        /Variable "items" is not an Array at line 1, column 1/
          .test(error.message))
      test.end() }) })

tape('nested if nonexistent error', function(test) {
  plaintemplate()(
    '<% each items { %><% if second { %>x<% } %><% } %>',
    { items: [ true ] },
    function(error) {
      test.assert(
        /No variable "second" at line 1, column 19/
          .test(error.message))
      test.end() }) })

tape('unknown directive', function(test) {
  plaintemplate()(
    '<% blah %>',
    { },
    function(error) {
      test.assert(
        /Unknown directive "blah" at line 1, column 1/
          .test(error.message))
      test.end() }) })

tape('custom tag handler', function(test) {
  var processor =plaintemplate(
    function(token, context, stringify, callback) {
      callback(null, context.happy) })
  processor(
    '<% super %> <% duper %>',
    { happy: 'Happy!' },
    function(error, result) {
      test.error(error)
      test.equal(result, 'Happy! Happy!')
      test.end() }) })
<commit_msg>Annotate test assertions<commit_after>var tape = require('tape')
var plaintemplate = require('./')

tape('without tags', function(test) {
  plaintemplate()(
    'Just text. No templating.',
    { },
    function(error, result) {
      test.error(error, 'no error')
      test.equal(result, 'Just text. No templating.')
      test.end() }) })

tape('one insert', function(test) {
  plaintemplate()(
    'Hello, <% insert name %>!',
    { name: 'John' },
    function(error, result) {
      test.error(error, 'no error')
      test.equal(result, 'Hello, John!')
      test.end() }) })

tape('error on insert nonexistent', function(test) {
  plaintemplate()(
    'Hello, <% insert name %>!',
    { },
    function(error) {
      test.assert(
        /No variable "name" at line 1, column 8/
          .test(error.message),
        'yields error')
      test.end() }) })

tape('two inserts', function(test) {
  plaintemplate()(
    'Hello, <% insert first %> <%insert last%>.',
    { first: 'John', last: 'Doe' },
    function(error, result) {
      test.error(error, 'no error')
      test.equal(result, 'Hello, John Doe.')
      test.end() }) })

tape('two inserts across lines', function(test) {
  plaintemplate()(
    'Hello, <% insert name%>!\nHow is <% insert state %>?',
    { name: 'John', state: 'Kentucky' },
    function(error, result) {
      test.error(error, 'no error')
      test.error(error, 'no error')
      test.equal(result, 'Hello, John!\nHow is Kentucky?')
      test.end() }) })

tape('if then insert', function(test) {
  plaintemplate()(
    '<% if onsale { %>Price: $<% insert price %><% } %>',
    { onsale: true, price: '100' },
    function(error, result) {
      test.error(error, 'no error')
      test.equal(result, 'Price: $100')
      test.end() }) })

tape('if nonexistent error', function(test) {
  plaintemplate()(
    '<% if onsale { %>x<% } %>',
    { },
    function(error) {
      test.assert(
        /No variable "onsale" at line 1, column 1/
          .test(error.message),
        'yields error')
      test.end() }) })

tape('unless then insert', function(test) {
  plaintemplate()(
    '<% unless onsale { %>Price: $<% insert price %><% } %>',
    { onsale: true, price: '100' },
    function(error, result) {
      test.error(error, 'no error')
      test.equal(result, '')
      test.end() }) })

tape('unless nonexistent error', function(test) {
  plaintemplate()(
    '<% unless onsale { %>x<% } %>',
    { },
    function(error) {
      test.assert(
        /No variable "onsale" at line 1, column 1/
          .test(error.message),
        'yields error')
      test.end() }) })

tape('custom parser delimiters', function(test) {
  var processor = plaintemplate(
    undefined,
    { open: '{{',
      close: '}}',
      start: 'start',
      end: 'end' })
  processor(
    '{{ if onsale start }}Price: ${{ insert price }}{{ end }}',
    { onsale: true, price: '100' },
    function(error, result) {
      test.error(error, 'no error')
      test.equal(result, 'Price: $100')
      test.end() }) })

tape('each', function(test) {
  plaintemplate()(
    ( '<% each people { %>' +
        '<% unless first { %>' +
          '<% if last { %>, and <% } %>' +
          '<% unless last { %>, <% } %>' +
        '<% } %>' +
        '<% insert element %>' +
      '<% } %>' ),
    { people: [ 'John', 'Paul', 'George', 'Ringo' ] },
    function(error, result) {
      test.error(error, 'no error')
      test.equal(result, 'John, Paul, George, and Ringo')
      test.end() }) })

tape('each nonexistent error', function(test) {
  plaintemplate()(
    '<% each items { %>x<% } %>',
    { },
    function(error) {
      test.assert(
        /No variable "items" at line 1, column 1/
          .test(error.message),
        'yields error')
      test.end() }) })

tape('each non-Array errors', function(test) {
  plaintemplate()(
    '<% each items { %>x<% } %>',
    { items: false },
    function(error) {
      test.assert(
        /Variable "items" is not an Array at line 1, column 1/
          .test(error.message),
        'yields error')
      test.end() }) })

tape('nested if nonexistent error', function(test) {
  plaintemplate()(
    '<% each items { %><% if second { %>x<% } %><% } %>',
    { items: [ true ] },
    function(error) {
      test.assert(
        /No variable "second" at line 1, column 19/
          .test(error.message),
        'yields error')
      test.end() }) })

tape('unknown directive', function(test) {
  plaintemplate()(
    '<% blah %>',
    { },
    function(error) {
      test.assert(
        /Unknown directive "blah" at line 1, column 1/
          .test(error.message), 'yields error')
      test.end() }) })

tape('custom tag handler', function(test) {
  var processor =plaintemplate(
    function(token, context, stringify, callback) {
      callback(null, context.happy) })
  processor(
    '<% super %> <% duper %>',
    { happy: 'Happy!' },
    function(error, result) {
      test.error(error, 'no error')
      test.equal(result, 'Happy! Happy!')
      test.end() }) })
<|endoftext|>


<commit_before>import Vue from 'vue'
import Vuex from 'vuex'
import calendars from '@/store/modules/calendars'
import user from '@/store/modules/user'
import event from '@/store/modules/event'

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  modules: {
    calendars,
    user,
    event
  },
  strict: debug
})
<commit_msg>Disabling vuex strict mode (task #6034)<commit_after>import Vue from 'vue'
import Vuex from 'vuex'
import calendars from '@/store/modules/calendars'
import user from '@/store/modules/user'
import event from '@/store/modules/event'

Vue.use(Vuex)

/**
 * @Note: had to disable strict mode for vuex, due
 * to vue-select multiple error.
 * @see https://github.com/sagalbot/vue-select/issues/529
 * */
const debug = false

export default new Vuex.Store({
  modules: {
    calendars,
    user,
    event
  },
  strict: debug
})
<|endoftext|>


<commit_before>'use strict';

var TextOMConstructor = require('textom'),
    ParseLatin = require('parse-latin');

function fromAST(TextOM, ast) {
    var iterator = -1,
        children, node;

    node = new TextOM[ast.type]();

    if ('children' in ast) {
        iterator = -1;
        children = ast.children;

        while (children[++iterator]) {
            node.append(fromAST(TextOM, children[iterator]));
        }
    } else {
        node.fromString(ast.value);
    }

    return node;
}

function useImmediately(rootNode, use) {
    return function (plugin) {
        var self = this,
            length = self.plugins.length;

        use.apply(self, arguments);

        if (length !== self.plugins.length) {
            plugin(rootNode, self);
        }

        return self;
    };
}

/**
 * Define `Retext`. Exported above, and used to instantiate a new
 * `Retext`.
 *
 * @param {Function?} parser - the parser to use. Defaults to parse-latin.
 * @api public
 * @constructor
 */
function Retext(parser) {
    var self = this;

    if (!parser) {
        parser = new ParseLatin();
    }

    self.parser = parser;
    self.TextOM = parser.TextOM = new TextOMConstructor();
    self.TextOM.parser = parser;
    self.plugins = [];
}

/**
 * `Retext#use` takes a plugin—a humble function—and when the parse
 * method of the Retext instance is called, the plugin will be called
 * with the parsed tree, and the retext instance as arguments.
 *
 * Note that, during the parsing stage, when the `use` method is called
 * by a plugin, the nested plugin is immediately called, before continuing
 * on with its parent plugin.
 *
 * @param {Function} plugin - the plugin to call when parsing.
 * @param {Function?} plugin.attach - called only once with a Retext
 *                                    instance. If you're planning on
 *                                    modifying TextOM or a parser, do it
 *                                    in this method.
 * @return this
 * @api public
 */
Retext.prototype.use = function (plugin) {
    if (typeof plugin !== 'function') {
        throw new TypeError('Illegal invocation: \'' + plugin +
            '\' is not a valid argument for \'Retext.prototype.use\'');
    }

    var self = this,
        plugins = self.plugins;

    if (plugins.indexOf(plugin) === -1) {
        if (plugin.attach) {
            plugin.attach(self);
        }

        plugins.push(plugin);
    }

    return self;
};

/**
 * `Retext#parse` takes a source to be given (and parsed) by the parser.
 * Then, `parse` iterates over all plugins, and allows them to modify the
 * TextOM tree created by the parser.
 *
 * @param {String?} source - The source to convert.
 * @return {Node} - A RootNode containing the tokenised source.
 * @api public
 */
Retext.prototype.parse = function (source) {
    var self = this,
        rootNode = fromAST(self.TextOM, self.parser.tokenizeRoot(source));

    self.applyPlugins(rootNode);

    return rootNode;
};

/**
 * `Retext#applyPlugins` applies the plugins bound to the retext instance to a
 * given tree.
 *
 * Note that, during the parsing stage, when the `use` plugin is called
 * by a plugin, the nested plugin is immediately called, before continuing
 * on with its parent plugin.
 *
 * @param {Node} tree - The tree to apply plugins to.
 * @api public
 */
Retext.prototype.applyPlugins = function (tree) {
    var self = this,
        plugins = self.plugins.concat(),
        iterator = -1,
        use = self.use;

    self.use = useImmediately(tree, use);

    while (plugins[++iterator]) {
        plugins[iterator](tree, this);
    }

    self.use = use;
};

/**
 * Expose `Retext`. Used to instantiate a new Retext object.
 */
exports = module.exports = Retext;
<commit_msg>Added support for including data properties set by parser (-plugins) on object model<commit_after>'use strict';

var TextOMConstructor = require('textom'),
    ParseLatin = require('parse-latin');

function fromAST(TextOM, ast) {
    var iterator = -1,
        children, node, data, attribute;

    node = new TextOM[ast.type]();

    if ('children' in ast) {
        iterator = -1;
        children = ast.children;

        while (children[++iterator]) {
            node.append(fromAST(TextOM, children[iterator]));
        }
    } else {
        node.fromString(ast.value);
    }

    /* istanbul ignore if: TODO, Untestable, will change soon. */
    if ('data' in ast) {
        data = ast.data;

        for (attribute in data) {
            if (data.hasOwnProperty(attribute)) {
                node.data[attribute] = data[attribute];
            }
        }
    }

    return node;
}

function useImmediately(rootNode, use) {
    return function (plugin) {
        var self = this,
            length = self.plugins.length;

        use.apply(self, arguments);

        if (length !== self.plugins.length) {
            plugin(rootNode, self);
        }

        return self;
    };
}

/**
 * Define `Retext`. Exported above, and used to instantiate a new
 * `Retext`.
 *
 * @param {Function?} parser - the parser to use. Defaults to parse-latin.
 * @api public
 * @constructor
 */
function Retext(parser) {
    var self = this;

    if (!parser) {
        parser = new ParseLatin();
    }

    self.parser = parser;
    self.TextOM = parser.TextOM = new TextOMConstructor();
    self.TextOM.parser = parser;
    self.plugins = [];
}

/**
 * `Retext#use` takes a plugin—a humble function—and when the parse
 * method of the Retext instance is called, the plugin will be called
 * with the parsed tree, and the retext instance as arguments.
 *
 * Note that, during the parsing stage, when the `use` method is called
 * by a plugin, the nested plugin is immediately called, before continuing
 * on with its parent plugin.
 *
 * @param {Function} plugin - the plugin to call when parsing.
 * @param {Function?} plugin.attach - called only once with a Retext
 *                                    instance. If you're planning on
 *                                    modifying TextOM or a parser, do it
 *                                    in this method.
 * @return this
 * @api public
 */
Retext.prototype.use = function (plugin) {
    if (typeof plugin !== 'function') {
        throw new TypeError('Illegal invocation: \'' + plugin +
            '\' is not a valid argument for \'Retext.prototype.use\'');
    }

    var self = this,
        plugins = self.plugins;

    if (plugins.indexOf(plugin) === -1) {
        if (plugin.attach) {
            plugin.attach(self);
        }

        plugins.push(plugin);
    }

    return self;
};

/**
 * `Retext#parse` takes a source to be given (and parsed) by the parser.
 * Then, `parse` iterates over all plugins, and allows them to modify the
 * TextOM tree created by the parser.
 *
 * @param {String?} source - The source to convert.
 * @return {Node} - A RootNode containing the tokenised source.
 * @api public
 */
Retext.prototype.parse = function (source) {
    var self = this,
        rootNode = fromAST(self.TextOM, self.parser.tokenizeRoot(source));

    self.applyPlugins(rootNode);

    return rootNode;
};

/**
 * `Retext#applyPlugins` applies the plugins bound to the retext instance to a
 * given tree.
 *
 * Note that, during the parsing stage, when the `use` plugin is called
 * by a plugin, the nested plugin is immediately called, before continuing
 * on with its parent plugin.
 *
 * @param {Node} tree - The tree to apply plugins to.
 * @api public
 */
Retext.prototype.applyPlugins = function (tree) {
    var self = this,
        plugins = self.plugins.concat(),
        iterator = -1,
        use = self.use;

    self.use = useImmediately(tree, use);

    while (plugins[++iterator]) {
        plugins[iterator](tree, this);
    }

    self.use = use;
};

/**
 * Expose `Retext`. Used to instantiate a new Retext object.
 */
exports = module.exports = Retext;
<|endoftext|>


<commit_before>var test = require('tape'); // require('tap').test; // tape works in browserify, tap works in node 0.10
var shimmedKeys = require('./index.js');
var keys = require('./shim.js');

test('works', function (t) {
	var obj = {
		a: true,
		b: true,
		c: true
	};
	var obj = {
		"str": "boz",
		"obj": {},
		"arr": [],
		"bool": true,
		"num": 42,
		"null": null,
		"undefined": undefined
	};
	var objKeys = ['str', 'obj', 'arr', 'bool', 'num', 'null', 'undefined'];

	t.test('exports a function', function (st) {
		st.plan(1);
		if (Object.keys) {
			st.equal(Object.keys, shimmedKeys, 'Object.keys is supported and exported');
		} else {
			st.equal(keys, shimmedKeys, 'Object.keys is not supported; shim is exported');
		}
	});

	t.test('working with actual shim', function (st) {
		st.plan(1);
		st.notEqual(Object.keys, keys, 'keys shim is not native Object.keys');
	});

	t.test('works with an object literal', function (st) {
		st.plan(2);
		var theKeys = keys(obj);
		st.equal(Array.isArray(theKeys), true, 'returns an array');
		st.deepEqual(theKeys, objKeys, 'Object has expected keys');
	});

	t.test('returns names which are own properties', function (st) {
		keys(obj).forEach(function (name) {
			st.equal(obj.hasOwnProperty(name), true);
		});
		st.end();
	});

	t.test('returns names which are enumerable', function (st) {
		var loopedValues = [];
		for (var k in obj) {
			loopedValues.push(k);
		}
		keys(obj).forEach(function (name) {
			st.notEqual(loopedValues.indexOf(name), -1, name + ' is not enumerable');
		});
		st.end();
	});

	t.test('throws an error for a non-object', function (st) {
		st.plan(1);
		st.throws(function () {
			return keys(42);
		}, new RangeError(), 'throws on a non-object');
	});
	t.end();
});

test('works with an object instance', function (t) {
	var Prototype = function () {};
	Prototype.prototype.foo = true;
	var obj = new Prototype();
	obj.bar = true;
	var theKeys = keys(obj);
	t.equal(Array.isArray(theKeys), true, 'returns an array');
	t.deepEqual(theKeys, ['bar'], 'Instance has expected keys');
	t.end();
});

<commit_msg>Removing an unused object.<commit_after>var test = require('tape'); // require('tap').test; // tape works in browserify, tap works in node 0.10
var shimmedKeys = require('./index.js');
var keys = require('./shim.js');

test('works', function (t) {
	var obj = {
		"str": "boz",
		"obj": {},
		"arr": [],
		"bool": true,
		"num": 42,
		"null": null,
		"undefined": undefined
	};
	var objKeys = ['str', 'obj', 'arr', 'bool', 'num', 'null', 'undefined'];

	t.test('exports a function', function (st) {
		st.plan(1);
		if (Object.keys) {
			st.equal(Object.keys, shimmedKeys, 'Object.keys is supported and exported');
		} else {
			st.equal(keys, shimmedKeys, 'Object.keys is not supported; shim is exported');
		}
	});

	t.test('working with actual shim', function (st) {
		st.plan(1);
		st.notEqual(Object.keys, keys, 'keys shim is not native Object.keys');
	});

	t.test('works with an object literal', function (st) {
		st.plan(2);
		var theKeys = keys(obj);
		st.equal(Array.isArray(theKeys), true, 'returns an array');
		st.deepEqual(theKeys, objKeys, 'Object has expected keys');
	});

	t.test('returns names which are own properties', function (st) {
		keys(obj).forEach(function (name) {
			st.equal(obj.hasOwnProperty(name), true);
		});
		st.end();
	});

	t.test('returns names which are enumerable', function (st) {
		var loopedValues = [];
		for (var k in obj) {
			loopedValues.push(k);
		}
		keys(obj).forEach(function (name) {
			st.notEqual(loopedValues.indexOf(name), -1, name + ' is not enumerable');
		});
		st.end();
	});

	t.test('throws an error for a non-object', function (st) {
		st.plan(1);
		st.throws(function () {
			return keys(42);
		}, new RangeError(), 'throws on a non-object');
	});
	t.end();
});

test('works with an object instance', function (t) {
	var Prototype = function () {};
	Prototype.prototype.foo = true;
	var obj = new Prototype();
	obj.bar = true;
	var theKeys = keys(obj);
	t.equal(Array.isArray(theKeys), true, 'returns an array');
	t.deepEqual(theKeys, ['bar'], 'Instance has expected keys');
	t.end();
});

<|endoftext|>


<commit_before>var marked = require('marked');
var merge = require('util-merge');
var util = require('util');
var path = require('path');
var fs = require('fs');

exports = module.exports = function serveMarkdown(root, options) {
    if (!root) {
        throw new TypeError('root path required')
    }

    options = merge({
        template: path.join(__dirname, 'public', 'template.html'),
        title: function (fileName) {
            return fileName;
        },
        classes: 'sm-content',
        style: path.join(__dirname, 'public', 'screen.css')
    }, options);

    initMarked(options.mdOptions);

    return function (req, res, next) {
        var fp = req.url;
        var ext = path.extname(fp).substr(1);

        fp = path.join(root, fp);
        var isExists = fs.existsSync(fp);
        if (isExists && (ext === 'md' || ext === 'markdown')) {
            var html = marked(fs.readFileSync(fp, 'utf8'));

            var template = options.template;
            if (fs.existsSync(template) && fs.statSync(template).isFile()) {
                template = fs.readFileSync(template, 'utf8');
            }

            var title = options.title;
            if (typeof title === 'function') {
                title = title(path.basename(fp));
            }

            var style = options.style;
            if (fs.existsSync(style) && fs.statSync(style).isFile()) {
                style = fs.readFileSync(style, 'utf8');
            }

            var classes = options.classes;
            if (Array.isArray(classes)) {
                classes = classes.join(' ')
            }

            html = template
                    .replace(/{{title}}/g, title)
                    .replace(/{{style}}/g, style)
                    .replace(/{{classes}}/g, classes)
                    .replace(/{{content}}/g, html);

            res.setHeader('Content-Type', 'text/html; charset=utf-8');
            res.end(html);
        } else {
            next();
        }
    }
};

function initMarked(options) {
    var mdOptions = {
        renderer: new marked.Renderer(),
        gfm: true,
        tables: true,
        breaks: true,
        pedantic: false,
        sanitize: true,
        smartLists: true,
        smartypants: false
    };

    mdOptions = merge(mdOptions, options)
    marked.setOptions(mdOptions);
}
<commit_msg>bugfix: filepath contain decoded chars, space etc. /2014%E5%B9%B45%E6%9C%8815%E6%97%A5/2014-05-15%2012.54.33.jpg<commit_after>var marked = require('marked')
  , merge = require('util-merge')
  , util = require('util')
  , path = require('path')
  , decode = require('urldecode')
  , fs = require('fs');

exports = module.exports = function serveMarkdown(root, options) {
    if (!root) {
        throw new TypeError('root path required')
    }

    options = merge({
        template: path.join(__dirname, 'public', 'template.html'),
        title: function (fileName) {
            return fileName;
        },
        classes: 'sm-content',
        style: path.join(__dirname, 'public', 'screen.css')
    }, options);

    initMarked(options.mdOptions);

    return function (req, res, next) {
        var fp = req.url;
        var ext = path.extname(fp).substr(1);

        fp = path.join(root, fp);
        fp = decode(fp);
        // path contain invalid chars
        if (!~fp) {
            next();
        };

        var isExists = fs.existsSync(fp);
        if (isExists && (ext === 'md' || ext === 'markdown')) {
            var html = marked(fs.readFileSync(fp, 'utf8'));

            var template = options.template;
            if (fs.existsSync(template) && fs.statSync(template).isFile()) {
                template = fs.readFileSync(template, 'utf8');
            }

            var title = options.title;
            if (typeof title === 'function') {
                title = title(path.basename(fp));
            }

            var style = options.style;
            if (fs.existsSync(style) && fs.statSync(style).isFile()) {
                style = fs.readFileSync(style, 'utf8');
            }

            var classes = options.classes;
            if (Array.isArray(classes)) {
                classes = classes.join(' ')
            }

            html = template
                    .replace(/{{title}}/g, title)
                    .replace(/{{style}}/g, style)
                    .replace(/{{classes}}/g, classes)
                    .replace(/{{content}}/g, html);

            res.setHeader('Content-Type', 'text/html; charset=utf-8');
            res.end(html);
        } else {
            next();
        }
    }
};

function initMarked(options) {
    var mdOptions = {
        renderer: new marked.Renderer(),
        gfm: true,
        tables: true,
        breaks: true,
        pedantic: false,
        sanitize: true,
        smartLists: true,
        smartypants: false
    };

    mdOptions = merge(mdOptions, options)
    marked.setOptions(mdOptions);
}
<|endoftext|>


<commit_before>module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    if (req.query.name || (req.body && req.body.name)) {
        res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    }
    else {
        res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    context.done(null, res);
};<commit_msg>fix test<commit_after>module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    if (req.query.name || (req.body && req.body.name)) {
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    context.done();
};<|endoftext|>


<commit_before>var dotest = require ('dotest');
var app = require ('./');

// Setup
// $ NODE_APP_IFACE=eth0 npm test
var vnstat = app ();

dotest.add ('Module', function (test) {
  test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', vnstat)
    .isFunction ('fail', '.getConfig', vnstat && vnstat.getConfig)
    .isFunction ('fail', '.getStats', vnstat && vnstat.getStats)
    .done ();
});

dotest.add ('Method .getConfig', function (test) {
  vnstat.getConfig (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data.DatabaseDir', data && data.DatabaseDir)
      .isNotEmpty ('fail', 'data.Interface', data && data.Interface)
      .done ();
  });
});

dotest.add ('Method .getStats - iface', function (test) {
  vnstat.getStats (process.env.NODE_APP_IFACE || 'eth0', function (err, data) {
    var days = data && data.traffic && data.traffic.days;
    var rx = days && days [0] && days [0] .rx;

    test (err)
      .isObject ('fail', 'data', data)
      .isString ('fail', 'data.id', data && data.id)
      .isObject ('fail', 'data.traffic', data && data.traffic)
      .isArray ('fail', 'data.traffic.days', days)
      .isObject ('fail', 'data.traffic.days[0]', days && days [0])
      .isNumber ('fail', 'data.traffic.days[0].rx', rx)
      .done ();
  });
});

dotest.add ('Method .getStats - all', function (test) {
  vnstat.getStats (function (err, data) {
    test (err)
      .isArray ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Method .getStats - error', function (test) {
  vnstat.getStats ('unreal-iface', function (err) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid interface')
      .done ();
  });
});

// Start the tests
dotest.run ();
<commit_msg>Test: clean up interface setting<commit_after>var dotest = require ('dotest');
var app = require ('./');

// Setup
// $ NODE_APP_IFACE=eth0 npm test
var vnstat = app ();
var iface = process.env.NODE_APP_IFACE || 'eth0';

dotest.add ('Module', function (test) {
  test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', vnstat)
    .isFunction ('fail', '.getConfig', vnstat && vnstat.getConfig)
    .isFunction ('fail', '.getStats', vnstat && vnstat.getStats)
    .done ();
});

dotest.add ('Method .getConfig', function (test) {
  vnstat.getConfig (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data.DatabaseDir', data && data.DatabaseDir)
      .isNotEmpty ('fail', 'data.Interface', data && data.Interface)
      .done ();
  });
});

dotest.add ('Method .getStats - iface', function (test) {
  vnstat.getStats (iface, function (err, data) {
    var days = data && data.traffic && data.traffic.days;
    var rx = days && days [0] && days [0] .rx;

    test (err)
      .isObject ('fail', 'data', data)
      .isString ('fail', 'data.id', data && data.id)
      .isObject ('fail', 'data.traffic', data && data.traffic)
      .isArray ('fail', 'data.traffic.days', days)
      .isObject ('fail', 'data.traffic.days[0]', days && days [0])
      .isNumber ('fail', 'data.traffic.days[0].rx', rx)
      .done ();
  });
});

dotest.add ('Method .getStats - all', function (test) {
  vnstat.getStats (function (err, data) {
    test (err)
      .isArray ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Method .getStats - error', function (test) {
  vnstat.getStats ('unreal-iface', function (err) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid interface')
      .done ();
  });
});

// Start the tests
dotest.run ();
<|endoftext|>


<commit_before>'use strict';
module.exports = function(db) {
  Object.keys(db.sequelize.models)
    .map(m => db.sequelize.model(m))
    .filter(m => m.relocate instanceof Function)
    .map( model => {

      let relocatees = model.relocate();
      let knownRelocatees = Object.keys(relocatees);
      let associates = Object.keys(model.associations);

      associates
        .map(a => model.associations[a])
        .filter(a => a.associationType === 'HasMany')
        .filter(a => knownRelocatees.indexOf(a.as) > -1)
        .map(association => {
          association.source.hook('beforeDestroy', (record, options) => {

            let relocation = {
              value: {},
              where: {},
            };

            relocation.value[association.foreignKey] = relocatees[association.as];
            relocation.where[association.foreignKey] = record.id;

            return association.target.update(relocation.value, {where: relocation.where});

          });
        });
    });
};
<commit_msg>Renamed to sequelize-reassociate<commit_after>'use strict';
module.exports = function(db) {
  Object.keys(db.sequelize.models)
    .map(m => db.sequelize.model(m))
    .filter(m => m.reassociate instanceof Function)
    .map( model => {

      let relocatees = model.reassociate();
      let knownRelocatees = Object.keys(relocatees);
      let associates = Object.keys(model.associations);

      associates
        .map(a => model.associations[a])
        .filter(a => a.associationType === 'HasMany')
        .filter(a => knownRelocatees.indexOf(a.as) > -1)
        .map(association => {
          association.source.hook('beforeDestroy', (record, options) => {

            let relocation = {
              value: {},
              where: {},
            };

            relocation.value[association.foreignKey] = relocatees[association.as];
            relocation.where[association.foreignKey] = record.id;

            return association.target.update(relocation.value, {where: relocation.where});

          });
        });
    });
};
<|endoftext|>


<commit_before><commit_msg>refactored test<commit_after>var count = require('./')
var test = require('tape')
var polygon = require('turf-polygon')
var point = require('turf-point')
var featurecollection =  require('turf-featurecollection')

test('count', function(t){
  var poly1 = polygon([[[0,0],[10,0],[10,10], [0,10]]])
  var poly2 = polygon([[[10,0],[20,10],[20,20], [20,0]]])
  var polyFC = featurecollection([poly1, poly2])
  var pt1 = point(5,5, {population: 200})
  var pt2 = point(1,3, {population: 600})
  var pt3 = point(14,2, {population: 100})
  var pt4 = point(13,1, {population: 200})
  var pt5 = point(19,7, {population: 300})
  var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5])

  var counted = count(polyFC, ptFC, 'pt_count')

  t.equal(counted.features[0].geometry.type, 'Polygon')
  t.equal(counted.features[0].properties.pt_count, 2)
  t.equal(counted.features[1].properties.pt_count, 3)

  t.end()
})<|endoftext|>


<commit_before>// Main process
'use strict';
const path = require('path');
const app = require('app');
const ipcMain = require('electron').ipcMain;
const BrowserWindow = require('browser-window');

app.on('ready', () => {
	const win = new BrowserWindow({
		webPreferences: {
			// Load `electron-notification-shim` in rendering view.
			preload: path.join(__dirname, 'browser.js')
		}
	});

	// Listen for notification events.
	ipcMain.on('notification-shim', (e, msg) => {
		console.log(`Title: ${msg.title}, Content: ${msg.options.content}`);
	});

	// Just to test. Don't do this at home, kids. :)
	win.loadURL(`https://google.com`);
	win.webContents.on('did-finish-load', () => {
		win.webContents.executeJavaScript('new Notification("Hello!", {content: "Notification world!"})');
	});
});
<commit_msg>Use body property of Notification<commit_after>// Main process
'use strict';
const path = require('path');
const app = require('app');
const ipcMain = require('electron').ipcMain;
const BrowserWindow = require('browser-window');

app.on('ready', () => {
	const win = new BrowserWindow({
		webPreferences: {
			// Load `electron-notification-shim` in rendering view.
			preload: path.join(__dirname, 'browser.js')
		}
	});

	// Listen for notification events.
	ipcMain.on('notification-shim', (e, msg) => {
		console.log(`Title: ${msg.title}, Body: ${msg.options.body}`);
	});

	// Just to test. Don't do this at home, kids. :)
	win.loadURL(`https://google.com`);
	win.webContents.on('did-finish-load', () => {
		win.webContents.executeJavaScript('new Notification("Hello!", {body: "Notification world!"})');
	});
});
<|endoftext|>


<commit_before>/*
  node index.js --user=GIT_USER_NAME --output=OUTPUT_FILE
*/

const spawn = require('child_process').spawn;
const fs = require('fs');

function rightPad(str, len, ch) {
  const padlen = len - str.length;
  return (padlen <= 0) ? str : str + (ch || ' ').repeat(padlen);
}

function logger(title, content) {
  console.log(` - ${rightPad(title, 6)}: ${content}`);
}

function makeMarkdown(dataArr, outputPath) {
  let str = '';
  dataArr.forEach((item) => {
    str = str + `# ${item.date}\n\n${item.value.join('\n').replace(/^/mg, ' - ')}\n\n`;
  });
  if (outputPath) {
    fs.writeFileSync(outputPath, str);
  } else {
    console.log('\n\n', str);
  }
}

function processData(raw) {
  const resArr = [];
  let currentArr;
  let currentDate = '';
  const lines = raw.split('\n');
  logger('Git Done', `${lines.length} Commits Found\n`)
  lines.forEach((item) => {
    item = item.replace(/^"/, '').replace(/"$/, '');
    const vs = item.split('$@$');
    if (vs.length !== 3) {
      return;
    }
    if ((/^merge.*branch.*into/i).test(vs[2])) {
      logger('Skip', `${vs[2].slice(0,55)}`);
      return;
    }
    vs[2] = vs[2].replace(/；|;/g, '\n');
    if (vs[0] == currentDate) {
      currentArr.push(vs[2]);
    } else {
      if (currentArr && currentArr.length > 0) {
        resArr.push({
          date: currentDate,
          value: currentArr
        });
      }
      currentDate = vs[0];
      currentArr = [];
      currentArr.push(vs[2]);
    }
  });
  if (currentArr && currentArr.length > 0) {
    resArr.push({
      date: currentDate,
      value: currentArr
    });
  }
  return resArr;
}

(function() {
  const params = {
    user: 'WangLei',
    output: false
  };
  process.argv.splice(2).forEach((arg) => {
    argPair = arg.split('=');
    if (argPair.length !== 2) {
      return;
    }
    const pName = argPair[0].replace(/^--/, '');
    if (pName && typeof params[pName] !== 'undefined') {
      params[pName] = argPair[1];
    }
  });
  logger('User', `${params.user}`);
  params.output && logger('Output', `${params.output}`);
  let rawData = '';
  let shell = spawn('git', ['log', '--pretty=format:"%ad$@$%an$@$%s"', '--author=' + params.user, '--since=4.weeks', '--reverse', '--date=short']);
  shell.stdout.on('data', function(data) {
    rawData = rawData + data;
  });
  shell.on('error', function() {
    logger('Error', 'Something is wrong. Is Git installed ?');
  });
  shell.on('exit', function(code, signal) {
    setTimeout(function() {
      makeMarkdown(processData(rawData), params.output);
      if (params.output) {
        logger('Done', `See ${params.output}`);
      }
      process.exit()
    }, 2000);
  });

})();
<commit_msg>bugfix<commit_after>/*
  node index.js --user=GIT_USER_NAME --output=OUTPUT_FILE
*/

const spawn = require('child_process').spawn;
const fs = require('fs');

function rightPad(str, len, ch) {
  const padlen = len - str.length;
  return (padlen <= 0) ? str : str + (ch || ' ').repeat(padlen);
}

function logger(title, content) {
  console.log(` - ${rightPad(title, 6)}: ${content}`);
}

function makeMarkdown(dataArr, outputPath) {
  let str = '';
  dataArr.forEach((item) => {
    str = str + `# ${item.date}\n\n${item.value.join('\n').replace(/^(\s)*/mg, ' - ')}\n\n`;
  });
  if (outputPath) {
    fs.writeFileSync(outputPath, str);
  } else {
    console.log('\n\n', str);
  }
}

function processData(raw) {
  const resArr = [];
  let currentArr;
  let currentDate = '';
  const lines = raw.split('\n');
  logger('Git Done', `${lines.length} Commits Found\n`)
  lines.forEach((item) => {
    item = item.replace(/^"|"$/g, '');
    const vs = item.split('$@$');
    if (vs.length !== 3) {
      return;
    }
    if ((/^merge.*branch.*into/i).test(vs[2])) {
      logger('Skip', `${vs[2].slice(0,55)}`);
      return;
    }
    vs[2] = vs[2].replace(/(；|;)/g, '\n').replace(/^(\s)*|(\s)*$/g, '');
    if (vs[0] == currentDate) {
      currentArr.push(vs[2]);
    } else {
      if (currentArr && currentArr.length > 0) {
        resArr.push({
          date: currentDate,
          value: currentArr
        });
      }
      currentDate = vs[0];
      currentArr = [];
      currentArr.push(vs[2]);
    }
  });
  if (currentArr && currentArr.length > 0) {
    resArr.push({
      date: currentDate,
      value: currentArr
    });
  }
  return resArr;
}

(function() {
  const params = {
    user: 'WangLei',
    output: false
  };
  process.argv.splice(2).forEach((arg) => {
    argPair = arg.split('=');
    if (argPair.length !== 2) {
      return;
    }
    const pName = argPair[0].replace(/^--/, '');
    if (pName && typeof params[pName] !== 'undefined') {
      params[pName] = argPair[1];
    }
  });
  logger('User', `${params.user}`);
  params.output && logger('Output', `${params.output}`);
  let rawData = '';
  let shell = spawn('git', ['log', '--pretty=format:"%ad$@$%an$@$%s"', '--author=' + params.user, '--since=4.weeks', '--reverse', '--date=short']);
  shell.stdout.on('data', function(data) {
    rawData = rawData + data;
  });
  shell.on('error', function() {
    logger('Error', 'Something is wrong. Is Git installed ?');
  });
  shell.on('exit', function(code, signal) {
    setTimeout(function() {
      makeMarkdown(processData(rawData), params.output);
      if (params.output) {
        logger('Done', `See ${params.output}`);
      }
      process.exit()
    }, 2000);
  });

})();
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-3 11:21:46<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


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

var mapnik = require('mapnik');
var assert = require('assert');
var path = require('path');
var fs = require('fs');

/* MAP */

// Test mapnik.Map object creation
var Map = mapnik.Map;

var map1 = new Map(256, 256);

assert.ok(map1 instanceof Map);

var map = new mapnik.Map(600, 400);

assert.ok(map instanceof mapnik.Map);
assert.throws(function() {new mapnik.Map('foo')});

// test initial values
assert.notStrictEqual(map.extent(), [-1.0, -1.0, 0.0, 0.0]);

// Test rendering a blank image
map.render_to_file('/tmp/nodemap.png');
assert.ok(path.existsSync('/tmp/nodemap.png'));

// Test loading a sample world map
map.load('./examples/stylesheet.xml');

// Test loading a map from a string
var style_string = fs.readFileSync('./examples/stylesheet.xml').toLocaleString();
var base_url = './examples/'; // must end with trailing slash
map.from_string(style_string,base_url);

// test new extent based on active layers
map.zoom_all();
var expected = [-20037508.3428, -14996604.5082, 20037508.3428, 25078412.1774];
assert.notStrictEqual(map.extent(), expected);

// Test rendering with actual data
map.render_to_file('/tmp/world.png');
assert.ok(path.existsSync('/tmp/world.png'));

assert.equal(map.width(), 600);
assert.equal(map.height(), 400);
map.resize(256, 256);
assert.equal(map.width(), 256);
assert.equal(map.height(), 256);

/* PROJECTION */

// Test mapnik.Projection object creation

assert.throws(function() {new mapnik.Projection('+init=epsg:foo')});
assert.throws(function() {new mapnik.Projection('+proj +foo')});

try {
    var proj = new mapnik.Projection('+init=epsg:foo');
}
catch (err)
{
    assert.equal(err.message, 'failed to initialize projection with:+init=epsg:foo');
}

var wgs84 = new mapnik.Projection('+init=epsg:4326');

assert.ok(wgs84 instanceof mapnik.Projection);

var merc = null;

try {
    // perhaps we've got a savvy user?
    merc = new mapnik.Projection('+init=epsg:900913');
}
catch (err) {
    // newer versions of proj4 have this code which is == 900913
    merc = new mapnik.Projection('+init=epsg:3857');
}

if (!merc) {
    /* be friendly if this test fails */
    var msg = 'warning, could not create a spherical mercator projection';
    msg += '\nwith either epsg:900913 or epsg:3857, so they must be missing';
    msg += '\nfrom your proj4 epsg table (/usr/local/share/proj/epsg)';
    console.log(msg);
}
else
{
    assert.ok(merc instanceof mapnik.Projection);
    long_lat_coords = [-122.33517, 47.63752];
    merc_coords = merc.forward(long_lat_coords);

    assert.equal(merc_coords.length, 2);
    assert.notStrictEqual(merc_coords, [-13618288.8305, 6046761.54747]);
    assert.notStrictEqual(long_lat_coords, merc.inverse(merc.forward(long_lat_coords)));

    long_lat_bounds = [-122.420654, 47.605006, -122.2435, 47.67764];
    merc_bounds = merc.forward(long_lat_bounds);

    assert.equal(merc_bounds.length, 4);
    var expected = [-13627804.8659, 6041391.68077, -13608084.1728, 6053392.19471];
    assert.notStrictEqual(merc_bounds, expected);
    assert.notStrictEqual(long_lat_bounds, merc.inverse(merc.forward(long_lat_bounds)));
}

console.log('All tests pass...');
<commit_msg>test version's match for the node process and the node version node-mapnik was compiled against<commit_after>#!/usr/bin/env node

var mapnik = require('mapnik');
var assert = require('assert');
var path = require('path');
var fs = require('fs');

/* settings */

assert.ok(mapnik.settings)
assert.ok(mapnik.settings.paths)
assert.ok(mapnik.settings.paths.fonts.length)
assert.ok(mapnik.settings.paths.input_plugins.length)

/* ABI compatibility */

// be strict/exact
assert.ok(mapnik.node_version === process.version,'The node version "' + process.version + '" does not match the node version that node-mapnik was compiled against: "' + mapnik.node_version + '"');

/* MAP */

// Test mapnik.Map object creation
var Map = mapnik.Map;

var map1 = new Map(256, 256);

assert.ok(map1 instanceof Map);

var map = new mapnik.Map(600, 400);

assert.ok(map instanceof mapnik.Map);
assert.throws(function() {new mapnik.Map('foo')});

// test initial values
assert.notStrictEqual(map.extent(), [-1.0, -1.0, 0.0, 0.0]);

// Test rendering a blank image
map.render_to_file('/tmp/nodemap.png');
assert.ok(path.existsSync('/tmp/nodemap.png'));

// Test loading a sample world map
map.load('./examples/stylesheet.xml');

// Test loading a map from a string
var style_string = fs.readFileSync('./examples/stylesheet.xml').toLocaleString();
var base_url = './examples/'; // must end with trailing slash
map.from_string(style_string,base_url);

// test new extent based on active layers
map.zoom_all();
var expected = [-20037508.3428, -14996604.5082, 20037508.3428, 25078412.1774];
assert.notStrictEqual(map.extent(), expected);

// Test rendering with actual data
map.render_to_file('/tmp/world.png');
assert.ok(path.existsSync('/tmp/world.png'));

assert.equal(map.width(), 600);
assert.equal(map.height(), 400);
map.resize(256, 256);
assert.equal(map.width(), 256);
assert.equal(map.height(), 256);

/* PROJECTION */

// Test mapnik.Projection object creation

assert.throws(function() {new mapnik.Projection('+init=epsg:foo')});
assert.throws(function() {new mapnik.Projection('+proj +foo')});

try {
    var proj = new mapnik.Projection('+init=epsg:foo');
}
catch (err)
{
    assert.equal(err.message, 'failed to initialize projection with:+init=epsg:foo');
}

var wgs84 = new mapnik.Projection('+init=epsg:4326');

assert.ok(wgs84 instanceof mapnik.Projection);

var merc = null;

try {
    // perhaps we've got a savvy user?
    merc = new mapnik.Projection('+init=epsg:900913');
}
catch (err) {
    // newer versions of proj4 have this code which is == 900913
    merc = new mapnik.Projection('+init=epsg:3857');
}

if (!merc) {
    /* be friendly if this test fails */
    var msg = 'warning, could not create a spherical mercator projection';
    msg += '\nwith either epsg:900913 or epsg:3857, so they must be missing';
    msg += '\nfrom your proj4 epsg table (/usr/local/share/proj/epsg)';
    console.log(msg);
}
else
{
    assert.ok(merc instanceof mapnik.Projection);
    long_lat_coords = [-122.33517, 47.63752];
    merc_coords = merc.forward(long_lat_coords);

    assert.equal(merc_coords.length, 2);
    assert.notStrictEqual(merc_coords, [-13618288.8305, 6046761.54747]);
    assert.notStrictEqual(long_lat_coords, merc.inverse(merc.forward(long_lat_coords)));

    long_lat_bounds = [-122.420654, 47.605006, -122.2435, 47.67764];
    merc_bounds = merc.forward(long_lat_bounds);

    assert.equal(merc_bounds.length, 4);
    var expected = [-13627804.8659, 6041391.68077, -13608084.1728, 6053392.19471];
    assert.notStrictEqual(merc_bounds, expected);
    assert.notStrictEqual(long_lat_bounds, merc.inverse(merc.forward(long_lat_bounds)));
}

console.log('All tests pass...');
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var url = require('url')
  , qs = require('querystring')

/**
 * Helpers method
 *
 * @param {String} name
 * @return {Function}
 * @api public
 */

function helpers (name) {
  return function (req, res, next) {
    res.locals.appName = name || 'App'
    res.locals.title = name || 'App'
    res.locals.req = req
    res.locals.isActive = function (link) {
      return req.url.indexOf(link) !== -1 ? 'active' : ''
    }
    res.locals.formatDate = formatDate
    res.locals.stripScript = stripScript
    res.locals.createPagination = createPagination(req)

    if (typeof req.flash !== 'undefined') {
      res.locals.info = req.flash('info')
      res.locals.errors = req.flash('errors')
      res.locals.success = req.flash('success')
      res.locals.warning = req.flash('warning')
    }

    next()
  }
}

module.exports = helpers

/**
 * Pagination helper
 *
 * @param {Number} pages
 * @param {Number} page
 * @return {String}
 * @api private
 */

function createPagination (req) {
  return function createPagination (pages, page) {
    var params = qs.parse(url.parse(req.url).query)
    var str = ''

    params.page = 0
    var clas = page == 0 ? "active" : "no"
    str += '
First
'
    for (var p = 1; p < pages; p++) {
      params.page = p
      clas = page == p ? "active" : "no"
      str += '
'+ p +'
'
    }
    params.page = --p
    clas = page == params.page ? "active" : "no"
    str += '
Last
'

    return str
  }
}

/**
 * Format date helper
 *
 * @param {Date} date
 * @return {String}
 * @api private
 */

function formatDate (date) {
  var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
  return monthNames[date.getMonth()]+' '+date.getDate()+', '+date.getFullYear()
}

/**
 * Format date time helper
 *
 * @param {Date} date
 * @return {String}
 * @api private
 */

function formatDatetime (date) {
  var hour = date.getHours();
  var minutes = date.getMinutes() < 10
    ? '0' + date.getMinutes().toString()
    : date.getMinutes();

  return formatDate(date) + ' ' + hour + ':' + minutes;
}

/**
 * Strip script tags
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

function stripScript (str) {
  return str.replace(/


<commit_before>/*
 * Copyright (c) 2015 Internet of Protocols Alliance (IOPA)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// DEPENDENCIES
const net = require('net'),
  util = require('util'),
  events = require('events'),

  iopaStream = require('iopa-common-stream'),
  iopa = require('iopa'),
  IOPA = iopa.constants.IOPA,
  SERVER = iopa.constants.SERVER

/* *********************************************************
 * IOPA TCP CLIENT (GENERIC)
 * ********************************************************* */
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
* Creates a new IOPA Request using a Tcp Url including host and port name
*
* @method TcpClient

* @parm {object} options not used
* @parm {string} urlStr url representation of ://127.0.0.1:8200
* @public
* @constructor
*/
function TcpClient(options, appFuncConnect, appFuncDispatch) {

  _classCallCheck(this, TcpClient);

  if (typeof options === 'function') {
    appFuncDispatch = appFuncConnect;
    appFuncConnect = options;
    options = {};
  }

  events.EventEmitter.call(this);

  this._connect = appFuncConnect || function(context){return Promise.resolve(context)};
  this._dispatch = appFuncDispatch || function(context){return Promise.resolve(context)};

  this._options = options;
  this._factory = new iopa.Factory(options);
  this._connections = {};
}

util.inherits(TcpClient, events.EventEmitter);

/**
* Creates a new IOPA Request using a Tcp Url including host and port name
*
* @method connect

* @parm {object} options not used
* @parm {string} urlStr url representation of ://127.0.0.1:8200
* @public
* @constructor
*/
TcpClient.prototype.connect = function TcpClient_connect(urlStr, defaults) {
 defaults = defaults || {};
 defaults[IOPA.Method] = defaults[IOPA.Method] || IOPA.METHODS.connect;
  var channelContext = this._factory.createRequestResponse(urlStr, defaults);
  var channelResponse = channelContext.response;

  channelContext[SERVER.Fetch] = TcpClient_Fetch.bind(this, channelContext);
  channelContext[SERVER.Dispatch] = this._dispatch;
  channelContext[SERVER.Disconnect] = this._disconnect.bind(this, channelContext);

  var that = this;
  return new Promise(function (resolve, reject) {
    var socket = net.createConnection(
      channelContext[SERVER.RemotePort],
      channelContext[SERVER.RemoteAddress],
      function () {
        channelContext[SERVER.RawStream] = socket;
        channelContext[SERVER.RawTransport] = socket;
        channelContext[SERVER.LocalAddress] = socket.localAddress;
        channelContext[SERVER.LocalPort] = socket.localPort;

        channelResponse[SERVER.RawStream] = socket;
        channelResponse[SERVER.RawTransport] = socket;
        channelResponse[SERVER.LocalAddress] = channelContext[SERVER.LocalAddress];
        channelResponse[SERVER.LocalPort] = channelContext[SERVER.LocalPort];

        socket.once('finish', that._disconnect.bind(that, channelContext, null));
        socket.once('error', that._disconnect.bind(that, channelContext));
        channelContext[SERVER.SessionId] = channelContext[SERVER.LocalAddress] + ":" + channelContext[SERVER.LocalPort] + "-" + channelContext[SERVER.RemoteAddress] + ":" + channelContext[SERVER.RemotePort];
        that._connections[channelContext[SERVER.SessionId]] = channelContext;
        resolve(that._connect(channelContext));
      });
  });
};

/**
 * Fetches a new IOPA Request using a Tcp Url including host and port name
 *
 * @method fetch

 * @param path string representation of ://127.0.0.1/hello
 * @param options object dictionary to override defaults
 * @param pipeline function(context):Promise  to call with context record
 * @returns Promise<null>
 * @public
 */
function TcpClient_Fetch(channelContext, path, options, prePipeline, postPipeline) {
  if (typeof options === 'function') {
    postPipeline = prePipeline;
    prePipeline = options;
    options = {};
  }

  var channelResponse = channelContext.response;

  var urlStr = channelContext[SERVER.OriginalUrl] + path;
  var context = channelContext[SERVER.Factory].createRequestResponse(urlStr, options);
  channelContext[SERVER.Factory].mergeCapabilities(context, channelContext);

  context[SERVER.LocalAddress] = channelContext[SERVER.LocalAddress];
  context[SERVER.LocalPort] = channelContext[SERVER.LocalPort];
  context[SERVER.RawStream] = channelContext[SERVER.RawStream];
  context[SERVER.SessionId] = channelContext[SERVER.SessionId];

  var response = context.response;
  response[SERVER.LocalAddress] = channelResponse[SERVER.LocalAddress];
  response[SERVER.LocalPort] = channelResponse[SERVER.LocalPort];
  response[SERVER.RawStream] = channelResponse[SERVER.RawStream];

   return context.using(function () {
    if (prePipeline)
       prePipeline(context);

    var value = channelContext[SERVER.Dispatch](context);

    if (postPipeline)
       postPipeline(context);

    return value;
  });
};

/**
 * @method close
 * Close the  channel context
 *
 * @public
 */
TcpClient.prototype._disconnect = function TcpClient_disconnect(channelContext, err) {
  if (channelContext[IOPA.CancelToken].isCancelled)
     return;

  channelContext[IOPA.Events] = null;
  channelContext[SERVER.CancelTokenSource].cancel(IOPA.EVENTS.Disconnect);
  delete this._connections[channelContext[SERVER.SessionId]];
  setTimeout(function(){
      channelContext[SERVER.RawTransport].destroy();
       channelContext.dispose();
  }, 100);
}

/**
 * @method close
 * Close all the underlying sockets
 *
 * @returns {Promise()}
 * @public
 */
TcpClient.prototype.close = function TcpClient_close() {
  for (var key in this._connections)
    this._disconnect(this._connections[key], null);

  this._connections = {};

  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(null);
    }, 200);
  });

};

module.exports = TcpClient;<commit_msg>dev test<commit_after>/*
 * Copyright (c) 2015 Internet of Protocols Alliance (IOPA)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// DEPENDENCIES
const net = require('net'),
  util = require('util'),
  events = require('events'),

  iopaStream = require('iopa-common-stream'),
  iopa = require('iopa'),
  IOPA = iopa.constants.IOPA,
  SERVER = iopa.constants.SERVER

/* *********************************************************
 * IOPA TCP CLIENT (GENERIC)
 * ********************************************************* */
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
* Creates a new IOPA Request using a Tcp Url including host and port name
*
* @method TcpClient

* @parm {object} options not used
* @parm {string} urlStr url representation of ://127.0.0.1:8200
* @public
* @constructor
*/
function TcpClient(options, appFuncConnect, appFuncDispatch) {

  _classCallCheck(this, TcpClient);

  if (typeof options === 'function') {
    appFuncDispatch = appFuncConnect;
    appFuncConnect = options;
    options = {};
  }

  events.EventEmitter.call(this);

  this._connect = appFuncConnect || function(context){return Promise.resolve(context)};
  this._dispatch = appFuncDispatch || function(context){return Promise.resolve(context)};

  this._options = options;
  this._factory = new iopa.Factory(options);
  this._connections = {};
}

util.inherits(TcpClient, events.EventEmitter);

/**
* Creates a new IOPA Request using a Tcp Url including host and port name
*
* @method connect

* @parm {object} options not used
* @parm {string} urlStr url representation of ://127.0.0.1:8200
* @public
* @constructor
*/
TcpClient.prototype.connect = function TcpClient_connect(urlStr, defaults) {
 defaults = defaults || {};
 defaults[IOPA.Method] = defaults[IOPA.Method] || IOPA.METHODS.connect;
  var channelContext = this._factory.createRequestResponse(urlStr, defaults);
  var channelResponse = channelContext.response;

  channelContext[SERVER.Fetch] = TcpClient_Fetch.bind(this, channelContext);
  channelContext[SERVER.Dispatch] = this._dispatch;
  channelContext[SERVER.Disconnect] = this._disconnect.bind(this, channelContext);

  var that = this;
  return new Promise(function (resolve, reject) {
    var socket = net.createConnection(
      channelContext[SERVER.RemotePort],
      channelContext[SERVER.RemoteAddress],
      function () {
        channelContext[SERVER.RawStream] = socket;
        channelContext[SERVER.RawTransport] = socket;
        channelContext[SERVER.LocalAddress] = socket.localAddress;
        channelContext[SERVER.LocalPort] = socket.localPort;

        channelResponse[SERVER.RawStream] = socket;
        channelResponse[SERVER.RawTransport] = socket;
        channelResponse[SERVER.LocalAddress] = channelContext[SERVER.LocalAddress];
        channelResponse[SERVER.LocalPort] = channelContext[SERVER.LocalPort];

        socket.once('finish', that._disconnect.bind(that, channelContext, null));
        socket.once('error', that._disconnect.bind(that, channelContext));
        channelContext[SERVER.SessionId] = channelContext[SERVER.LocalAddress] + ":" + channelContext[SERVER.LocalPort] + "-" + channelContext[SERVER.RemoteAddress] + ":" + channelContext[SERVER.RemotePort];
        that._connections[channelContext[SERVER.SessionId]] = channelContext;
        resolve(that._connect(channelContext));
      });
  });
};

/**
 * Fetches a new IOPA Request using a Tcp Url including host and port name
 *
 * @method fetch

 * @param path string representation of ://127.0.0.1/hello
 * @param options object dictionary to override defaults
 * @param pipeline function(context):Promise  to call with context record
 * @returns Promise<null>
 * @public
 */
function TcpClient_Fetch(channelContext, path, options, prePipeline, postPipeline) {
  if (typeof options === 'function') {
    postPipeline = prePipeline;
    prePipeline = options;
    options = {};
  }

  var channelResponse = channelContext.response;

  var urlStr = channelContext[SERVER.OriginalUrl] + path;
  var context = channelContext[SERVER.Factory].createRequestResponse(urlStr, options);
  channelContext[SERVER.Factory].mergeCapabilities(context, channelContext);

  context[SERVER.LocalAddress] = channelContext[SERVER.LocalAddress];
  context[SERVER.LocalPort] = channelContext[SERVER.LocalPort];
  context[SERVER.RawStream] = channelContext[SERVER.RawStream];
  context[SERVER.SessionId] = channelContext[SERVER.SessionId];

  var response = context.response;
  response[SERVER.LocalAddress] = channelResponse[SERVER.LocalAddress];
  response[SERVER.LocalPort] = channelResponse[SERVER.LocalPort];
  response[SERVER.RawStream] = channelResponse[SERVER.RawStream];

   return context.using(function () {
    if (prePipeline)
       prePipeline(context);

    var value = channelContext[SERVER.Dispatch](context);

    if (postPipeline)
     return  value.then
     (function(){
        return postPipeline(context);
     })

    else return value;
  });
};

/**
 * @method close
 * Close the  channel context
 *
 * @public
 */
TcpClient.prototype._disconnect = function TcpClient_disconnect(channelContext, err) {
  if (channelContext[IOPA.CancelToken].isCancelled)
     return;

  channelContext[IOPA.Events] = null;
  channelContext[SERVER.CancelTokenSource].cancel(IOPA.EVENTS.Disconnect);
  delete this._connections[channelContext[SERVER.SessionId]];
  setTimeout(function(){
      channelContext[SERVER.RawTransport].destroy();
       channelContext.dispose();
  }, 100);
}

/**
 * @method close
 * Close all the underlying sockets
 *
 * @returns {Promise()}
 * @public
 */
TcpClient.prototype.close = function TcpClient_close() {
  for (var key in this._connections)
    this._disconnect(this._connections[key], null);

  this._connections = {};

  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(null);
    }, 200);
  });

};

module.exports = TcpClient;<|endoftext|>


<commit_before>var startTime = Date.now()

require('debug/browser')

var debug = require('debug')('index')
var electron = require('electron')
var path = require('path')

var app = electron.app

app.on('open-file', onOpen)
app.on('open-url', onOpen)

function onOpen (e, torrentId) {
  e.preventDefault()
  mainWindow.send('action', 'addTorrent', torrentId)
}

// report crashes
// require('crash-reporter').start({
//   productName: 'WebTorrent',
//   companyName: 'WebTorrent',
//   submitURL: 'https://webtorrent.io/crash-report',
//   autoSubmit: true
// })

// prevent windows from being garbage collected
var mainWindow // eslint-disable-line no-unused-vars

app.on('ready', function () {
  mainWindow = createMainWindow()

  var menu = electron.Menu.buildFromTemplate(template)
  electron.Menu.setApplicationMenu(menu)
})

app.on('activate', function () {
  if (mainWindow) {
    mainWindow.show()
  } else {
    mainWindow = createMainWindow()
  }
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

var isQuitting = false
app.on('before-quit', function () {
  isQuitting = true
})

function createMainWindow () {
  var win = new electron.BrowserWindow({
    backgroundColor: '#282828',
    darkTheme: true,
    minWidth: 360,
    show: false,
    title: 'WebTorrent',
    titleBarStyle: 'hidden-inset',
    width: 500,
    height: 300
  })
  win.loadURL('file://' + path.join(__dirname, 'main', 'index.html'))
  win.webContents.on('did-finish-load', function () {
    setTimeout(function () {
      debug('startup time: %sms', Date.now() - startTime)
      win.show()
    }, 50)
  })
  win.on('close', function (e) {
    if (process.platform === 'darwin' && !isQuitting) {
      e.preventDefault()
      win.hide()
    }
  })
  win.once('closed', function () {
    mainWindow = null
  })
  return win
}

function addTorrentFromPaste () {
  var torrentIds = electron.clipboard.readText().split('\n')
  console.log(torrentIds)
  torrentIds.forEach(function (torrentId) {
    torrentId = torrentId.trim()
    if (torrentId.length === 0) return
    mainWindow.send('action', 'addTorrent', torrentId)
  })
}

function toggleDevTools (win) {
  win = win || electron.BrowserWindow.getFocusedWindow()

  if (win) {
    win.toggleDevTools()
  }
}

function reloadWindow (win) {
  win = win || electron.BrowserWindow.getFocusedWindow()

  if (win) {
    startTime = Date.now()
    win.webContents.reloadIgnoringCache()
  }
}

electron.ipcMain.on('action', function (event, action, ...args) {
  debug('action %s', action)
  if (action === 'addTorrentFromPaste') {
    addTorrentFromPaste()
  }
})

var template = [
  {
    label: 'File',
    submenu: [
      {
        label: 'Create New Torrent...',
        accelerator: 'CmdOrCtrl+N',
        click: function () {
          electron.dialog.showOpenDialog({
            title: 'Select a file or folder for the torrent file.',
            properties: [ 'openFile', 'openDirectory', 'multiSelections' ]
          }, function (filenames) {
            if (!Array.isArray(filenames)) return
            mainWindow.send('action', 'seed', filenames)
          })
        }
      },
      {
        label: 'Open Torrent File...',
        accelerator: 'CmdOrCtrl+O',
        click: function () {
          electron.dialog.showOpenDialog(mainWindow, {
            title: 'Select a .torrent file to open.',
            properties: [ 'openFile', 'multiSelections' ]
          }, function (filenames) {
            if (!Array.isArray(filenames)) return
            filenames.forEach(function (filename) {
              mainWindow.send('action', 'addTorrent', filename)
            })
          })
        }
      },
      {
        label: 'Open Torrent Address...',
        accelerator: 'CmdOrCtrl+U',
        click: function () { electron.dialog.showMessageBox({ message: 'TODO', buttons: ['OK'] }) }
      },
      {
        type: 'separator'
      },
      {
        label: 'Close Window',
        accelerator: 'CmdOrCtrl+W',
        role: 'close'
      }
    ]
  },
  {
    label: 'Edit',
    submenu: [
      {
        label: 'Cut',
        accelerator: 'CmdOrCtrl+X',
        role: 'cut'
      },
      {
        label: 'Copy',
        accelerator: 'CmdOrCtrl+C',
        role: 'copy'
      },
      {
        label: 'Paste Torrent Address',
        accelerator: 'CmdOrCtrl+V',
        role: 'paste'
      },
      {
        label: 'Select All',
        accelerator: 'CmdOrCtrl+A',
        role: 'selectall'
      }
    ]
  },
  {
    label: 'View',
    submenu: [
      {
        label: 'Toggle Full Screen',
        accelerator: (function () {
          if (process.platform === 'darwin') return 'Ctrl+Command+F'
          else return 'F11'
        })(),
        click: function (item, focusedWindow) {
          if (focusedWindow) focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
        }
      },
      {
        type: 'separator'
      },
      {
        label: 'Reload',
        accelerator: 'CmdOrCtrl+R',
        click: function (item, focusedWindow) {
          reloadWindow(focusedWindow)
        }
      },
      {
        label: 'Toggle Developer Tools',
        accelerator: (function () {
          if (process.platform === 'darwin') return 'Alt+Command+I'
          else return 'Ctrl+Shift+I'
        })(),
        click: function (item, focusedWindow) {
          toggleDevTools(focusedWindow)
        }
      }
    ]
  },
  {
    label: 'Window',
    role: 'window',
    submenu: [
      {
        label: 'Minimize',
        accelerator: 'CmdOrCtrl+M',
        role: 'minimize'
      }
    ]
  },
  {
    label: 'Help',
    role: 'help',
    submenu: [
      {
        label: 'Learn more about WebTorrent',
        click: function () { electron.shell.openExternal('https://webtorrent.io') }
      },
      {
        label: 'Contribute on GitHub',
        click: function () { electron.shell.openExternal('https://github.com/feross/webtorrent-app') }
      },
      {
        type: 'separator'
      },
      {
        label: 'Report an Issue...',
        click: function () { electron.shell.openExternal('https://github.com/feross/webtorrent-app/issues') }
      }
    ]
  }
]

if (process.platform === 'darwin') {
  var name = app.getName()
  template.unshift({
    label: name,
    submenu: [
      {
        label: 'About ' + name,
        role: 'about'
      },
      {
        type: 'separator'
      },
      {
        label: 'Services',
        role: 'services',
        submenu: []
      },
      {
        type: 'separator'
      },
      {
        label: 'Hide ' + name,
        accelerator: 'Command+H',
        role: 'hide'
      },
      {
        label: 'Hide Others',
        accelerator: 'Command+Alt+H',
        role: 'hideothers'
      },
      {
        label: 'Show All',
        role: 'unhide'
      },
      {
        type: 'separator'
      },
      {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: function () { app.quit() }
      }
    ]
  })

  // Window menu
  template[4].submenu.push(
    {
      type: 'separator'
    },
    {
      label: 'Bring All to Front',
      role: 'front'
    }
  )
}

// var progress = 0
// setInterval(function () {
//   progress += 0.1
//   mainWindow.setProgressBar(progress)
// }, 1000)
<commit_msg>window: set min height of one row visible<commit_after>var startTime = Date.now()

require('debug/browser')

var debug = require('debug')('index')
var electron = require('electron')
var path = require('path')

var app = electron.app

app.on('open-file', onOpen)
app.on('open-url', onOpen)

function onOpen (e, torrentId) {
  e.preventDefault()
  mainWindow.send('action', 'addTorrent', torrentId)
}

// report crashes
// require('crash-reporter').start({
//   productName: 'WebTorrent',
//   companyName: 'WebTorrent',
//   submitURL: 'https://webtorrent.io/crash-report',
//   autoSubmit: true
// })

// prevent windows from being garbage collected
var mainWindow // eslint-disable-line no-unused-vars

app.on('ready', function () {
  mainWindow = createMainWindow()

  var menu = electron.Menu.buildFromTemplate(template)
  electron.Menu.setApplicationMenu(menu)
})

app.on('activate', function () {
  if (mainWindow) {
    mainWindow.show()
  } else {
    mainWindow = createMainWindow()
  }
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

var isQuitting = false
app.on('before-quit', function () {
  isQuitting = true
})

function createMainWindow () {
  var win = new electron.BrowserWindow({
    backgroundColor: '#282828',
    darkTheme: true,
    minWidth: 360,
    minHeight: 168,
    show: false,
    title: 'WebTorrent',
    titleBarStyle: 'hidden-inset',
    width: 500,
    height: 300
  })
  win.loadURL('file://' + path.join(__dirname, 'main', 'index.html'))
  win.webContents.on('did-finish-load', function () {
    setTimeout(function () {
      debug('startup time: %sms', Date.now() - startTime)
      win.show()
    }, 50)
  })
  win.on('close', function (e) {
    if (process.platform === 'darwin' && !isQuitting) {
      e.preventDefault()
      win.hide()
    }
  })
  win.once('closed', function () {
    mainWindow = null
  })
  return win
}

function addTorrentFromPaste () {
  var torrentIds = electron.clipboard.readText().split('\n')
  console.log(torrentIds)
  torrentIds.forEach(function (torrentId) {
    torrentId = torrentId.trim()
    if (torrentId.length === 0) return
    mainWindow.send('action', 'addTorrent', torrentId)
  })
}

function toggleDevTools (win) {
  win = win || electron.BrowserWindow.getFocusedWindow()

  if (win) {
    win.toggleDevTools()
  }
}

function reloadWindow (win) {
  win = win || electron.BrowserWindow.getFocusedWindow()

  if (win) {
    startTime = Date.now()
    win.webContents.reloadIgnoringCache()
  }
}

electron.ipcMain.on('action', function (event, action, ...args) {
  debug('action %s', action)
  if (action === 'addTorrentFromPaste') {
    addTorrentFromPaste()
  }
})

var template = [
  {
    label: 'File',
    submenu: [
      {
        label: 'Create New Torrent...',
        accelerator: 'CmdOrCtrl+N',
        click: function () {
          electron.dialog.showOpenDialog({
            title: 'Select a file or folder for the torrent file.',
            properties: [ 'openFile', 'openDirectory', 'multiSelections' ]
          }, function (filenames) {
            if (!Array.isArray(filenames)) return
            mainWindow.send('action', 'seed', filenames)
          })
        }
      },
      {
        label: 'Open Torrent File...',
        accelerator: 'CmdOrCtrl+O',
        click: function () {
          electron.dialog.showOpenDialog(mainWindow, {
            title: 'Select a .torrent file to open.',
            properties: [ 'openFile', 'multiSelections' ]
          }, function (filenames) {
            if (!Array.isArray(filenames)) return
            filenames.forEach(function (filename) {
              mainWindow.send('action', 'addTorrent', filename)
            })
          })
        }
      },
      {
        label: 'Open Torrent Address...',
        accelerator: 'CmdOrCtrl+U',
        click: function () { electron.dialog.showMessageBox({ message: 'TODO', buttons: ['OK'] }) }
      },
      {
        type: 'separator'
      },
      {
        label: 'Close Window',
        accelerator: 'CmdOrCtrl+W',
        role: 'close'
      }
    ]
  },
  {
    label: 'Edit',
    submenu: [
      {
        label: 'Cut',
        accelerator: 'CmdOrCtrl+X',
        role: 'cut'
      },
      {
        label: 'Copy',
        accelerator: 'CmdOrCtrl+C',
        role: 'copy'
      },
      {
        label: 'Paste Torrent Address',
        accelerator: 'CmdOrCtrl+V',
        role: 'paste'
      },
      {
        label: 'Select All',
        accelerator: 'CmdOrCtrl+A',
        role: 'selectall'
      }
    ]
  },
  {
    label: 'View',
    submenu: [
      {
        label: 'Toggle Full Screen',
        accelerator: (function () {
          if (process.platform === 'darwin') return 'Ctrl+Command+F'
          else return 'F11'
        })(),
        click: function (item, focusedWindow) {
          if (focusedWindow) focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
        }
      },
      {
        type: 'separator'
      },
      {
        label: 'Reload',
        accelerator: 'CmdOrCtrl+R',
        click: function (item, focusedWindow) {
          reloadWindow(focusedWindow)
        }
      },
      {
        label: 'Toggle Developer Tools',
        accelerator: (function () {
          if (process.platform === 'darwin') return 'Alt+Command+I'
          else return 'Ctrl+Shift+I'
        })(),
        click: function (item, focusedWindow) {
          toggleDevTools(focusedWindow)
        }
      }
    ]
  },
  {
    label: 'Window',
    role: 'window',
    submenu: [
      {
        label: 'Minimize',
        accelerator: 'CmdOrCtrl+M',
        role: 'minimize'
      }
    ]
  },
  {
    label: 'Help',
    role: 'help',
    submenu: [
      {
        label: 'Learn more about WebTorrent',
        click: function () { electron.shell.openExternal('https://webtorrent.io') }
      },
      {
        label: 'Contribute on GitHub',
        click: function () { electron.shell.openExternal('https://github.com/feross/webtorrent-app') }
      },
      {
        type: 'separator'
      },
      {
        label: 'Report an Issue...',
        click: function () { electron.shell.openExternal('https://github.com/feross/webtorrent-app/issues') }
      }
    ]
  }
]

if (process.platform === 'darwin') {
  var name = app.getName()
  template.unshift({
    label: name,
    submenu: [
      {
        label: 'About ' + name,
        role: 'about'
      },
      {
        type: 'separator'
      },
      {
        label: 'Services',
        role: 'services',
        submenu: []
      },
      {
        type: 'separator'
      },
      {
        label: 'Hide ' + name,
        accelerator: 'Command+H',
        role: 'hide'
      },
      {
        label: 'Hide Others',
        accelerator: 'Command+Alt+H',
        role: 'hideothers'
      },
      {
        label: 'Show All',
        role: 'unhide'
      },
      {
        type: 'separator'
      },
      {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: function () { app.quit() }
      }
    ]
  })

  // Window menu
  template[4].submenu.push(
    {
      type: 'separator'
    },
    {
      label: 'Bring All to Front',
      role: 'front'
    }
  )
}

// var progress = 0
// setInterval(function () {
//   progress += 0.1
//   mainWindow.setProgressBar(progress)
// }, 1000)
<|endoftext|>


<commit_before>
var batchqueue = require('./')
var assert = require('assert')

require('interleavings').test(function (async) {

  var output = []

  var queue = batchqueue(function (batch, cb) {
    batch.forEach(function (data) {
      output.push(data)
    })

    if(output.length == 99) {
      for(var i = 0; i < 100; i++)
        assert.equal(output[i], i)
      async.done()
    }
    async(cb)()
  })

  for(var i = 0; i < 100; i++) {
    queue(i)
  }

})
<commit_msg>test with drain function<commit_after>
var batchqueue = require('./')
var assert = require('assert')

require('interleavings').test(function (async) {

  var output = []

  var queue = batchqueue(function (batch, cb) {
    batch.forEach(function (data) {
      output.push(data)
    })

    async(cb)()
  }, function (err) {
    if(err) throw err
    console.log(output.length)
    for(var i = 0; i < 100; i++)
      assert.equal(output[i], i)
    async.done()
  })

  for(var i = 0; i < 100; i++) {
    queue(i)
  }

})
<|endoftext|>