<commit_before>var chai = require('chai');
var exec = require('shelljs').exec;
var util = require('util');
var sprintf = util.format;

var should = chai.should();
chai.Assertion.includeStack = true;

var baseConjureCmd = [
  'bin/conjure',
  '--server ' + __dirname + '/../../bin/test-server',
  '--root-dir ' + __dirname + '/../..',
  '--test-dir test/casper',
  '--verbose'
].join(' ') + ' ';
var baseConjureOpt = {stdout: true, stderr: true, failOnError: false};

function itShouldRunCasperWith(file, cb) {
  var expectation;
  if (typeof file === 'string') {
    expectation = 'should run test/' + file + '.js';
  } else {
    expectation = 'should run test/ files matching ' + file;
  }
  it(expectation, cb);
}

function basicRun(file) {
  itShouldRunCasperWith(file, function() {
    var res = exec(
      baseConjureCmd +
      '--grep-file "^' + file + '\\.js$" '
    );
    res.code.should.equal(0);
    res.output.trim().should.not.equal('');
  });
}

function detailedRun(file, args, cb) {
  args = [].concat(args);
  args.unshift('--grep-file "^' + file + '\\.js"');

  if (cb) {
    itShouldRunCasperWith(file, function() {
      cb(exec(baseConjureCmd + args.join(' ')));
    });
  } else {
    itShouldRunCasperWith(file, function() {
      var res = exec(baseConjureCmd + args.join(' '));
      res.code.should.equal(0);
      res.output.trim().should.not.equal('');
    });
  }
}

describe('/bin/conjure', function() {
  var basicTestFiles = [];
  basicTestFiles.forEach(function(file) {
    basicRun(file);
  });

  detailedRun('empty-test', [], function(res) {
    res.output.should.match(/\/empty-test.js.*Did not call conjure.test\(\)/);
    res.code.should.equal(1);
  });

  detailedRun('context-props', '--timeout 10000');
  detailedRun('bootstrap', '--bootstrap test/fixture/custom-bootstrap.js');
  detailedRun('grep-case', '--grep-case should only run this');
  detailedRun('grepv-case', '--grepv-case should prevent this from running');

  detailedRun('wait-status-on-timeout', [], function(res) {
    res.code.should.equal(1);
    res.output.should.match(/wait-status-on-timeout.js.*Auto-killed.*5000ms/);
    res.output.should.match(strSeqToRegex([
      ['should match'],
      ['selectorExists'],
      ['.selector-does-not-exist'],
      ['waitFor']
    ]));
  });

  detailedRun('flow', [], function(res) {
    res.code.should.equal(0);
    res.output.should.match(/path=weir integration,describe1,describe2,describe3,it1\n/);
  });

  detailedRun('stack-trace', [], function(res) {
    res.code.should.equal(1);
    res.output.should.not.contain('describe');
    res.output.should.match(strSeqToRegex([
      ['it', 'name', 'should trigger error']
    ]));
  });

  detailedRun('stack-trace', ['--full-trace'], function(res) {
    res.code.should.equal(1);
    res.output.should.match(strSeqToRegex([
      lane(0, 'describe', 'name', 'initial selector'),
      lane(1, 'it', 'name', 'should match'),
      lane(2, 'selectorExists'),
      lane(2, 'args', 'sel', 'body'),
      lane(2, 'closure', 'type', 'waitFor'),
      lane(2, 'closure', 'type', 'then'),
      lane(0, 'describe', 'name', 'r1'),
      lane(1, 'describe', 'name', 'd1'),
      lane(2, 'it', 'name', 'i1'),
      lane(1, 'describe', 'name', 'd2'),
      lane(2, 'describe', 'name', 'd3'),
      lane(3, 'describe', 'name', 'd4'),
      lane(4, 'it', 'name', 'i2'),
      lane(4, 'it', 'name', 'should trigger error')
    ]));
  });

  detailedRun('last-step', ['--full-trace', '--timeout 10000'], function(res) {
    res.code.should.equal(1);
    res.output.should.match(strSeqToRegex([
      lane(0, 'describe', 'name', 'initial selector'),
      lane(1, 'it', 'name', 'should match'),
      lane(2, 'selectorExists'),
      lane(3, 'args'),
      lane(3, 'closure', 'type', 'waitFor'),
      lane(3, 'closure', 'type', 'then'),
      lane(0, 'describe', 'name', 'r1'),
      lane(1, 'describe', 'name', 'click'),
      lane(2, 'it', 'name', 'should tag last step in native-click mode'),
      lane(3, 'click'),
      lane(4, 'args'),
      lane(4, 'selectorExists'),
      lane(5, 'args'),
      lane(5, 'closure'),
      lane(5, 'closure'),
      lane(2, 'it', 'name', 'should tag last step in jQuery-click mode'),
      lane(3, 'click'),
      lane(4, 'args'),
      lane(4, 'selectorExists'),
      lane(5, 'args'),
      lane(5, 'closure'),
      lane(5, 'closure'),
      lane(1, 'describe', 'name', 'then'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'then'),
      lane(1, 'describe', 'name', 'thenOpen'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'thenOpen'),
      lane(4, 'args'),
      lane(1, 'describe', 'name', 'assertSelText'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'assertSelText'),
      lane(4, 'args'),
      lane(4, 'closure'),
      lane(1, 'describe', 'name', 'each'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'each'),
      lane(4, 'args'),
      lane(4, 'closure'),
      lane(4, 'then'),
      lane(1, 'describe', 'name', 'openHash'),
      lane(2, 'it', 'name', 'should tag last step when not'),
      lane(3, 'openHash'),
      lane(4, 'args'),
      lane(2, 'it', 'name', 'should tag last step when waiting'),
      lane(3, 'openHash'),
      lane(4, 'args'),
      lane(4, 'selectorExists'),
      lane(5, 'args'),
      lane(5, 'closure'),
      lane(5, 'closure'),
      lane(1, 'describe', 'name', 'openInitUrl'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'openInitUrl'),
      lane(4, 'args')
    ]));
  });
});

/**
 * Build a regex that matches a sequence of sub-strings, with anything in between
 * them (e.g. terminal color codes), over a sequence of lines.
 *
 * @param {array} lines Each item is an array with a sequence of strings.
 * - Items represent expectations for a consecutive sequence of lines.
 * - Use empty strings to represent lines w/ no specific content expectation.
 * @return {regexp}
 */
function strSeqToRegex(lines) {
  var reStr = '';
  var linesLen = lines.length;

  lines.forEach(function(strSeq, idx) {
    strSeq.forEach(function(str) {
      if (str) { reStr += str + '.*'; }
    });
    if (idx < linesLen - 1) { reStr += '\\n.*'; }
  });

  return new RegExp(reStr, 'gm');
}

/**
 * Return a strSeqToRegex() compatible line definition with lane indentation.
 *
 * @param {number} depth Lane count
 * @param {string} str* String sequence
 * @return {array}
 */
function lane(depth, strSeq) {
  return [Array(depth + 1).join('\\|    ')].concat([].slice.call(arguments, 1));
}
<commit_msg>test(bin): Fix bad ref to real shelljs<commit_after>var chai = require('chai');
var shelljs = require('outer-shelljs').create();
var util = require('util');
var sprintf = util.format;

var should = chai.should();
chai.Assertion.includeStack = true;

var baseConjureCmd = [
  'bin/conjure',
  '--server ' + __dirname + '/../../bin/test-server',
  '--root-dir ' + __dirname + '/../..',
  '--test-dir test/casper',
  '--verbose'
].join(' ') + ' ';
var baseConjureOpt = {stdout: true, stderr: true, failOnError: false};

function itShouldRunCasperWith(file, cb) {
  var expectation;
  if (typeof file === 'string') {
    expectation = 'should run test/' + file + '.js';
  } else {
    expectation = 'should run test/ files matching ' + file;
  }
  it(expectation, cb);
}

function basicRun(file) {
  itShouldRunCasperWith(file, function() {
    var res = shelljs._(
      'exec',
      baseConjureCmd +
      '--grep-file "^' + file + '\\.js$" '
    );
    res.code.should.equal(0);
    res.output.trim().should.not.equal('');
  });
}

function detailedRun(file, args, cb) {
  args = [].concat(args);
  args.unshift('--grep-file "^' + file + '\\.js"');

  if (cb) {
    itShouldRunCasperWith(file, function() {
      cb(shelljs._('exec', baseConjureCmd + args.join(' ')));
    });
  } else {
    itShouldRunCasperWith(file, function() {
      var res = shelljs._('exec', baseConjureCmd + args.join(' '));
      res.code.should.equal(0);
      res.output.trim().should.not.equal('');
    });
  }
}

describe('/bin/conjure', function() {
  var basicTestFiles = [];
  basicTestFiles.forEach(function(file) {
    basicRun(file);
  });

  detailedRun('empty-test', [], function(res) {
    res.output.should.match(/\/empty-test.js.*Did not call conjure.test\(\)/);
    res.code.should.equal(1);
  });

  detailedRun('context-props', '--timeout 10000');
  detailedRun('bootstrap', '--bootstrap test/fixture/custom-bootstrap.js');
  detailedRun('grep-case', '--grep-case should only run this');
  detailedRun('grepv-case', '--grepv-case should prevent this from running');

  detailedRun('wait-status-on-timeout', [], function(res) {
    res.code.should.equal(1);
    res.output.should.match(/wait-status-on-timeout.js.*Auto-killed.*5000ms/);
    res.output.should.match(strSeqToRegex([
      ['should match'],
      ['selectorExists'],
      ['.selector-does-not-exist'],
      ['waitFor']
    ]));
  });

  detailedRun('flow', [], function(res) {
    res.code.should.equal(0);
    res.output.should.match(/path=weir integration,describe1,describe2,describe3,it1\n/);
  });

  detailedRun('stack-trace', [], function(res) {
    res.code.should.equal(1);
    res.output.should.not.contain('describe');
    res.output.should.match(strSeqToRegex([
      ['it', 'name', 'should trigger error']
    ]));
  });

  detailedRun('stack-trace', ['--full-trace'], function(res) {
    res.code.should.equal(1);
    res.output.should.match(strSeqToRegex([
      lane(0, 'describe', 'name', 'initial selector'),
      lane(1, 'it', 'name', 'should match'),
      lane(2, 'selectorExists'),
      lane(2, 'args', 'sel', 'body'),
      lane(2, 'closure', 'type', 'waitFor'),
      lane(2, 'closure', 'type', 'then'),
      lane(0, 'describe', 'name', 'r1'),
      lane(1, 'describe', 'name', 'd1'),
      lane(2, 'it', 'name', 'i1'),
      lane(1, 'describe', 'name', 'd2'),
      lane(2, 'describe', 'name', 'd3'),
      lane(3, 'describe', 'name', 'd4'),
      lane(4, 'it', 'name', 'i2'),
      lane(4, 'it', 'name', 'should trigger error')
    ]));
  });

  detailedRun('last-step', ['--full-trace', '--timeout 10000'], function(res) {
    res.code.should.equal(1);
    res.output.should.match(strSeqToRegex([
      lane(0, 'describe', 'name', 'initial selector'),
      lane(1, 'it', 'name', 'should match'),
      lane(2, 'selectorExists'),
      lane(3, 'args'),
      lane(3, 'closure', 'type', 'waitFor'),
      lane(3, 'closure', 'type', 'then'),
      lane(0, 'describe', 'name', 'r1'),
      lane(1, 'describe', 'name', 'click'),
      lane(2, 'it', 'name', 'should tag last step in native-click mode'),
      lane(3, 'click'),
      lane(4, 'args'),
      lane(4, 'selectorExists'),
      lane(5, 'args'),
      lane(5, 'closure'),
      lane(5, 'closure'),
      lane(2, 'it', 'name', 'should tag last step in jQuery-click mode'),
      lane(3, 'click'),
      lane(4, 'args'),
      lane(4, 'selectorExists'),
      lane(5, 'args'),
      lane(5, 'closure'),
      lane(5, 'closure'),
      lane(1, 'describe', 'name', 'then'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'then'),
      lane(1, 'describe', 'name', 'thenOpen'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'thenOpen'),
      lane(4, 'args'),
      lane(1, 'describe', 'name', 'assertSelText'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'assertSelText'),
      lane(4, 'args'),
      lane(4, 'closure'),
      lane(1, 'describe', 'name', 'each'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'each'),
      lane(4, 'args'),
      lane(4, 'closure'),
      lane(4, 'then'),
      lane(1, 'describe', 'name', 'openHash'),
      lane(2, 'it', 'name', 'should tag last step when not'),
      lane(3, 'openHash'),
      lane(4, 'args'),
      lane(2, 'it', 'name', 'should tag last step when waiting'),
      lane(3, 'openHash'),
      lane(4, 'args'),
      lane(4, 'selectorExists'),
      lane(5, 'args'),
      lane(5, 'closure'),
      lane(5, 'closure'),
      lane(1, 'describe', 'name', 'openInitUrl'),
      lane(2, 'it', 'name', 'should tag last step'),
      lane(3, 'openInitUrl'),
      lane(4, 'args')
    ]));
  });
});

/**
 * Build a regex that matches a sequence of sub-strings, with anything in between
 * them (e.g. terminal color codes), over a sequence of lines.
 *
 * @param {array} lines Each item is an array with a sequence of strings.
 * - Items represent expectations for a consecutive sequence of lines.
 * - Use empty strings to represent lines w/ no specific content expectation.
 * @return {regexp}
 */
function strSeqToRegex(lines) {
  var reStr = '';
  var linesLen = lines.length;

  lines.forEach(function(strSeq, idx) {
    strSeq.forEach(function(str) {
      if (str) { reStr += str + '.*'; }
    });
    if (idx < linesLen - 1) { reStr += '\\n.*'; }
  });

  return new RegExp(reStr, 'gm');
}

/**
 * Return a strSeqToRegex() compatible line definition with lane indentation.
 *
 * @param {number} depth Lane count
 * @param {string} str* String sequence
 * @return {array}
 */
function lane(depth, strSeq) {
  return [Array(depth + 1).join('\\|    ')].concat([].slice.call(arguments, 1));
}
<|endoftext|>


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

var daily = require("../../../controllers/crawler/daily");

describe("controllers/crawler/daily", function ()
{
    describe("1.fetchStoryIndexes", function ()
    {
        it("should fetch the story indexes of: 20130519", function (done)
        {
            var date = "20130519"
            var target = {
                date: "20130519",
                indexes: [401, 396, 395, 394, 390, 388]
            };
            daily.fetchStoryIndexes("20130519", function (err, res)
            {
                should.not.exist(err);
                res.date.should.equal(date);
                res.should.deepEqual(target);
                done();
            });
        });

        it("should not fetch the story indexes of: 20130518", function (done)
        {
            var date = "20130518"
            var target = {};
            daily.fetchStoryIndexes("20130518", function (err, res)
            {
                should.not.exist(err);
                res.should.deepEqual(target);
                done();
            });
        });

        it("should not fetch the story indexes of: 20133030", function (done)
        {
            var date = "20133030"
            daily.fetchStoryIndexes("20133030", function (err, res)
            {
                should.exist(err);
                done();
            });
        });
    });
});
<commit_msg>update<commit_after>var _ = require("lodash");
var should = require("should");

var daily = require("../../../controllers/crawler/daily");

describe("controllers/crawler/daily", function ()
{
    describe("1.fetchStoryIndexes", function ()
    {
        it("should fetch the story indexes of date: 20130519", function (done)
        {
            var date = "20130519"
            var target = {
                date: "20130519",
                indexes: [401, 396, 395, 394, 390, 388]
            };
            daily.fetchStoryIndexes(date, function (err, res)
            {
                should.not.exist(err);
                res.date.should.equal(date);
                res.should.deepEqual(target);
                done();
            });
        });

        it("should not fetch the story indexes of date: 20130518", function (done)
        {
            var date = "20130518"
            var target = {};
            daily.fetchStoryIndexes(date, function (err, res)
            {
                should.not.exist(err);
                res.should.deepEqual(target);
                done();
            });
        });

        it("should not fetch the story indexes of date: 20133030", function (done)
        {
            var date = "20133030"
            daily.fetchStoryIndexes(date, function (err, res)
            {
                should.exist(err);
                done();
            });
        });
    });

    describe("2.fetchStory", function ()
    {
        it("should fetch the story of id: 401", function (done)
        {
            var id = 401;
            var title = "学英语才是正经事儿";
            var imageSource = "人民教育出版社";
            var shareURL = "http://daily.zhihu.com/story/401";
            daily.fetchStory(id, function (err, res)
            {
                should.not.exist(err);
                res.id.should.equal(id);
                res.title.should.equal(title);
                res.imageSource.should.equal(imageSource);
                res.shareURL.should.equal(shareURL);
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>
((module) => {
	'use strict';

	var createClassFromSuper = require('simple-class-utils').createClass.super;
	var recursiveConstructor = require('./utils/recursive-constructor.js');
	var ProductIterableSuper = require('./utils/appx-super-class.js')(build, iterate);
	var manySameElements = require('./utils/many-same-elements.js');
	var mostMatrix = require('./utils/most-matrix.js');

	class ProductIterable extends ProductIterableSuper {

		most(callback, init) {
			return mostMatrix(callback, this, init);
		}

		static times(...args) {
			return ProductIterable.pow(...args);
		}

		static pow(iterable, exponent) {
			var args = manySameElements(iterable, exponent);
			return args.length ? new ProductIterable(...args) : [];
		}

	}

	module.exports = ProductIterable;

	ProductIterable.Result = createClassFromSuper(Array);

	function build(self, ...args) {
		return recursiveConstructor(self, ProductIterable, ...args);
	}

	function * iterate() {
		for (let i of this.first) {
			for (let j of this.second) {
				yield new ProductIterable.Result(i, ...j);
			}
		}
	}

})(module);
<commit_msg>class should be here<commit_after>
((module) => {
	'use strict';

	var createClassFromSuper = require('simple-class-utils').createClass.super;
	var recursiveConstructor = require('./utils/recursive-constructor.js');
	var manySameElements = require('./utils/many-same-elements.js');
	var mostMatrix = require('./utils/most-matrix.js');
	var ProductIterableSuper = require('./utils/appx-super-class.js')(build, iterate);

	class ProductIterable extends ProductIterableSuper {

		most(callback, init) {
			return mostMatrix(callback, this, init);
		}

		static times(...args) {
			return ProductIterable.pow(...args);
		}

		static pow(iterable, exponent) {
			var args = manySameElements(iterable, exponent);
			return args.length ? new ProductIterable(...args) : [];
		}

	}

	module.exports = ProductIterable;

	ProductIterable.Result = createClassFromSuper(Array);

	function build(self, ...args) {
		return recursiveConstructor(self, ProductIterable, ...args);
	}

	function * iterate() {
		for (let i of this.first) {
			for (let j of this.second) {
				yield new ProductIterable.Result(i, ...j);
			}
		}
	}

})(module);
<|endoftext|>


<commit_before>var path = require('path');
var DocsPlugin = require('../../../lib/plugin');

module.exports = {
  context: __dirname,

  entry: {
    simple: './simple'
  },

  output: {
    path: path.resolve(__dirname, '../../../build'),
    filename: '[name].js'
  },

  module: {
    loaders: [
      {
        test: /\.js/,
        loader: DocsPlugin.extract()
      }
    ]
  },

  plugins: [
    new DocsPlugin()
  ]
};<commit_msg>Add exclude option to docs loader config<commit_after>var path = require('path');
var DocsPlugin = require('../../../lib/plugin');

module.exports = {
  context: __dirname,

  entry: {
    simple: './simple'
  },

  output: {
    path: path.resolve(__dirname, '../../../build'),
    filename: '[name].js'
  },

  module: {
    loaders: [
      {
        test: /\.js/,
        exclude: [path.resolve(__dirname, '../../../node_modules')],
        loader: DocsPlugin.extract()
      }
    ]
  },

  plugins: [
    new DocsPlugin()
  ]
};<|endoftext|>


<commit_before>var vows = require('vows'),
    assert = require('assert'),
    AssetGraph = require('../lib/AssetGraph');

vows.describe('inlineKnockoutJsTemplates').addBatch({
    'After loading a test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/inlineKnockoutJsTemplates/'})
                .loadAssets('index.html')
                .populate()
                .run(this.callback);
        },
        'the graph should contain 1 Html asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Html'}).length, 2);
        },
        'the graph should contain 3 non-inline JavaScript assets': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'JavaScript', isInline: false}).length, 3);
        },
        'the graph should contain 4 JavaScriptAmdRequire/JavaScriptAmdDefine relations pointing at Knockout.js templates': function (assetGraph) {
            assert.equal(assetGraph.findRelations({type: ['JavaScriptAmdRequire', 'JavaScriptAmdDefine'], to: {type: 'KnockoutJsTemplate'}}).length, 4);
        },
        'the graph should contain 1 JavaScriptGetStaticUrl relation': function (assetGraph) {
            assert.equal(assetGraph.findRelations({type: 'JavaScriptGetStaticUrl'}).length, 1);
        },
        'the graph should contain 3 KnockoutJsTemplate assets': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'KnockoutJsTemplate'}).length, 3);
        },
        'the graph should contain 1 Png asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Png'}).length, 1);
        },
        'then run the inlineKnockoutJsTemplates transform': {
            topic: function (assetGraph) {
                assetGraph.inlineKnockoutJsTemplates().run(this.callback);
            },
            'the graph should contain no JavaScriptAmdRequire/JavaScriptAmdDefine relations pointing at Knockout.js templates': function (assetGraph) {
                assert.equal(assetGraph.findRelations({type: ['JavaScriptAmdRequire', 'JavaScriptAmdDefine'], to: {type: 'KnockoutJsTemplate'}}).length, 0);
            },
            'the graph should contain 4 HtmlInlineScriptTemplate relations, all of them from the main Html asset': function (assetGraph) {
                assert.equal(assetGraph.findRelations({type: 'HtmlInlineScriptTemplate'}).length, 4);
                assert.equal(assetGraph.findRelations({type: 'HtmlInlineScriptTemplate', from: {url: /\/index\.html$/}}).length, 4);
            },
            'index.html should have the expected contents': function (assetGraph) {
                assert.equal(assetGraph.findAssets({url: /\/index\.html$/})[0].text, '<!DOCTYPE html>\n\n\n\n    \n\n\n');
            },
            'one of the HtmlInlineScriptTemplateRelations should have an id of "foo" and point at a KnockoutJsTemplate asset with the correct contents': function (assetGraph) {
                var relation = assetGraph.findRelations({type: 'HtmlInlineScriptTemplate', node: function (node) {return node.getAttribute('id') === 'foo';}})[0];
                assert.ok(relation);
                assert.equal(relation.to.text, '\n');
            },
            'one of the HtmlInlineScriptTemplateRelations should have an id of "bar" and point at a KnockoutJsTemplate asset with the correct contents': function (assetGraph) {
                var relation = assetGraph.findRelations({type: 'HtmlInlineScriptTemplate', node: function (node) {return node.getAttribute('id') === 'bar';}})[0];
                assert.ok(relation);
                assert.equal(relation.to.text, '
\n
bar.ko
\n
\n');
            }
        }
    }
})['export'](module);
<commit_msg>Fixed the inlineKnockoutJsTemplates test.<commit_after>var vows = require('vows'),
    assert = require('assert'),
    AssetGraph = require('../lib/AssetGraph');

vows.describe('inlineKnockoutJsTemplates').addBatch({
    'After loading a test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/inlineKnockoutJsTemplates/'})
                .loadAssets('index.html')
                .populate()
                .run(this.callback);
        },
        'the graph should contain 1 Html asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Html'}).length, 2);
        },
        'the graph should contain 3 non-inline JavaScript assets': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'JavaScript', isInline: false}).length, 3);
        },
        'the graph should contain 4 JavaScriptAmdRequire/JavaScriptAmdDefine relations pointing at Knockout.js templates': function (assetGraph) {
            assert.equal(assetGraph.findRelations({type: ['JavaScriptAmdRequire', 'JavaScriptAmdDefine'], to: {type: 'KnockoutJsTemplate'}}).length, 4);
        },
        'the graph should contain 1 JavaScriptGetStaticUrl relation': function (assetGraph) {
            assert.equal(assetGraph.findRelations({type: 'JavaScriptGetStaticUrl'}).length, 1);
        },
        'the graph should contain 3 KnockoutJsTemplate assets': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'KnockoutJsTemplate'}).length, 3);
        },
        'the graph should contain 1 Png asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Png'}).length, 1);
        },
        'then run the inlineKnockoutJsTemplates transform': {
            topic: function (assetGraph) {
                assetGraph.inlineKnockoutJsTemplates().run(this.callback);
            },
            'the graph should contain no JavaScriptAmdRequire/JavaScriptAmdDefine relations pointing at Knockout.js templates': function (assetGraph) {
                assert.equal(assetGraph.findRelations({type: ['JavaScriptAmdRequire', 'JavaScriptAmdDefine'], to: {type: 'KnockoutJsTemplate'}}).length, 0);
            },
            'the graph should contain 4 HtmlInlineScriptTemplate relations, all of them from the main Html asset': function (assetGraph) {
                assert.equal(assetGraph.findRelations({type: 'HtmlInlineScriptTemplate'}).length, 4);
                assert.equal(assetGraph.findRelations({type: 'HtmlInlineScriptTemplate', from: {url: /\/index\.html$/}}).length, 4);
            },
            'index.html should have the expected contents': function (assetGraph) {
                assert.equal(assetGraph.findAssets({url: /\/index\.html$/})[0].text, '<!DOCTYPE html>\n\n\n\n    \n\n\n');
            },
            'one of the HtmlInlineScriptTemplateRelations should have an id of "foo" and point at a KnockoutJsTemplate asset with the correct contents': function (assetGraph) {
                var relation = assetGraph.findRelations({type: 'HtmlInlineScriptTemplate', node: function (node) {return node.getAttribute('id') === 'foo';}})[0];
                assert.ok(relation);
                assert.equal(relation.to.text, '\n');
            },
            'one of the HtmlInlineScriptTemplateRelations should have an id of "bar" and point at a KnockoutJsTemplate asset with the correct contents': function (assetGraph) {
                var relation = assetGraph.findRelations({type: 'HtmlInlineScriptTemplate', node: function (node) {return node.getAttribute('id') === 'bar';}})[0];
                assert.ok(relation);
                assert.equal(relation.to.text, '
\n
bar.ko
\n
\n');
            }
        }
    }
})['export'](module);
<|endoftext|>


<commit_before>var san = require('../../dist/san.ssr');
var MyComponent = san.defineComponent({
    template: `

            {{ item.title }}

{{ item.title }}

{{ item.desc }}

                {{ item.category.title }} |

    `,

    doneTodo: function (index) {
        var todo = this.data.get('todos', index);
        service.doneTodo(todo.id);

        this.data.set('todos.' + index + '.done', true);
    },

    rmTodo: function (index) {
        var todo = this.data.get('todos', index);
        service.rmTodo(todo.id);

        this.data.removeAt('todos', index);
    }
});

var data = {
    "todos": [
    ],
    "categories": [
        {
            "id": 8,
            "title": "category8",
            "color": "#c23531"
        },
        {
            "id": 7,
            "title": "category7",
            "color": "#314656"
        },
        {
            "id": 6,
            "title": "category6",
            "color": "#dd8668"
        },
        {
            "id": 5,
            "title": "category5",
            "color": "#91c7ae"
        },
        {
            "id": 4,
            "title": "category4",
            "color": "#6e7074"
        },
        {
            "id": 3,
            "title": "category3",
            "color": "#bda29a"
        },
        {
            "id": 2,
            "title": "category2",
            "color": "#44525d"
        },
        {
            "id": 1,
            "title": "category1",
            "color": "#c4ccd3"
        }
    ]
};

for (var i = 500; i > 0; i--) {
    data.todos.push({
        "id": i,
        "title": "TodoTitle" + i,
        "desc": "Todo Description" + i,
        "endTime": 1548149025190,
        "category": data.categories[i % 8],
        "addTime": 1548062625190,
        "done": i === 100 ? true : false
    });
}

var renderer = san.compileToRenderer(MyComponent);

console.log('----- List SSR Perf (500 items x 100 times) -----');

console.time('san')
for (var i = 0; i < 100; i++) {
    renderer(data);
}
console.timeEnd('san')

exports = module.exports = MyComponent;
<commit_msg>add artTpl<commit_after>const san = require('../../dist/san.ssr');
const art = require('art-template');

let artRenderer = art.compile(`

        <% for(let i = 0; i < categories.length; i++){ let item = categories[i]; %>
        <li style="background: <%= item.color %>">
            <a href="/todos/category/<%= item.id %>"><%= item.title %>

        <% } %>

        <% for(let index = 0; index < todos.length; index++){ let item = todos[index]; %>
        <li style="border-color: <%= item.category.color%>"
            class="<%= item.done ? 'todo-done' : ''%>"
        >

<%=  item.title %>

<%=  item.desc %>

                <% if (item.category) { %>
                <%=  item.category.title %> |
                <% } %>

            <a class="fa fa-pencil" href="/edit/<%=  item.id %>">

        <% } %>

`);

var MyComponent = san.defineComponent({
    template: `

            {{ item.title }}

{{ item.title }}

{{ item.desc }}

                {{ item.category.title }} |

    `,

    doneTodo: function (index) {
        var todo = this.data.get('todos', index);
        service.doneTodo(todo.id);

        this.data.set('todos.' + index + '.done', true);
    },

    rmTodo: function (index) {
        var todo = this.data.get('todos', index);
        service.rmTodo(todo.id);

        this.data.removeAt('todos', index);
    }
});

var data = {
    "todos": [
    ],
    "categories": [
        {
            "id": 8,
            "title": "category8",
            "color": "#c23531"
        },
        {
            "id": 7,
            "title": "category7",
            "color": "#314656"
        },
        {
            "id": 6,
            "title": "category6",
            "color": "#dd8668"
        },
        {
            "id": 5,
            "title": "category5",
            "color": "#91c7ae"
        },
        {
            "id": 4,
            "title": "category4",
            "color": "#6e7074"
        },
        {
            "id": 3,
            "title": "category3",
            "color": "#bda29a"
        },
        {
            "id": 2,
            "title": "category2",
            "color": "#44525d"
        },
        {
            "id": 1,
            "title": "category1",
            "color": "#c4ccd3"
        }
    ]
};

for (var i = 500; i > 0; i--) {
    data.todos.push({
        "id": i,
        "title": "TodoTitle" + i,
        "desc": "Todo Description" + i,
        "endTime": 1548149025190,
        "category": data.categories[i % 8],
        "addTime": 1548062625190,
        "done": i === 100 ? true : false
    });
}

var renderer = san.compileToRenderer(MyComponent);

console.log('----- List SSR Perf (500 items x 100 times) -----');

console.time('san');
for (var i = 0; i < 100; i++) {
    renderer(data);
}
console.timeEnd('san');

console.time('artTpl');
for (var i = 0; i < 100; i++) {
    artRenderer(data);
}
console.timeEnd('artTpl');

exports = module.exports = MyComponent;
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    require('load-grunt-tasks')(grunt);
    require('time-grunt')(grunt);
    var watchAdapter = require('grunt-mozu-appdev-sync/watch-adapter');
    grunt.initConfig({
        pkg: require('./package.json'),
        mozuconfig: require('./mozu.config.json'),
        jshint: {
            normal: ['./assets/src/**/*.js'],
            continuous: {
                options: { force: true },
                src: '<%= jshint.normal %>'
            }
        },
        browserify: {
            all: {
                dest: './assets/dist/app.js',
                src: ['./assets/src/index.js'],
                options: {
                    browserifyOptions: {
                        standalone: 'index',
                        commondir: false,
                        builtins: [
                            'stream',
                            'util',
                            'path',
                            'url',
                            'string_decoder',
                            'events',
                            'net',
                            'punycode',
                            'querystring',
                            'dgram',
                            'dns',
                            'assert',
                            'tls',
                            'crypto'
                        ],
                        insertGlobals: false,
                        detectGlobals: false
                    }
                }
            },
            discview: {
                dest: './app.tmp.js',
                src: '<%= browserify.all.src %>',
                options: {
                    ignore: '<%= browserify.all.options.ignore',
                    browserifyOptions: {
                        standalone: 'index',
                        commondir: false,
                        fullPaths: true,
                        builtins: '<%= browserify.all.options.browserifyOptions.builtins',
                        insertGlobals: false,
                        detectGlobals: false
                    }
                }
            }
        },
        mozusync: {
            options: {
                applicationKey: '<%= mozuconfig.workingApplicationKey %>',
                context: '<%= mozuconfig %>'
            },
            upload: {
                options: {
                    action: 'upload',
                    noclobber: true
                },
                src: ['./assets/**/*'],
                filter: 'isFile'
            },
            del: {
                options: { action: 'delete' },
                src: '<%= mozusync.upload.src %>',
                filter: 'isFile',
                // grunt's "files" object doesn't work for deletes,
                // since it automatically filters patterns that don't
                // match existing files. but for the task to work, we
                // need to match on deleted files! so use the "remove"
                // array in exactly the same way, as a list of files.
                remove: []
            },
            wipe: {
                options: { action: 'deleteAll' },
                src: '<%= mozusync.upload.src %>'
            }
        },
        watch: {
            options: { spawn: false },
            src: {
                files: '<%= jshint.normal %>',
                tasks: [
                    'jshint:continuous',
                    'browserify:all',
                    'manifest'
                ]
            },
            sync: {
                files: ['assets/**/*'],
                tasks: [
                    'mozusync:upload',
                    'mozusync:del'
                ]
            }
        },
        clean: {
            tmp: ['./*.tmp.js']
        }
    });
    grunt.loadNpmTasks('grunt-debug-task');

    var path = require('path');
    grunt.registerTask('manifest', 'Compiles the `functions.json` manifest for the Mozu Extensions Framework to read which custom functions are extended.', function() {
        var conf = grunt.config.get('browserify').all;
        var manifest = conf.src.reduce(function(functionsManifest, indexFile) {
            var index = require(indexFile);
            return functionsManifest.concat(Object.keys(index).map(function(key) {
               return {
                id: key,
                virtualPath: './' + path.relative('assets', conf.dest),
                actionId: index[key].actionName
               };
            }));
        }, []);
        grunt.file.write('./assets/functions.json', JSON.stringify({ exports: manifest }, null, 2));
        grunt.log.ok('Wrote ' + manifest.length + ' custom functions to functions.json');
    });
    grunt.registerTask('discview', 'Uses discify to view the size of the dependency tree', function() {
       var done = this.async();
       grunt.util.spawn({
        cmd: './node_modules/.bin/discify',
        args: ['./app.tmp.js', '--open']
       }, done);
    });
    watchAdapter(grunt, {
        src: 'mozusync.upload.src',
        action: 'upload',
        always: ['<%= browserify.all.dest %>','./assets/functions.json']
    });
    watchAdapter(grunt, {
        src: 'mozusync.del.remove',
        action: 'delete'
    });
    grunt.registerTask('test', []);
    grunt.registerTask('default', [
        'jshint:normal',
        'browserify:all',
        'manifest',
        'test',
        'mozusync:upload'
    ]);
    grunt.registerTask('reset', [
        'mozusync:wipe',
        'mozusync:upload'
    ]);
    grunt.registerTask('viewsize', [
        'browserify:discview',
        'discview',
        'clean'
    ]);
    grunt.registerTask('cont', ['watch']);
    grunt.registerTask('c', ['watch']);
    grunt.registerTask('w', ['watch']);
};<commit_msg>fixing bad template strings<commit_after>module.exports = function (grunt) {
    require('load-grunt-tasks')(grunt);
    require('time-grunt')(grunt);
    var watchAdapter = require('grunt-mozu-appdev-sync/watch-adapter');
    grunt.initConfig({
        pkg: require('./package.json'),
        mozuconfig: require('./mozu.config.json'),
        jshint: {
            normal: ['./assets/src/**/*.js'],
            continuous: {
                options: { force: true },
                src: '<%= jshint.normal %>'
            }
        },
        browserify: {
            all: {
                dest: './assets/dist/app.js',
                src: ['./assets/src/index.js'],
                options: {
                    browserifyOptions: {
                        standalone: 'index',
                        commondir: false,
                        builtins: [
                            'stream',
                            'util',
                            'path',
                            'url',
                            'string_decoder',
                            'events',
                            'net',
                            'punycode',
                            'querystring',
                            'dgram',
                            'dns',
                            'assert',
                            'tls',
                            'crypto'
                        ],
                        insertGlobals: false,
                        detectGlobals: false
                    }
                }
            },
            discview: {
                dest: './app.tmp.js',
                src: '<%= browserify.all.src %>',
                options: {
                    ignore: '<%= browserify.all.options.ignore %>',
                    browserifyOptions: {
                        standalone: 'index',
                        commondir: false,
                        fullPaths: true,
                        builtins: '<%= browserify.all.options.browserifyOptions.builtins %>',
                        insertGlobals: false,
                        detectGlobals: false
                    }
                }
            }
        },
        mozusync: {
            options: {
                applicationKey: '<%= mozuconfig.workingApplicationKey %>',
                context: '<%= mozuconfig %>'
            },
            upload: {
                options: {
                    action: 'upload',
                    noclobber: true
                },
                src: ['./assets/**/*'],
                filter: 'isFile'
            },
            del: {
                options: { action: 'delete' },
                src: '<%= mozusync.upload.src %>',
                filter: 'isFile',
                // grunt's "files" object doesn't work for deletes,
                // since it automatically filters patterns that don't
                // match existing files. but for the task to work, we
                // need to match on deleted files! so use the "remove"
                // array in exactly the same way, as a list of files.
                remove: []
            },
            wipe: {
                options: { action: 'deleteAll' },
                src: '<%= mozusync.upload.src %>'
            }
        },
        watch: {
            options: { spawn: false },
            src: {
                files: '<%= jshint.normal %>',
                tasks: [
                    'jshint:continuous',
                    'browserify:all',
                    'manifest'
                ]
            },
            sync: {
                files: ['assets/**/*'],
                tasks: [
                    'mozusync:upload',
                    'mozusync:del'
                ]
            }
        },
        clean: {
            tmp: ['./*.tmp.js']
        }
    });
    grunt.loadNpmTasks('grunt-debug-task');

    var path = require('path');
    grunt.registerTask('manifest', 'Compiles the `functions.json` manifest for the Mozu Extensions Framework to read which custom functions are extended.', function() {
        var conf = grunt.config.get('browserify').all;
        var manifest = conf.src.reduce(function(functionsManifest, indexFile) {
            var index = require(indexFile);
            return functionsManifest.concat(Object.keys(index).map(function(key) {
               return {
                id: key,
                virtualPath: './' + path.relative('assets', conf.dest),
                actionId: index[key].actionName
               };
            }));
        }, []);
        grunt.file.write('./assets/functions.json', JSON.stringify({ exports: manifest }, null, 2));
        grunt.log.ok('Wrote ' + manifest.length + ' custom functions to functions.json');
    });
    grunt.registerTask('discview', 'Uses discify to view the size of the dependency tree', function() {
       var done = this.async();
       grunt.util.spawn({
        cmd: './node_modules/.bin/discify',
        args: ['./app.tmp.js', '--open']
       }, done);
    });
    watchAdapter(grunt, {
        src: 'mozusync.upload.src',
        action: 'upload',
        always: ['<%= browserify.all.dest %>','./assets/functions.json']
    });
    watchAdapter(grunt, {
        src: 'mozusync.del.remove',
        action: 'delete'
    });
    grunt.registerTask('test', []);
    grunt.registerTask('default', [
        'jshint:normal',
        'browserify:all',
        'manifest',
        'test',
        'mozusync:upload'
    ]);
    grunt.registerTask('reset', [
        'mozusync:wipe',
        'mozusync:upload'
    ]);
    grunt.registerTask('viewsize', [
        'browserify:discview',
        'discview',
        'clean'
    ]);
    grunt.registerTask('cont', ['watch']);
    grunt.registerTask('c', ['watch']);
    grunt.registerTask('w', ['watch']);
};<|endoftext|>


<commit_before>var recurse = require('../');
var test = require('tap').test;
var fs = require('fs');
var Stream = require('stream');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');

test('recursive dirs', function (t) {
  var files = [
    'recursive/1.txt',
    'recursive/2.txt',
    'recursive/sub/3.txt',
    'recursive/sub/subsub/4.txt',
    'recursive/sub/subsub/subsubsub/5.txt',
    'recursive/sub/subsub/subsubsub/6.txt',
    'recursive/sub2/7.txt'
  ];

  mkdirp.sync('recursive/sub/subsub/subsubsub');
  mkdirp.sync('recursive/sub/subsub/empty');
  mkdirp.sync('recursive/sub2');

  files.forEach(function (f) {
    fs.openSync(f, 'w');
  });

  t.plan(1);

  var recursive = recurse('recursive');

  var all = [];
  var concat = new Stream;
  concat.writable = true;
  concat.write = function (data) {
    all.push(data);
  };
  concat.end = function () {
    t.equal(all.sort().join('\n'), files.sort().join('\n'));
    rimraf.sync('recursive');
  };

  recursive.pipe(concat);
});
<commit_msg>Use testfs for recursive tests.<commit_after>var recurse = require('../');
var test = require('tap').test;
var Stream = require('stream');
var path = require('path');

// TODO: extract to module:
var testfs = require('./lib/testfs');

test('recursive dirs', function (t) {
  t.plan(1);

  var files = [
    '1.txt',
    '2.txt',
    'sub/3.txt',
    'sub/subsub/4.txt',
    'sub/subsub/subsubsub/5.txt',
    'sub/subsub/subsubsub/6.txt',
    'sub2/7.txt',
  ];

  var paths = files.slice(0);
  paths.push('sub/subsub/empty/');

  var prefix = 'recursive';

  var fs = testfs(prefix, paths, function (err) {
    var recursive = recurse('recursive');

    var all = [];
    var concat = new Stream;
    concat.writable = true;
    concat.write = function (data) {
      all.push(data);
    };
    concat.end = function () {
      t.equal(
        all.sort().join('\n'),
        files.map(function (name) {
          return path.join(prefix, name);
        }).sort().join('\n')
      );
      fs.rm();
    };

    recursive.pipe(concat);
  });
});
<|endoftext|>


<commit_before>describe('RichTypo', function() {
	var rt = require('../richtypo');

	function _symb(s) {
		return s.replace(/_/g, String.fromCharCode(160));
	}

	it('has API functions', function() {
		rt.lang('ru');
		expect(rt.lite('Такса — животное.'))
			.toBe(_symb('Такса_— животное.'));
	});

	it('has API functions', function() {
		expect(rt.lang).toBeDefined();
		expect(rt.lite).toBeDefined();
		expect(rt.rich).toBeDefined();
	});

	it('safe tags ru', function() {
		rt.lang('ru');

		expect(rt.rich(' -->> '))
			.toBe(' -->> ');

		expect(rt.rich(' а — б '))
			.toBe(' а — б ');

		expect(rt.rich('А текст внутри тегов  не надо типографить.'))
			.toBe(_symb('А_текст внутри тегов  не_надо типографить.'));

		expect(rt.rich('Теперь всё — вместе. А текст внутри тегов  не надо типографить. И кода кусок:
\nа — б\nа — б\nа — б\n
.'))
			.toBe(_symb('Теперь всё_— вместе. А_текст внутри тегов  не_надо типографить. И_кода кусок:
\nа — б\nа — б\nа — б\n
.'));
	});

	it('spaces lite ru', function() {
		rt.lang('ru');

		expect(rt.rich('Такса — животное.'))
			.toBe(_symb('Такса_— животное.'));

		expect(rt.rich('Там было много тлонов, тутликов, табачек и т. п. и т. п.'))
			.toBe(_symb('Там было много тлонов, тутликов, табачек и_т._п. и_т._п.'));
	});

	it('spaces ru', function() {
		rt.lang('ru');

		expect(rt.rich('Прочитай § 13 журнала «Такса» № 27, там про тлонов, тутликов, табачек.'))
			.toBe(_symb('Прочитай §_13 журнала «Такса» №_27, там про тлонов, тутликов, табачек.'));

		expect(rt.rich('Приснился однажды В. И. Ленин В. Путину.'))
			.toBe('Приснился однажды <nobr>В. И. Ленин</nobr> <nobr>В. Путину</nobr>.');

		expect(rt.rich('Из-за чего-то всё-таки это как-то очень странно.'))
			.toBe('<nobr>Из-за</nobr> <nobr>чего-то</nobr> всё-таки это <nobr>как-то</nobr> очень странно.');

		expect(rt.rich('За колбасой в магазин пошла такса из резины.'))
			.toBe(_symb('За_колбасой в_магазин пошла такса из_резины.'));

		expect(rt.rich('Это ж как бы колбаса!'))
			.toBe(_symb('Это_ж как_бы колбаса!'));

		expect(rt.rich('Колбаса стоит 23 р. Такса стоит 1000000 $.'))
			.toBe(_symb('Колбаса стоит 23_р. Такса стоит 1000000_$.'));

		expect(rt.rich('Это было в 1927 г.'))
			.toBe(_symb('Это было в_1927_г.'));

		expect(rt.rich('Цири родилась 30 июля.'))
			.toBe(_symb('Цири родилась 30_июля.'));
	});

	it('lite ru', function() {
		rt.lang('ru');

		expect(rt.lite('Эх...'))
			.toBe('Эх…');

		expect(rt.lite('Такса -- зверь'))
			.toBe(_symb('Такса_— зверь'));

		expect(rt.lite('Такса - зверь'))
			.toBe(_symb('Такса_— зверь'));

		expect(rt.lite('
- Бадыдыщь!
'))
			.toBe(_symb('
— Бадыдыщь!
'));

		expect(rt.lite('- Бадыдыщь!\n- Бадыдыщь!'))
			.toBe('— Бадыдыщь!\n— Бадыдыщь!');

		expect(rt.lite('
- Бадыдыщь!
'))
			.toBe(_symb('
— Бадыдыщь!
'));
	});

	it('lite en', function() {
		rt.lang('en');

		expect(rt.lite('Yep...'))
			.toBe('Yep…');

		expect(rt.lite('Dachshund--beast'))
			.toBe(_symb('<nobr>Dachshund—</nobr>beast'));
	});

	it('quotes ru', function() {
		rt.lang('ru');

		expect(rt.lite('Тут просто "текст в кавычках".'))
			.toBe('Тут просто «текст в кавычках».');

		expect(rt.lite('"Текст в кавычках "в кавычках"".'))
			.toBe('«Текст в кавычках «в кавычках»».');

		expect(rt.lite('А тут "текст "в кавычках" в кавычках".'))
			.toBe('А тут «текст «в кавычках» в кавычках».');

		expect(rt.lite('И "клинический "случай".'))
			.toBe('И «клинический «случай».');
	});

	it('quotes en', function() {
		rt.lang('en');

		expect(rt.lite('There is a "text in quotes."'))
			.toBe('There is a “text in quotes.”');

		expect(rt.lite('There is a "text "in quotes" in quotes."'))
			.toBe('There is a “text “in quotes” in quotes.”');
	});

	it('amps en', function() {
		rt.lang('en');

		expect(rt.title('Dessi & Tsiri'))
			.toBe('Dessi & Tsiri');
	});

	it('abbrs ru', function() {
		rt.lang('ru');

		expect(rt.title('На ХХ таксовке ТАКСА было 37 такс'))
			.toBe(_symb('На_ХХ таксовке ТАКСА было 37 такс'));
	});

	it('abbrs en', function() {
		rt.lang('en');

		expect(rt.title('On XX dachshund party DOXIE was 37 wieners'))
			.toBe(_symb('On_XX dachshund party DOXIE was 37 wieners'));
	});

	it('hanging', function() {
		expect(rt.title('The “quoted text.”'))
			.toBe(_symb('The  “quoted text.”'));

		expect(rt.title('“Quoted text” two.'))
			.toBe(_symb('“Quoted text” two.'));

		expect(rt.title('alert("Hello world!")'))
			.toBe(_symb('alert("Hello world!")'));
	});

	it('textify', function() {
		expect(rt.textify(rt.title('The “quoted text.”')))
			.toBe(_symb('The “quoted text.”'));

			expect(rt.textify(rt.lite('- Бадыдыщь!\n- Бадыдыщь!', 'ru')))
				.toBe('— Бадыдыщь!\n— Бадыдыщь!');
	});

	it('leaves commented out tags alone', function() {
		expect(rt.lite(''))
			.toBe('');
	});

	it('plays nice with ie conditional comments', function() {
		expect(rt.title(''))
			.toBe('');

		expect(rt.title(''))
			.toBe('');
	});

});
<commit_msg>Update failing test.<commit_after>describe('RichTypo', function() {
	var rt = require('../richtypo');

	function _symb(s) {
		return s.replace(/_/g, String.fromCharCode(160));
	}

	it('has API functions', function() {
		rt.lang('ru');
		expect(rt.lite('Такса — животное.'))
			.toBe(_symb('Такса_— животное.'));
	});

	it('has API functions', function() {
		expect(rt.lang).toBeDefined();
		expect(rt.lite).toBeDefined();
		expect(rt.rich).toBeDefined();
	});

	it('safe tags ru', function() {
		rt.lang('ru');

		expect(rt.rich(' -->> '))
			.toBe(' -->> ');

		expect(rt.rich(' а — б '))
			.toBe(' а — б ');

		expect(rt.rich('А текст внутри тегов  не надо типографить.'))
			.toBe(_symb('А_текст внутри тегов  не_надо типографить.'));

		expect(rt.rich('Теперь всё — вместе. А текст внутри тегов  не надо типографить. И кода кусок:
\nа — б\nа — б\nа — б\n
.'))
			.toBe(_symb('Теперь всё_— вместе. А_текст внутри тегов  не_надо типографить. И_кода кусок:
\nа — б\nа — б\nа — б\n
.'));
	});

	it('spaces lite ru', function() {
		rt.lang('ru');

		expect(rt.rich('Такса — животное.'))
			.toBe(_symb('Такса_— животное.'));

		expect(rt.rich('Там было много тлонов, тутликов, табачек и т. п. и т. п.'))
			.toBe(_symb('Там было много тлонов, тутликов, табачек и_т._п. и_т._п.'));
	});

	it('spaces ru', function() {
		rt.lang('ru');

		expect(rt.rich('Прочитай § 13 журнала «Такса» № 27, там про тлонов, тутликов, табачек.'))
			.toBe(_symb('Прочитай §_13 журнала «Такса» №_27, там про тлонов, тутликов, табачек.'));

		expect(rt.rich('Приснился однажды В. И. Ленин В. Путину.'))
			.toBe('Приснился однажды <nobr>В. И. Ленин</nobr> <nobr>В. Путину</nobr>.');

		expect(rt.rich('Из-за чего-то всё-таки это как-то очень странно.'))
			.toBe('<nobr>Из-за</nobr> <nobr>чего-то</nobr> всё-таки это <nobr>как-то</nobr> очень странно.');

		expect(rt.rich('За колбасой в магазин пошла такса из резины.'))
			.toBe(_symb('За_колбасой в_магазин пошла такса из_резины.'));

		expect(rt.rich('Это ж как бы колбаса!'))
			.toBe(_symb('Это_ж как_бы колбаса!'));

		expect(rt.rich('Колбаса стоит 23 р. Такса стоит 1000000 $.'))
			.toBe(_symb('Колбаса стоит 23_р. Такса стоит 1000000_$.'));

		expect(rt.rich('Это было в 1927 г.'))
			.toBe(_symb('Это было в_1927_г.'));

		expect(rt.rich('Цири родилась 30 июля.'))
			.toBe(_symb('Цири родилась 30_июля.'));
	});

	it('lite ru', function() {
		rt.lang('ru');

		expect(rt.lite('Эх...'))
			.toBe('Эх…');

		expect(rt.lite('Такса -- зверь'))
			.toBe(_symb('Такса_— зверь'));

		expect(rt.lite('Такса - зверь'))
			.toBe(_symb('Такса_— зверь'));

		expect(rt.lite('
- Бадыдыщь!
'))
			.toBe(_symb('
— Бадыдыщь!
'));

		expect(rt.lite('- Бадыдыщь!\n- Бадыдыщь!'))
			.toBe('— Бадыдыщь!\n— Бадыдыщь!');

		expect(rt.lite('
- Бадыдыщь!
'))
			.toBe(_symb('
— Бадыдыщь!
'));
	});

	it('lite en', function() {
		rt.lang('en');

		expect(rt.lite('Yep...'))
			.toBe('Yep…');

		expect(rt.lite('Dachshund--beast'))
			.toBe(_symb('<nobr>Dachshund—</nobr>beast'));
	});

	it('quotes ru', function() {
		rt.lang('ru');

		expect(rt.lite('Тут просто "текст в кавычках".'))
			.toBe('Тут просто «текст в кавычках».');

		expect(rt.lite('"Текст в кавычках "в кавычках"".'))
			.toBe('«Текст в кавычках «в кавычках»».');

		expect(rt.lite('А тут "текст "в кавычках" в кавычках".'))
			.toBe('А тут «текст «в кавычках» в кавычках».');

		expect(rt.lite('И "клинический "случай".'))
			.toBe('И «клинический «случай».');
	});

	it('quotes en', function() {
		rt.lang('en');

		expect(rt.lite('There is a "text in quotes."'))
			.toBe('There is a “text in quotes.”');

		expect(rt.lite('There is a "text "in quotes" in quotes."'))
			.toBe('There is a “text “in quotes” in quotes.”');
	});

	it('amps en', function() {
		rt.lang('en');

		expect(rt.title('Dessi & Tsiri'))
			.toBe('Dessi & Tsiri');
	});

	it('abbrs ru', function() {
		rt.lang('ru');

		expect(rt.title('На ХХ таксовке ТАКСА было 37 такс'))
			.toBe(_symb('На_ХХ таксовке ТАКСА было 37 такс'));
	});

	it('abbrs en', function() {
		rt.lang('en');

		expect(rt.title('On XX dachshund party DOXIE was 37 wieners'))
			.toBe(_symb('On_XX dachshund party DOXIE was 37 wieners'));
	});

	it('hanging', function() {
		expect(rt.title('The “quoted text.”'))
			.toBe(_symb('The  “quoted text.”'));

		expect(rt.title('“Quoted text” two.'))
			.toBe(_symb('“Quoted text” two.'));

		expect(rt.title('alert("Hello world!")'))
			.toBe(_symb('alert("Hello world!")'));
	});

	it('textify', function() {
		expect(rt.textify(rt.title('The “quoted text.”')))
			.toBe(_symb('The “quoted text.”'));

			expect(rt.textify(rt.lite('- Бадыдыщь!\n- Бадыдыщь!', 'ru')))
				.toBe('— Бадыдыщь!\n— Бадыдыщь!');
	});

	it('leaves commented out tags alone', function() {
		expect(rt.lite(''))
			.toBe('');
	});

	it('plays nice with ie conditional comments', function() {
		expect(rt.title(''))
			.toBe('');

		expect(rt.title(''))
			.toBe('');
	});

});
<|endoftext|>


<commit_before>/*  ------------------------------------------------------------------------ */

const ccxt     = require ('../ccxt')
    , assert   = require ('assert')
    , log      = require ('ololog')
    , ansi     = require ('ansicolor').nice;

/*  ------------------------------------------------------------------------ */

describe ('ccxt base code', () => {

    it ('sleep() is robust', async () => {

        const delay = 10

        for (let i = 0; i < 30; i++) {

            const before = Date.now ()
            await ccxt.sleep (delay)
            const now = Date.now ()

            const elapsed = now - before
            assert (elapsed >= (delay - 1)) // not too fast
            assert (elapsed < (delay * 2)) // but not too slow either...
        }
    })

    it ('calculateFee() works', () => {

        const price  = 100.00
        const amount = 10.00
        const taker  = 0.0025
        const maker  = 0.0010
        const fees   = { taker, maker }
        const market = {
            'id':     'foobar',
            'symbol': 'FOO/BAR',
            'base':   'FOO',
            'quote':  'BAR',
            'taker':   taker,
            'maker':   maker,
            'precision': {
                'amount': 8,
                'price': 8,
            },
        }

        const exchange = new ccxt.Exchange ({
            'id': 'mock',
            'markets': {
                'FOO/BAR': market,
            },
        })

        Object.keys (fees).forEach (takerOrMaker => {

            const result = exchange.calculateFee (market['symbol'], 'limit', 'sell', amount, price, takerOrMaker, {})

            assert.deepEqual (result, {
                'currency': 'BAR',
                'rate': fees[takerOrMaker],
                'cost': fees[takerOrMaker] * amount * price,
            })
        })
    })

    it ('rate limiting works', async () => {

        const calls = []
        const rateLimit = 100
        const exchange = new ccxt.Exchange ({

            id: 'mock',
            rateLimit,
            enableRateLimit: true,

            async executeRestRequest (...args) { calls.push ({ when: Date.now (), path: args[0], args }) }
        })

        await exchange.fetch ('foo')
        await exchange.fetch ('bar')
        await exchange.fetch ('baz')

        await Promise.all ([
            exchange.fetch ('qux'),
            exchange.fetch ('zap'),
            exchange.fetch ('lol')
        ])

        assert.deepEqual (calls.map (x => x.path), ['foo', 'bar', 'baz', 'qux', 'zap', 'lol'])

        calls.reduce ((prevTime, call) => {
            // log ('delta T:', call.when - prevTime)
            assert ((call.when - prevTime) >= (rateLimit - 1))
            return call.when
        }, 0)
    })

    it ('getCurrencyUsedOnOpenOrders() works', () => {

        const calls = []
        const rateLimit = 100
        const exchange = new ccxt.Exchange ({
            'orders': [
                { status: 'open',   symbol: 'ETH/BTC', side: 'sell', price: 200.0, amount: 20.0 },
                { status: 'open',   symbol: 'ETH/BTC', side: 'buy',  price: 200.0, amount: 20.0 },
                { status: 'open',   symbol: 'ETH/BTC', side: 'sell', price: 200.0, amount: 20.0 },
                { status: 'closed', symbol: 'BTC/USD', side: 'sell', price: 10.0, amount: 10.0 },
                { status: 'open',   symbol: 'BTC/USD', side: 'buy',  price: 10.0, amount: 10.0 },
                { status: 'open',   symbol: 'BTC/USD', side: 'sell', price: 10.0, amount: 10.0 },
            ],
            'markets': {
                'ETH/BTC': { id: 'ETH/BTC', symbol: 'ETH/BTC', base: 'ETH', quote: 'BTC' },
                'BTC/USD': { id: 'BTC/USD', symbol: 'BTC/USD', base: 'BTC', quote: 'USD' },
            },
        })

        assert.equal (exchange.getCurrencyUsedOnOpenOrders ('LTC'), 0)
        assert.equal (exchange.getCurrencyUsedOnOpenOrders ('ETH'), 40)
        assert.equal (exchange.getCurrencyUsedOnOpenOrders ('USD'), 100)
        assert.equal (exchange.getCurrencyUsedOnOpenOrders ('BTC'), 4010)

    })

    it ('aggregate() works', () => {

        const bids = [
            [ 789.1, 123.0 ],
            [ 789.100, 123.0 ],
            [ 123.0, 456.0 ],
            [ 789.0, 123.0 ],
            [ 789.10, 123.0 ],
        ]

        const asks = [
            [ 123.0, 456.0 ],
            [ 789.0, 123.0 ],
            [ 789.10, 123.0 ],
        ]

        assert.deepEqual (ccxt.aggregate (bids.sort ()), [
            [ 123.0, 456.0 ],
            [ 789.0, 123.0 ],
            [ 789.1, 369.0 ],
        ])

        assert.deepEqual (ccxt.aggregate (asks.sort ()), [
            [ 123.0, 456.0 ],
            [ 789.0, 123.0 ],
            [ 789.10, 123.0 ],
        ])

        assert.deepEqual (ccxt.aggregate ([]), [])
    })

    it ('deepExtend() works', () => {

        let count = 0;

        const values = [{
            a: 1,
            b: 2,
            d: {
                a: 1,
                b: [],
                c: { test1: 123, test2: 321 }},
            f: 5,
            g: 123,
            i: 321,
            j: [1, 2],
        },
        {
            b: 3,
            c: 5,
            d: {
                b: { first: 'one', second: 'two' },
                c: { test2: 222 }},
            e: { one: 1, two: 2 },
            f: [{ 'foo': 'bar' }],
            g: (void 0),
            h: /abc/g,
            i: null,
            j: [3, 4]
        }]

        const extended = ccxt.deepExtend (...values)
        assert.deepEqual ({
            a: 1,
            b: 3,
            d: {
                a: 1,
                b: { first: 'one', second: 'two' },
                c: { test1: 123, test2: 222 }
            },
            f: [{ 'foo': 'bar' }],
            g: undefined,
            c: 5,
            e: { one: 1, two: 2 },
            h: /abc/g,
            i: null,
            j: [3, 4]
        }, extended)
    })

    it ('groupBy() works', () => {

        const array = [
            { 'foo': 'a' },
            { 'foo': 'b' },
            { 'foo': 'c' },
            { 'foo': 'b' },
            { 'foo': 'c' },
            { 'foo': 'c' },
        ]

        assert.deepEqual (ccxt.groupBy (array, 'foo'), {
            'a': [ { 'foo': 'a' } ],
            'b': [ { 'foo': 'b' }, { 'foo': 'b' } ],
            'c': [ { 'foo': 'c' }, { 'foo': 'c' }, { 'foo': 'c' } ],
        })
    })

    it ('truncate() works', () => {

        assert.equal (ccxt.truncate (0, 0), 0)
        assert.equal (ccxt.truncate (-17.56,   2), -17.56)
        assert.equal (ccxt.truncate ( 17.56,   2),  17.56)
        assert.equal (ccxt.truncate (-17.569,  2), -17.56)
        assert.equal (ccxt.truncate ( 17.569,  2),  17.56)
        assert.equal (ccxt.truncate (49.9999,  4), 49.9999)
        assert.equal (ccxt.truncate (49.99999, 4), 49.9999)
    })

    it.only ('parseBalance() works', () => {

        const exchange = new ccxt.Exchange ({
            'markets': {
                'ETH/BTC': { 'id': 'ETH/BTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', }
            }
        })

        const input = {
            'ETH': { 'free': 10, 'used': 10, 'total': 20 },
            'ZEC': { 'free': 0, 'used': 0, 'total': 0 },
        }

        const expected = {
            'ETH': { 'free': 10, 'used': 10, 'total': 20 },
            'ZEC': { 'free': 0, 'used': 0, 'total': 0 },
            'free': {
                'ETH': 10,
                'ZEC': 0,
            },
            'used': {
                'ETH': 10,
                'ZEC': 0,
            },
            'total': {
                'ETH': 20,
                'ZEC': 0,
            },
        }

        const actual = exchange.parseBalance (input)

        log ('Actual:', '\t', actual)

        log ('Expected:', '\t', expected)

        assert.deepEqual (actual, expected)
    })
})

/*  ------------------------------------------------------------------------ */
<commit_msg>it.only → it in parseBalance test_base<commit_after>/*  ------------------------------------------------------------------------ */

const ccxt     = require ('../ccxt')
    , assert   = require ('assert')
    , log      = require ('ololog')
    , ansi     = require ('ansicolor').nice;

/*  ------------------------------------------------------------------------ */

describe ('ccxt base code', () => {

    it ('sleep() is robust', async () => {

        const delay = 10

        for (let i = 0; i < 30; i++) {

            const before = Date.now ()
            await ccxt.sleep (delay)
            const now = Date.now ()

            const elapsed = now - before
            assert (elapsed >= (delay - 1)) // not too fast
            assert (elapsed < (delay * 2)) // but not too slow either...
        }
    })

    it ('calculateFee() works', () => {

        const price  = 100.00
        const amount = 10.00
        const taker  = 0.0025
        const maker  = 0.0010
        const fees   = { taker, maker }
        const market = {
            'id':     'foobar',
            'symbol': 'FOO/BAR',
            'base':   'FOO',
            'quote':  'BAR',
            'taker':   taker,
            'maker':   maker,
            'precision': {
                'amount': 8,
                'price': 8,
            },
        }

        const exchange = new ccxt.Exchange ({
            'id': 'mock',
            'markets': {
                'FOO/BAR': market,
            },
        })

        Object.keys (fees).forEach (takerOrMaker => {

            const result = exchange.calculateFee (market['symbol'], 'limit', 'sell', amount, price, takerOrMaker, {})

            assert.deepEqual (result, {
                'currency': 'BAR',
                'rate': fees[takerOrMaker],
                'cost': fees[takerOrMaker] * amount * price,
            })
        })
    })

    it ('rate limiting works', async () => {

        const calls = []
        const rateLimit = 100
        const exchange = new ccxt.Exchange ({

            id: 'mock',
            rateLimit,
            enableRateLimit: true,

            async executeRestRequest (...args) { calls.push ({ when: Date.now (), path: args[0], args }) }
        })

        await exchange.fetch ('foo')
        await exchange.fetch ('bar')
        await exchange.fetch ('baz')

        await Promise.all ([
            exchange.fetch ('qux'),
            exchange.fetch ('zap'),
            exchange.fetch ('lol')
        ])

        assert.deepEqual (calls.map (x => x.path), ['foo', 'bar', 'baz', 'qux', 'zap', 'lol'])

        calls.reduce ((prevTime, call) => {
            // log ('delta T:', call.when - prevTime)
            assert ((call.when - prevTime) >= (rateLimit - 1))
            return call.when
        }, 0)
    })

    it ('getCurrencyUsedOnOpenOrders() works', () => {

        const calls = []
        const rateLimit = 100
        const exchange = new ccxt.Exchange ({
            'orders': [
                { status: 'open',   symbol: 'ETH/BTC', side: 'sell', price: 200.0, amount: 20.0 },
                { status: 'open',   symbol: 'ETH/BTC', side: 'buy',  price: 200.0, amount: 20.0 },
                { status: 'open',   symbol: 'ETH/BTC', side: 'sell', price: 200.0, amount: 20.0 },
                { status: 'closed', symbol: 'BTC/USD', side: 'sell', price: 10.0, amount: 10.0 },
                { status: 'open',   symbol: 'BTC/USD', side: 'buy',  price: 10.0, amount: 10.0 },
                { status: 'open',   symbol: 'BTC/USD', side: 'sell', price: 10.0, amount: 10.0 },
            ],
            'markets': {
                'ETH/BTC': { id: 'ETH/BTC', symbol: 'ETH/BTC', base: 'ETH', quote: 'BTC' },
                'BTC/USD': { id: 'BTC/USD', symbol: 'BTC/USD', base: 'BTC', quote: 'USD' },
            },
        })

        assert.equal (exchange.getCurrencyUsedOnOpenOrders ('LTC'), 0)
        assert.equal (exchange.getCurrencyUsedOnOpenOrders ('ETH'), 40)
        assert.equal (exchange.getCurrencyUsedOnOpenOrders ('USD'), 100)
        assert.equal (exchange.getCurrencyUsedOnOpenOrders ('BTC'), 4010)

    })

    it ('aggregate() works', () => {

        const bids = [
            [ 789.1, 123.0 ],
            [ 789.100, 123.0 ],
            [ 123.0, 456.0 ],
            [ 789.0, 123.0 ],
            [ 789.10, 123.0 ],
        ]

        const asks = [
            [ 123.0, 456.0 ],
            [ 789.0, 123.0 ],
            [ 789.10, 123.0 ],
        ]

        assert.deepEqual (ccxt.aggregate (bids.sort ()), [
            [ 123.0, 456.0 ],
            [ 789.0, 123.0 ],
            [ 789.1, 369.0 ],
        ])

        assert.deepEqual (ccxt.aggregate (asks.sort ()), [
            [ 123.0, 456.0 ],
            [ 789.0, 123.0 ],
            [ 789.10, 123.0 ],
        ])

        assert.deepEqual (ccxt.aggregate ([]), [])
    })

    it ('deepExtend() works', () => {

        let count = 0;

        const values = [{
            a: 1,
            b: 2,
            d: {
                a: 1,
                b: [],
                c: { test1: 123, test2: 321 }},
            f: 5,
            g: 123,
            i: 321,
            j: [1, 2],
        },
        {
            b: 3,
            c: 5,
            d: {
                b: { first: 'one', second: 'two' },
                c: { test2: 222 }},
            e: { one: 1, two: 2 },
            f: [{ 'foo': 'bar' }],
            g: (void 0),
            h: /abc/g,
            i: null,
            j: [3, 4]
        }]

        const extended = ccxt.deepExtend (...values)
        assert.deepEqual ({
            a: 1,
            b: 3,
            d: {
                a: 1,
                b: { first: 'one', second: 'two' },
                c: { test1: 123, test2: 222 }
            },
            f: [{ 'foo': 'bar' }],
            g: undefined,
            c: 5,
            e: { one: 1, two: 2 },
            h: /abc/g,
            i: null,
            j: [3, 4]
        }, extended)
    })

    it ('groupBy() works', () => {

        const array = [
            { 'foo': 'a' },
            { 'foo': 'b' },
            { 'foo': 'c' },
            { 'foo': 'b' },
            { 'foo': 'c' },
            { 'foo': 'c' },
        ]

        assert.deepEqual (ccxt.groupBy (array, 'foo'), {
            'a': [ { 'foo': 'a' } ],
            'b': [ { 'foo': 'b' }, { 'foo': 'b' } ],
            'c': [ { 'foo': 'c' }, { 'foo': 'c' }, { 'foo': 'c' } ],
        })
    })

    it ('truncate() works', () => {

        assert.equal (ccxt.truncate (0, 0), 0)
        assert.equal (ccxt.truncate (-17.56,   2), -17.56)
        assert.equal (ccxt.truncate ( 17.56,   2),  17.56)
        assert.equal (ccxt.truncate (-17.569,  2), -17.56)
        assert.equal (ccxt.truncate ( 17.569,  2),  17.56)
        assert.equal (ccxt.truncate (49.9999,  4), 49.9999)
        assert.equal (ccxt.truncate (49.99999, 4), 49.9999)
    })

    it ('parseBalance() works', () => {

        const exchange = new ccxt.Exchange ({
            'markets': {
                'ETH/BTC': { 'id': 'ETH/BTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', }
            }
        })

        const input = {
            'ETH': { 'free': 10, 'used': 10, 'total': 20 },
            'ZEC': { 'free': 0, 'used': 0, 'total': 0 },
        }

        const expected = {
            'ETH': { 'free': 10, 'used': 10, 'total': 20 },
            'ZEC': { 'free': 0, 'used': 0, 'total': 0 },
            'free': {
                'ETH': 10,
                'ZEC': 0,
            },
            'used': {
                'ETH': 10,
                'ZEC': 0,
            },
            'total': {
                'ETH': 20,
                'ZEC': 0,
            },
        }

        const actual = exchange.parseBalance (input)

        log ('Actual:', '\t', actual)

        log ('Expected:', '\t', expected)

        assert.deepEqual (actual, expected)
    })
})

/*  ------------------------------------------------------------------------ */
<|endoftext|>


<commit_before>define("DrawEngine", function() {
    function DrawEngine(arenaDisplay, arena) {
        this.arena = arena;
        this.display = arenaDisplay.getContext("2d");

        var size = { width: arenaDisplay.width, height: arenaDisplay.height };
        var lastTime = 0;

        var self = this;

        var update = function (time) {
            if (lastTime === 0) lastTime = time;
            self.display.clearRect(0, 0, size.width, size.height);

            var animationLength = 1000;
            var speed = 10;
            var deltaT = time - lastTime;
            var animationPoint = 0;
            if (self.arena.animatingTurnEnded) {
                animationPoint = time - self.arena.startTime;
                self.arena.animatingTurnEnded = (animationPoint < animationLength);
            }

            for (var i = 0; i < self.arena.players.length; i++) {
                var player = self.arena.players[i].Token;
                if (player.CurrentPosition === undefined) {
                    player.CurrentPosition = player.Position;
                    player.CurrentIndex = 0;
                }

                var currentPosition = player.CurrentPosition;
                var endPoint = player.MovePath[player.CurrentIndex];
                if (endPoint == undefined)
                    endPoint = currentPosition;

                var xDistance = endPoint.X - currentPosition.X;
                var yDistance = endPoint.Y - currentPosition.Y;

                var moveLength = Math.sqrt(xDistance * xDistance + yDistance * yDistance);

                var sin = yDistance / moveLength;
                var cos = xDistance / moveLength;

                currentPosition.X = currentPosition.X + speed * cos;
                currentPosition.Y = currentPosition.Y + speed * sin;

                paintPlayer(currentPosition, player.Size, player.MovePath.slice(player.CurrentIndex));
            }

            last = time;
            requestAnimationFrame(update);
        };

        var paintPlayer = function (position, size, movePath) {
            self.display.fillRect(position.X, position.Y, size.X, size.Y);
            self.display.strokeStyle = "#777";
            self.display.beginPath();
            self.display.moveTo(position.X, position.Y);
            for (var j = 0; j < movePath.length; j++) {
                var pathPoint = movePath[j];
                self.display.lineTo(pathPoint.X, pathPoint.Y);
            }
            self.display.stroke();
        }

        requestAnimationFrame(update);
    }

    return DrawEngine;
});<commit_msg>moving to next point after current one is done<commit_after>define("DrawEngine", function() {
    function DrawEngine(arenaDisplay, arena) {
        this.arena = arena;
        this.display = arenaDisplay.getContext("2d");

        var size = { width: arenaDisplay.width, height: arenaDisplay.height };
        var lastTime = 0;
        var speed = 100;

        var self = this;

        var update = function (time) {
            if (lastTime === 0) lastTime = time;
            self.display.clearRect(0, 0, size.width, size.height);

            var deltaT = time - lastTime;

            for (var i = 0; i < self.arena.players.length; i++) {
                var player = self.arena.players[i].Token;
                if (player.CurrentPosition === undefined) {
                    player.CurrentPosition = player.Position;
                    player.CurrentIndex = 0;
                }

                var endPoint = player.MovePath[player.CurrentIndex];
                if (endPoint == undefined)
                    endPoint = player.CurrentPosition;

                var xDistance = endPoint.X - player.CurrentPosition.X;
                var yDistance = endPoint.Y - player.CurrentPosition.Y;

                var moveLength = Math.sqrt(xDistance * xDistance + yDistance * yDistance);

                var sin = yDistance / moveLength;
                var cos = xDistance / moveLength;

                player.CurrentPosition.X = player.CurrentPosition.X + speed * cos * deltaT / 1000;
                player.CurrentPosition.Y = player.CurrentPosition.Y + speed * sin * deltaT / 1000;

                if (xDistance > 0 && player.CurrentPosition.X > endPoint.X ||
                    xDistance < 0 && player.CurrentPosition.X < endPoint.X ||
                    yDistance > 0 && player.CurrentPosition.Y > endPoint.Y ||
                    yDistance < 0 && player.CurrentPosition.Y < endPoint.Y) {
                    player.CurrentIndex++;
                    player.CurrentPosition.X = endPoint.X;
                    player.CurrentPosition.Y = endPoint.Y;
                }

                paintPlayer(player.CurrentPosition, player.Size, player.MovePath.slice(player.CurrentIndex));
            }

            lastTime = time;
            requestAnimationFrame(update);
        };

        var paintPlayer = function (position, size, movePath) {
            self.display.fillRect(position.X, position.Y, size.X, size.Y);
            self.display.strokeStyle = "#777";
            self.display.beginPath();
            self.display.moveTo(position.X, position.Y);
            for (var j = 0; j < movePath.length; j++) {
                var pathPoint = movePath[j];
                self.display.lineTo(pathPoint.X, pathPoint.Y);
            }
            self.display.stroke();
        }

        requestAnimationFrame(update);
    }

    return DrawEngine;
});<|endoftext|>


<commit_before>/**
 * Copyright 2016 IBM All Rights Reserved.
 *
 * 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.
 */
'use strict';

var utils = require('fabric-client/lib/utils.js');
var logger = utils.getLogger('E2E create-channel');

var tape = require('tape');
var _test = require('tape-promise');
var test = _test(tape);

var Client = require('fabric-client');
var util = require('util');
var fs = require('fs');
var path = require('path');
var grpc = require('grpc');

var _commonProto = grpc.load(path.join(__dirname, '../../../fabric-client/lib/protos/common/common.proto')).common;
var _configtxProto = grpc.load(path.join(__dirname, '../../../fabric-client/lib/protos/common/configtx.proto')).common;

var testUtil = require('../../unit/util.js');
var e2eUtils = require('./e2eUtils.js');

var the_user = null;

var ORGS;

var channel_name = 'mychannel';
// can use "channel=<name>" to control the channel name from command line
if (process.argv.length > 2) {
	if (process.argv[2].indexOf('channel=') === 0) {
		channel_name = process.argv[2].split('=')[1];
	}
}

//
//Attempt to send a request to the orderer with the createChannel method
//
test('\n\n***** SDK Built config update  create flow  *****\n\n', function(t) {
	testUtil.resetDefaults();
	Client.addConfigFile(path.join(__dirname, './config.json'));
	ORGS = Client.getConfigSetting('test-network');

	//
	// Create and configure the test channel
	//
	var client = new Client();

	var caRootsPath = ORGS.orderer.tls_cacerts;
	let data = fs.readFileSync(caRootsPath);
	let caroots = Buffer.from(data).toString();

	var orderer = client.newOrderer(
		ORGS.orderer.url,
		{
			'pem': caroots,
			'ssl-target-name-override': ORGS.orderer['server-hostname']
		}
	);

	var TWO_ORG_MEMBERS_AND_ADMIN = [{
		role: {
			name: 'member',
			mspId: 'Org1MSP'
		}
	}, {
		role: {
			name: 'member',
			mspId: 'Org2MSP'
		}
	}, {
		role: {
			name: 'admin',
			mspId: 'OrdererMSP'
		}
	}];

	var ONE_OF_TWO_ORG_MEMBER = {
		identities: TWO_ORG_MEMBERS_AND_ADMIN,
		policy: {
			'1-of': [{ 'signed-by': 0 }, { 'signed-by': 1 }]
		}
	};

	var ACCEPT_ALL = {
		identities: [],
		policy: {
			'0-of': []
		}
	};

	var config = null;
	var signatures = [];

	// Acting as a client in org1 when creating the channel
	var org = ORGS.org1.name;

	utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js');

	return Client.newDefaultKeyValueStore({
		path: testUtil.storePathForOrg(org)
	}).then((store) => {
		client.setStateStore(store);
		var cryptoSuite = Client.newCryptoSuite();
		cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(org)}));
		client.setCryptoSuite(cryptoSuite);

		return testUtil.getOrderAdminSubmitter(client, t);
	}).then((admin) =>{
		t.pass('Successfully enrolled user \'admin\' for orderer');

		// use the config update created by the configtx tool
		let envelope_bytes = fs.readFileSync(path.join(__dirname, '../../fixtures/channel/mychannel.tx'));
		config = client.extractChannelConfig(envelope_bytes);
		t.pass('Successfull extracted the config update from the configtx envelope');

		client._userContext = null;
		return testUtil.getSubmitter(client, t, true /*get the org admin*/, 'org1');
	}).then((admin) => {
		t.pass('Successfully enrolled user \'admin\' for org1');

		// sign the config
		var signature = client.signChannelConfig(config);
		// convert signature to a storable string
		// fabric-client SDK will convert back during create
		var string_signature = signature.toBuffer().toString('hex');
		t.pass('Successfully signed config update');
		// collect signature from org1 admin
		// TODO: signature counting against policies on the orderer
		// at the moment is being investigated, but it requires this
		// weird double-signature from each org admin
		signatures.push(string_signature);
		signatures.push(string_signature);

		// make sure we do not reuse the user
		client._userContext = null;
		return testUtil.getSubmitter(client, t, true /*get the org admin*/, 'org2');
	}).then((admin) => {
		t.pass('Successfully enrolled user \'admin\' for org2');

		// sign the config
		var signature = client.signChannelConfig(config);
		t.pass('Successfully signed config update');

		// collect signature from org2 admin
		// TODO: signature counting against policies on the orderer
		// at the moment is being investigated, but it requires this
		// weird double-signature from each org admin
		signatures.push(signature);
		signatures.push(signature);

		// make sure we do not reuse the user
		client._userContext = null;
		return testUtil.getOrderAdminSubmitter(client, t);
	}).then((admin) => {
		t.pass('Successfully enrolled user \'admin\' for orderer');
		the_user = admin;

		// sign the config
		var signature = client.signChannelConfig(config);
		t.pass('Successfully signed config update');

		// collect signature from orderer org admin
		// TODO: signature counting against policies on the orderer
		// at the moment is being investigated, but it requires this
		// weird double-signature from each org admin
		signatures.push(signature);
		signatures.push(signature);

		logger.debug('\n***\n done signing \n***\n');

		// build up the create request
		let tx_id = client.newTransactionID();
		var request = {
			config: config,
			signatures : signatures,
			name : channel_name,
			orderer : orderer,
			txId  : tx_id
		};

		// send create request to orderer
		return client.createChannel(request);
	})
	.then((result) => {
		logger.debug('\n***\n completed the create \n***\n');

		logger.debug(' response ::%j',result);
		t.pass('Successfully created the channel.');
		if(result.status && result.status === 'SUCCESS') {
			return e2eUtils.sleep(5000);
		} else {
			t.fail('Failed to create the channel. ');
			t.end();
		}
	}, (err) => {
		t.fail('Failed to create the channel: ' + err.stack ? err.stack : err);
		t.end();
	})
	.then((nothing) => {
		t.pass('Successfully waited to make sure new channel was created.');
		t.end();
	}, (err) => {
		t.fail('Failed to sleep due to error: ' + err.stack ? err.stack : err);
		t.end();
	});
});
<commit_msg>Revert "changed createchannel.js"<commit_after>/**
 * Copyright 2016 IBM All Rights Reserved.
 *
 * 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.
 */
'use strict';

var utils = require('fabric-client/lib/utils.js');
var logger = utils.getLogger('E2E create-channel');

var tape = require('tape');
var _test = require('tape-promise');
var test = _test(tape);

var Client = require('fabric-client');
var util = require('util');
var fs = require('fs');
var path = require('path');
var grpc = require('grpc');

var _commonProto = grpc.load(path.join(__dirname, '../../../fabric-client/lib/protos/common/common.proto')).common;
var _configtxProto = grpc.load(path.join(__dirname, '../../../fabric-client/lib/protos/common/configtx.proto')).common;

var testUtil = require('../../unit/util.js');
var e2eUtils = require('./e2eUtils.js');

var the_user = null;

var ORGS;

var channel_name = 'mychannel';
// can use "channel=<name>" to control the channel name from command line
if (process.argv.length > 2) {
	if (process.argv[2].indexOf('channel=') === 0) {
		channel_name = process.argv[2].split('=')[1];
	}
}

//
//Attempt to send a request to the orderer with the createChannel method
//
test('\n\n***** SDK Built config update  create flow  *****\n\n', function(t) {
	testUtil.resetDefaults();
	Client.addConfigFile(path.join(__dirname, './config.json'));
	ORGS = Client.getConfigSetting('test-network');

	//
	// Create and configure the test channel
	//
	var client = new Client();

	var caRootsPath = ORGS.orderer.tls_cacerts;
	let data = fs.readFileSync(path.join(__dirname, caRootsPath));
	let caroots = Buffer.from(data).toString();

	var orderer = client.newOrderer(
		ORGS.orderer.url,
		{
			'pem': caroots,
			'ssl-target-name-override': ORGS.orderer['server-hostname']
		}
	);

	var TWO_ORG_MEMBERS_AND_ADMIN = [{
		role: {
			name: 'member',
			mspId: 'Org1MSP'
		}
	}, {
		role: {
			name: 'member',
			mspId: 'Org2MSP'
		}
	}, {
		role: {
			name: 'admin',
			mspId: 'OrdererMSP'
		}
	}];

	var ONE_OF_TWO_ORG_MEMBER = {
		identities: TWO_ORG_MEMBERS_AND_ADMIN,
		policy: {
			'1-of': [{ 'signed-by': 0 }, { 'signed-by': 1 }]
		}
	};

	var ACCEPT_ALL = {
		identities: [],
		policy: {
			'0-of': []
		}
	};

	var config = null;
	var signatures = [];

	// Acting as a client in org1 when creating the channel
	var org = ORGS.org1.name;

	utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js');

	return Client.newDefaultKeyValueStore({
		path: testUtil.storePathForOrg(org)
	}).then((store) => {
		client.setStateStore(store);
		var cryptoSuite = Client.newCryptoSuite();
		cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(org)}));
		client.setCryptoSuite(cryptoSuite);

		return testUtil.getOrderAdminSubmitter(client, t);
	}).then((admin) =>{
		t.pass('Successfully enrolled user \'admin\' for orderer');

		// use the config update created by the configtx tool
		let envelope_bytes = fs.readFileSync(path.join(__dirname, '../../fixtures/channel/mychannel.tx'));
		config = client.extractChannelConfig(envelope_bytes);
		t.pass('Successfull extracted the config update from the configtx envelope');

		client._userContext = null;
		return testUtil.getSubmitter(client, t, true /*get the org admin*/, 'org1');
	}).then((admin) => {
		t.pass('Successfully enrolled user \'admin\' for org1');

		// sign the config
		var signature = client.signChannelConfig(config);
		// convert signature to a storable string
		// fabric-client SDK will convert back during create
		var string_signature = signature.toBuffer().toString('hex');
		t.pass('Successfully signed config update');
		// collect signature from org1 admin
		// TODO: signature counting against policies on the orderer
		// at the moment is being investigated, but it requires this
		// weird double-signature from each org admin
		signatures.push(string_signature);
		signatures.push(string_signature);

		// make sure we do not reuse the user
		client._userContext = null;
		return testUtil.getSubmitter(client, t, true /*get the org admin*/, 'org2');
	}).then((admin) => {
		t.pass('Successfully enrolled user \'admin\' for org2');

		// sign the config
		var signature = client.signChannelConfig(config);
		t.pass('Successfully signed config update');

		// collect signature from org2 admin
		// TODO: signature counting against policies on the orderer
		// at the moment is being investigated, but it requires this
		// weird double-signature from each org admin
		signatures.push(signature);
		signatures.push(signature);

		// make sure we do not reuse the user
		client._userContext = null;
		return testUtil.getOrderAdminSubmitter(client, t);
	}).then((admin) => {
		t.pass('Successfully enrolled user \'admin\' for orderer');
		the_user = admin;

		// sign the config
		var signature = client.signChannelConfig(config);
		t.pass('Successfully signed config update');

		// collect signature from orderer org admin
		// TODO: signature counting against policies on the orderer
		// at the moment is being investigated, but it requires this
		// weird double-signature from each org admin
		signatures.push(signature);
		signatures.push(signature);

		logger.debug('\n***\n done signing \n***\n');

		// build up the create request
		let tx_id = client.newTransactionID();
		var request = {
			config: config,
			signatures : signatures,
			name : channel_name,
			orderer : orderer,
			txId  : tx_id
		};

		// send create request to orderer
		return client.createChannel(request);
	})
	.then((result) => {
		logger.debug('\n***\n completed the create \n***\n');

		logger.debug(' response ::%j',result);
		t.pass('Successfully created the channel.');
		if(result.status && result.status === 'SUCCESS') {
			return e2eUtils.sleep(5000);
		} else {
			t.fail('Failed to create the channel. ');
			t.end();
		}
	}, (err) => {
		t.fail('Failed to create the channel: ' + err.stack ? err.stack : err);
		t.end();
	})
	.then((nothing) => {
		t.pass('Successfully waited to make sure new channel was created.');
		t.end();
	}, (err) => {
		t.fail('Failed to sleep due to error: ' + err.stack ? err.stack : err);
		t.end();
	});
});
<|endoftext|>


<commit_before>"use strict";

describe("test", function() {

    it("should be defined", function() {
        expect(window.test).toBeDefined();
    });

    it("should return true when called with test", function() {
        expect(window.test("test")).toEqual(true);
    });

});
<commit_msg>testing...<commit_after>"use strict";

describe("test", function() {

    it("should be defined", function() {
        expect(window.test).toBeDefined();
    });

    it("should return true when called with test ", function() {
        expect(window.test("test")).toEqual(true);
    });

});
<|endoftext|>


<commit_before>const ForecastIo = require('forecastio');
const fs = require('fs');

var forecastIo = new ForecastIo('ce1e9e7c47068378251586a90ecb14cd');
forecastIo.forecast('47.8669', -121.6780).then(function(data) {
  var jsonString = JSON.stringify((data) , null, 2);
  var parsed = JSON.parse(jsonString);
  for (var i = 0; i < 3; i++) {
    var date = new Date(parsed['daily']['data'][i]['time']*1000);
    console.log('Rain Chance for ' + date + ' = ' + parsed['daily']['data'][i]['precipProbability']*100 + ' %');
  }
});
<commit_msg>revise weather.js<commit_after>const ForecastIo = require('forecastio');

var forecastIo = new ForecastIo('ce1e9e7c47068378251586a90ecb14cd');
forecastIo.forecast('47.8669', -121.6780).then(function(data) {
  var jsonString = JSON.stringify((data) , null, 2);
  var parsed = JSON.parse(jsonString);
  for (var i = 0; i < 3; i++) {
    var date = new Date(parsed['daily']['data'][i]['time']*1000);
    console.log('Rain Chance for ' + date + ' = ' + parsed['daily']['data'][i]['precipProbability']*100 + ' %');
  }
});
<|endoftext|>