<commit_before>var es    = require('event-stream'),
	gulp  = require('gulp'),
	mox   = require('./mock-knox'),
	gutil = require('gulp-util');

describe('publisher', function () {
	var publisher,
		gulpS3,
		mockedStream;

	// replace all the required module with either mocked module or
	// the exact same module so that istanbul would not include them in the coverage
	beforeEach(function() {
		mockedStream = es.mapSync( function (file) { return file;});
		gulpS3 = sinon.stub().returns( mockedStream );
		publisher = SandboxedModule.require('../publisher', {
			requires: {
				'gulp-s3': gulpS3,
				'event-stream': es,
				'knox': mox,
				'gulp-util': gutil
			}
		});

	});

	describe ('Parameter', function () {
		it('should throw with null options', function() {
			expect(publisher).to.throw( 'Missing options' );
		});

		it('should throw with empty options', function() {
			expect(function() {
				publisher.app({});
			}).to.throw( 'Missing id' );
		});

		it('should throw with no credentials', function() {
			var options = {
				id: 'some-ID',
				devTag: 'some-tag'
			};
			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing credentials' );
		});

		it('should throw with no key', function() {
			var options = {
				id: 'some-ID',
				creds: {},
				devTag: 'some-tag'
			};
			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing credential key' );
		});

		it('should throw with no secret', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key'
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing credential secret' );
		});

		it('should throw with no devTag', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret'
				}
			};

			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing devTag' );
		});

		it('should throw with no id', function() {
			var options = {
				creds: {
					key: 'some-key',
					secret: 'some-secret'
				},
				devTag: 'some-tag'
			};
			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing id' );
		});

		it ('should not throw even if there is extra info in the creds', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
					useless: 'testetetse'
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.app(options);
			}).to.not.throw();
		});

		it ('should not throw when using app publisher', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.app(options);
			}).to.not.throw();
		});

		it ('should not throw when using library publisher', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.lib(options);
			}).to.not.throw();
		});

		it('should still work with deprecated "appID"', function() {
			var options = {
				appID: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.lib(options);
			}).to.not.throw();
		});
	});

	describe('location', function () {
		it('should return the proper address', function () {
			var options = {
				id: 'some-ID',
				creds: { key: 'some-key', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			expect(publisher.app( options ).location).to.equal('https://s.brightspace.com/apps/some-ID/dev/some-tag/');
		});

		it('should return the proper address for libraries', function () {
			var options = {
				id: 'some-ID',
				creds: { key: 'some-key', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			expect(publisher.lib( options ).location).to.equal('https://s.brightspace.com/libs/some-ID/dev/some-tag/');
		});

		it('should give precedence to "id" rather than "appID"', function() {
			var options = {
				appID: 'wrong-ID',
				id: 'correct-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
				},
				devTag: 'some-tag'
			};

			expect(publisher.app( options ).location).to.equal('https://s.brightspace.com/apps/correct-ID/dev/some-tag/');
		});
	});

	describe('stream', function () {

		it('should pipe files into a s3-amazon bucket with existing contents but not overwrite contents', function (done) {
			var options = {
				id: 'some-ID',
				creds: { key: 'key-a', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			var dataHandler = sinon.spy();
			gulp.src('./test/dist/**')
				.pipe( publisher.app(options) )
				.on('data', dataHandler)
				.on('end', function (err) {

					expect(dataHandler).to.not.be.called;
					done();
				});
		});

		it('should pipe files into an empty s3-amazon bucket successfully', function (done) {
			var options = {
				id: 'some-ID',
				creds: { key: 'some-key', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			var dataHandler = sinon.spy();
			gulp.src('./test/dist/**')
				.pipe( publisher.app(options) )
				.on('data', dataHandler)
				.on('end', function (err) {
					expect(dataHandler).to.be.called;
					done();
				});
		});

		it('should expect an error when give a wrong key', function (done) {
			var options = {
				id: 'some-ID',
				creds: { key: 'wrong-key', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			gulp.src('./test/dist/**')
				.pipe( publisher.app(options) )
				.on('error', function (err) {

					done();
				});

		});
	});

});
<commit_msg>Added new Test and Change test to not use Deprecated code<commit_after>var gulp  = require('gulp'),
	es    = require('event-stream'),
	mox   = require('./mock-knox'),
	gutil = require('gulp-util');

describe('publisher', function () {
	var publisher,
		gulpS3,
		mockedStream;

	// replace all the required module with either mocked module or
	// the exact same module so that istanbul would not include them in the coverage
	beforeEach(function() {
		mockedStream = es.mapSync( function (file) { return file;});
		gulpS3 = sinon.stub().returns( mockedStream );
		publisher = SandboxedModule.require('../publisher', {
			requires: {
				'gulp-s3': gulpS3,
				'event-stream': es,
				'knox': mox,
				'gulp-util': gutil
			}
		});

	});

	describe ('Parameter', function () {
		it('should throw with null options', function() {
			expect(publisher).to.throw( 'Missing options' );
		});

		it('should throw with empty options', function() {
			expect(function() {
				publisher.app({});
			}).to.throw( 'Missing id' );
		});

		it('should throw with no credentials', function() {
			var options = {
				id: 'some-ID',
				devTag: 'some-tag'
			};
			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing credentials' );
		});

		it('should throw with no key', function() {
			var options = {
				id: 'some-ID',
				creds: {},
				devTag: 'some-tag'
			};
			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing credential key' );
		});

		it('should throw with no secret', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key'
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing credential secret' );
		});

		it('should throw with no devTag', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret'
				}
			};

			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing devTag' );
		});

		it('should throw with no id', function() {
			var options = {
				creds: {
					key: 'some-key',
					secret: 'some-secret'
				},
				devTag: 'some-tag'
			};
			expect(function() {
				publisher.app(options);
			}).to.throw( 'Missing id' );
		});

		it ('should not throw even if there is extra info in the creds', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
					useless: 'testetetse'
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.app(options);
			}).to.not.throw();
		});

		it ('should not throw when using app publisher', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.app(options);
			}).to.not.throw();
		});

		it ('should not throw when using library publisher', function() {
			var options = {
				id: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.lib(options);
			}).to.not.throw();
		});

		it('should still work with deprecated "appID"', function() {
			var options = {
				appID: 'some-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
				},
				devTag: 'some-tag'
			};

			expect(function() {
				publisher.lib(options);
			}).to.not.throw();
		});
	});

	describe('location', function () {
		it('should return the proper address', function () {
			var options = {
				id: 'some-ID',
				creds: { key: 'some-key', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			expect(publisher.app( options ).location).to.equal('https://s.brightspace.com/apps/some-ID/dev/some-tag/');
		});

		it('should return the proper address for libraries', function () {
			var options = {
				id: 'some-ID',
				creds: { key: 'some-key', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			expect(publisher.lib( options ).location).to.equal('https://s.brightspace.com/libs/some-ID/dev/some-tag/');
		});

		it('should give precedence to "id" rather than "appID"', function() {
			var options = {
				appID: 'wrong-ID',
				id: 'correct-ID',
				creds: {
					key: 'some-key',
					secret: 'some-secret',
				},
				devTag: 'some-tag'
			};

			expect(publisher.app( options ).location).to.equal('https://s.brightspace.com/apps/correct-ID/dev/some-tag/');
		});
	});

	describe('stream', function () {

		it('should pipe files into a s3-amazon bucket with existing contents but not overwrite contents', function (done) {
			var options = {
				id: 'some-ID',
				creds: { key: 'key-a', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			var dataHandler = sinon.spy();
			gulp.src('./test/dist/**')
				.pipe( publisher.app(options) )
				.on('data', dataHandler)
				.on('end', function (err) {

					expect(dataHandler).to.not.be.called;
					done();
				});
		});

		it('should pipe files into an empty s3-amazon bucket successfully', function (done) {
			var options = {
				id: 'some-ID',
				creds: { key: 'some-key', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			var dataHandler = sinon.spy();
			gulp.src('./test/dist/**')
				.pipe( publisher.app(options) )
				.on('data', dataHandler)
				.on('end', function (err) {
					expect(dataHandler).to.be.called;
					done();
				});
		});

		it('should expect an error when give a wrong key', function (done) {
			var options = {
				id: 'some-ID',
				creds: { key: 'wrong-key', secret: 'some-secret' },
				devTag: 'some-tag'
			};

			gulp.src('./test/dist/**')
				.pipe( publisher.app(options) )
				.on('error', function (err) {

					done();
				});

		});
	});

});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var chai = require('chai');

var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

var expect = require('chai').expect;
var bmq = require('../');

describe('[Role Client]', function() {
  var client;

  beforeEach(function() {
    client = new bmq.Client();
  });

  afterEach(function() {
    client.removeAllListeners();
    client.destroy();
  });

  it('should create `Client` object', function() {
    expect(client.constructor.name).to.eq('Client');
  });

  describe('methods', function() {
    it('should have initialize method', function() {
      expect(client.initialize).to.be.a('function');
    });

    it('should have destroy method', function() {
      expect(client.destroy).to.be.a('function');
    });

    it('should have use method', function() {
      expect(client.use).to.be.a('function');
    });

    it('should have on method', function() {
      expect(client.on).to.be.a('function');
    });

    it('should have send method', function() {
      expect(client.send).to.be.a('function');
    });
  });

  describe('initialize', function() {
    it('should be fulfilled', function() {
      return expect(client.initialize()).to.be.fulfilled;
    });

    it('should have defined default configuration', function() {
      return expect(client.initialize()).to.become({
        approach: bmq.Connection.REQ,
        socket: bmq.Connection.CONNECT,
        address: 'tcp://127.0.0.1:12345'
      });
    });
  });
});

describe('[Role Broker]', function() {
  var broker;

  beforeEach(function() {
    broker = new bmq.Broker();
  });

  afterEach(function() {
    broker.removeAllListeners();
    broker.destroy();
  });

  it('should create `Broker` object', function() {
    expect(broker.constructor.name).to.eq('Broker');
  });

  describe('methods', function() {
    it('should have initialize method', function() {
      expect(broker.initialize).to.be.a('function');
    });

    it('should have destroy method', function() {
      expect(broker.destroy).to.be.a('function');
    });

    it('should have use method', function() {
      expect(broker.use).to.be.a('function');
    });

    it('should have on method', function() {
      expect(broker.on).to.be.a('function');
    });

    it('should have send method', function() {
      expect(broker.send).to.be.a('function');
    });
  });

  describe('initialize ', function() {
    it('should be fulfilled', function() {
      return expect(broker.initialize()).to.be.fulfilled;
    });

    it('should have defined default configuration', function() {
      return expect(broker.initialize()).to.become({
        approach: bmq.Connection.REP,
        socket: bmq.Connection.BIND,
        address: 'tcp://127.0.0.1:12345'
      });
    });
  });
});

describe('[Role Worker]', function() {
  var worker;

  beforeEach(function() {
    worker = new bmq.Worker();
  });

  afterEach(function() {
    worker.removeAllListeners();
    worker.destroy();
  });

  it('should create `Worker` object', function() {
    expect(worker.constructor.name).to.eq('Worker');
  });

  describe('methods', function() {
    it('should have initialize method', function() {
      expect(worker.initialize).to.be.a('function');
    });

    it('should have destroy method', function() {
      expect(worker.destroy).to.be.a('function');
    });

    it('should have use method', function() {
      expect(worker.use).to.be.a('function');
    });

    it('should have on method', function() {
      expect(worker.on).to.be.a('function');
    });

    it('should have send method', function() {
      expect(worker.send).to.be.a('function');
    });
  });

  describe('initialize', function() {
    it('should be fulfilled', function() {
      return expect(worker.initialize()).to.be.fulfilled;
    });

    it('should have defined default configuration', function() {
      return expect(worker.initialize()).to.become({
        approach: bmq.Connection.REQ,
        socket: bmq.Connection.CONNECT,
        address: 'tcp://127.0.0.1:12345'
      });
    });
  });
});
<commit_msg>chore(test): Removed redundant whitespace.<commit_after>'use strict';

/**
 * Module dependencies.
 */
var chai = require('chai');

var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

var expect = require('chai').expect;
var bmq = require('../');

describe('[Role Client]', function() {
  var client;

  beforeEach(function() {
    client = new bmq.Client();
  });

  afterEach(function() {
    client.removeAllListeners();
    client.destroy();
  });

  it('should create `Client` object', function() {
    expect(client.constructor.name).to.eq('Client');
  });

  describe('methods', function() {
    it('should have initialize method', function() {
      expect(client.initialize).to.be.a('function');
    });

    it('should have destroy method', function() {
      expect(client.destroy).to.be.a('function');
    });

    it('should have use method', function() {
      expect(client.use).to.be.a('function');
    });

    it('should have on method', function() {
      expect(client.on).to.be.a('function');
    });

    it('should have send method', function() {
      expect(client.send).to.be.a('function');
    });
  });

  describe('initialize', function() {
    it('should be fulfilled', function() {
      return expect(client.initialize()).to.be.fulfilled;
    });

    it('should have defined default configuration', function() {
      return expect(client.initialize()).to.become({
        approach: bmq.Connection.REQ,
        socket: bmq.Connection.CONNECT,
        address: 'tcp://127.0.0.1:12345'
      });
    });
  });
});

describe('[Role Broker]', function() {
  var broker;

  beforeEach(function() {
    broker = new bmq.Broker();
  });

  afterEach(function() {
    broker.removeAllListeners();
    broker.destroy();
  });

  it('should create `Broker` object', function() {
    expect(broker.constructor.name).to.eq('Broker');
  });

  describe('methods', function() {
    it('should have initialize method', function() {
      expect(broker.initialize).to.be.a('function');
    });

    it('should have destroy method', function() {
      expect(broker.destroy).to.be.a('function');
    });

    it('should have use method', function() {
      expect(broker.use).to.be.a('function');
    });

    it('should have on method', function() {
      expect(broker.on).to.be.a('function');
    });

    it('should have send method', function() {
      expect(broker.send).to.be.a('function');
    });
  });

  describe('initialize', function() {
    it('should be fulfilled', function() {
      return expect(broker.initialize()).to.be.fulfilled;
    });

    it('should have defined default configuration', function() {
      return expect(broker.initialize()).to.become({
        approach: bmq.Connection.REP,
        socket: bmq.Connection.BIND,
        address: 'tcp://127.0.0.1:12345'
      });
    });
  });
});

describe('[Role Worker]', function() {
  var worker;

  beforeEach(function() {
    worker = new bmq.Worker();
  });

  afterEach(function() {
    worker.removeAllListeners();
    worker.destroy();
  });

  it('should create `Worker` object', function() {
    expect(worker.constructor.name).to.eq('Worker');
  });

  describe('methods', function() {
    it('should have initialize method', function() {
      expect(worker.initialize).to.be.a('function');
    });

    it('should have destroy method', function() {
      expect(worker.destroy).to.be.a('function');
    });

    it('should have use method', function() {
      expect(worker.use).to.be.a('function');
    });

    it('should have on method', function() {
      expect(worker.on).to.be.a('function');
    });

    it('should have send method', function() {
      expect(worker.send).to.be.a('function');
    });
  });

  describe('initialize', function() {
    it('should be fulfilled', function() {
      return expect(worker.initialize()).to.be.fulfilled;
    });

    it('should have defined default configuration', function() {
      return expect(worker.initialize()).to.become({
        approach: bmq.Connection.REQ,
        socket: bmq.Connection.CONNECT,
        address: 'tcp://127.0.0.1:12345'
      });
    });
  });
});
<|endoftext|>


<commit_before>// Load in our dependencies
var assert = require('assert');
var mprisUtils = require('./utils/mpris');

// Start our tests
// http://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html
describe('A default MPRIS Root interface', function () {
  mprisUtils.init({name: 'root-default'});

  // TODO: Break down into utilities for simpler asserts -- it's going to get a lot more complex
  //   Initial thoughts
  //   `it('defaults CanQuit to false', mprisUtils.getProperty('CanQuit', function (CanQuit) {})`
  //   `mprisUtils.assertProperty('CanQuit', false);` in place of `it`
  //   `describe('CanQuit', function () { mprisUtils.getProperty('CanQuit'); it('defaults CanQuit')`
  //   `mprisUtils.getProperties(['CanQuit', 'CanRaise']); it(function () { this.CanQuit; });
  //   ^^^ winner
  // http://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:CanQuit
  it('defaults CanQuit to false', function (done) {
    this.mprisSubscriber.GetCanQuit(function handleGetCanQuit (err, CanQuit) {
      if (err) { return done(err); }
      assert.strictEqual(CanQuit, false);
      done();
    });
  });

  // http://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:CanRaise
  it('defaults CanRaise to false', function (done) {
    this.mprisSubscriber.GetCanRaise(function handleGetCanRaise (err, CanRaise) {
      if (err) { return done(err); }
      assert.strictEqual(CanRaise, false);
      done();
    });
  });
});
<commit_msg>Started another test for ourselves<commit_after>// Load in our dependencies
var assert = require('assert');
var mprisUtils = require('./utils/mpris');

// Start our tests
// http://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html
describe('A default MPRIS Root interface', function () {
  mprisUtils.init({name: 'root-default'});

  // TODO: Break down into utilities for simpler asserts -- it's going to get a lot more complex
  //   Initial thoughts
  //   `it('defaults CanQuit to false', mprisUtils.getProperty('CanQuit', function (CanQuit) {})`
  //   `mprisUtils.assertProperty('CanQuit', false);` in place of `it`
  //   `describe('CanQuit', function () { mprisUtils.getProperty('CanQuit'); it('defaults CanQuit')`
  //   `mprisUtils.getProperties(['CanQuit', 'CanRaise']); it(function () { this.CanQuit; });
  //   ^^^ winner
  // http://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:CanQuit
  it('defaults CanQuit to false', function (done) {
    this.mprisSubscriber.GetCanQuit(function handleGetCanQuit (err, CanQuit) {
      if (err) { return done(err); }
      assert.strictEqual(CanQuit, false);
      done();
    });
  });

  // http://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:CanRaise
  it('defaults CanRaise to false', function (done) {
    this.mprisSubscriber.GetCanRaise(function handleGetCanRaise (err, CanRaise) {
      if (err) { return done(err); }
      assert.strictEqual(CanRaise, false);
      done();
    });
  });

  it('hides optional properties', function () {
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var util = require('./source-map/util');

function run(tests) {
  var failures = [];
  var total = 0;
  var passed = 0;

  for (var i = 0; i < tests.length; i++) {
    for (var k in tests[i].testCase) {
      if (/^test/.test(k)) {
        total++;
        try {
          tests[i].testCase[k](assert, util);
          passed++;
          process.stdout.write('.');
        }
        catch (e) {
          failures.push({
            name: tests[i].name + ': ' + k,
            error: e
          });
          process.stdout.write('E');
        }
      }
    }
  }

  process.stdout.write('\n');
  console.log(passed + ' / ' + total + ' tests passed.');

  failures.forEach(function (f) {
    console.log('================================================================================');
    console.log(f.name);
    console.log('--------------------------------------------------------------------------------');
    console.log(f.error.stack);
  });

  return failures.length;
}

var code;

process.stdout.on('close', function () {
  process.exit(code);
});

function isTestFile(f) {
  return /^test\-.*?\.js/.test(f);
}

function toModule(f) {
  return './source-map/' + f.replace(/\.js$/, '');
}

var requires = fs.readdirSync(path.join(__dirname, 'source-map')).filter(isTestFile).map(toModule);

code = run(requires.map(require).map(function (mod, i) {
  return {
    name: requires[i],
    testCase: mod
  };
}));
process.exit(code);
<commit_msg>Extend the test runner so that we can choose to run only a specific test file.<commit_after>#!/usr/bin/env node
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var util = require('./source-map/util');

function run(tests) {
  var failures = [];
  var total = 0;
  var passed = 0;

  for (var i = 0; i < tests.length; i++) {
    for (var k in tests[i].testCase) {
      if (/^test/.test(k)) {
        total++;
        try {
          tests[i].testCase[k](assert, util);
          passed++;
        }
        catch (e) {
          console.log('FAILED ' + tests[i].name + ': ' + k + '!');
          console.log(e.stack);
        }
      }
    }
  }

  console.log("");
  console.log(passed + ' / ' + total + ' tests passed.');
  console.log("");

  failures.forEach(function (f) {
  });

  return failures.length;
}

var code;

process.stdout.on('close', function () {
  process.exit(code);
});

function isTestFile(f) {
  var testToRun = process.argv[2];
  return testToRun
    ? path.basename(testToRun) === f
    : /^test\-.*?\.js/.test(f);
}

function toModule(f) {
  return './source-map/' + f.replace(/\.js$/, '');
}

var requires = fs.readdirSync(path.join(__dirname, 'source-map'))
  .filter(isTestFile)
  .map(toModule);

code = run(requires.map(require).map(function (mod, i) {
  return {
    name: requires[i],
    testCase: mod
  };
}));
process.exit(code);
<|endoftext|>


<commit_before>const {size} = require('../src/lib/mean');
const {expect} = require('chai');

describe('size of collection', function() {
  it('should return length for array-like values', function() {
    expect(size()).to.equal()
  })
})
<commit_msg>fixed test case errors for size<commit_after>const {size} = require('../src/lib/size');
const {expect} = require('chai');

describe('size of collection', function() {
  it('should return length for array-like values', function() {
    expect(size([1,2,3,4])).to.equal(4)
  })
})
<|endoftext|>


<commit_before>module.exports = {
  name: 'basis.l10n',

  html: __dirname + 'l10n.html',  // to properly load .l10n file
  init: function(){
    basis.require('basis.l10n');
    basis.require('basis.ui');
  },

  test: [
    {
      name: 'fallback',
      test: function(){
        var res = JSON.parse(basis.require('./l10n.l10n').resource.get(true));
        var dict = basis.l10n.dictionary('./l10n.l10n');
        basis.l10n.setCulture('en-US');
        assert(dict.token('value').value === 'base');

        basis.l10n.setCultureList('en-US a/b b/c c');

        basis.l10n.setCulture('c');
        assert(dict.token('value').value === 'base');
        basis.l10n.setCulture('b');
        assert(dict.token('value').value === 'base');
        basis.l10n.setCulture('a');
        assert(dict.token('value').value === 'base');

        res.c = { value: 'c' };
        dict.resource.update(JSON.stringify(res));
        basis.l10n.setCulture('c');
        assert(dict.token('value').value === 'c');

        basis.l10n.setCulture('b');
        assert(dict.token('value').value === 'c');
        basis.l10n.setCulture('a');
        assert(dict.token('value').value === 'c');

        res.b = { value: 'b' };
        dict.resource.update(JSON.stringify(res));
        assert(dict.token('value').value === 'b');
        basis.l10n.setCulture('b');
        assert(dict.token('value').value === 'b');
        basis.l10n.setCulture('c');
        assert(dict.token('value').value === 'c');

        res.a = { value: 'a' };
        dict.resource.update(JSON.stringify(res));
        basis.l10n.setCulture('a');
        assert(dict.token('value').value === 'a');
        basis.l10n.setCulture('b');
        assert(dict.token('value').value === 'b');
        basis.l10n.setCulture('c');
        assert(dict.token('value').value === 'c');

        res.b = {
          token: {
            key1: 'a',
            key2: 'b'
          }
        };
        dict.resource.update(JSON.stringify(res));
        basis.l10n.setCulture('a');
        var node = new basis.ui.Node({ template: basis.resource('./l10n.tmpl') });
        node.tmpl.set('key', 'key1');
        assert(node.element.innerText === 'a');
        res.a = {
          token: {
            key1: 'c'
          }
        };
        dict.resource.update(JSON.stringify(res));
        assert(node.element.innerText === 'c');
        node.tmpl.set('key', 'key2');
        assert(node.element.innerText === 'b');
      }
    },
    {
      name: 'dictionary',
      test: function(){
        assert(basis.l10n.dictionary('./l10n.l10n') === basis.l10n.dictionary('./l10n.l10n'));
        assert(basis.l10n.dictionary(basis.resource('./l10n.l10n')) === basis.l10n.dictionary('./l10n.l10n'));

        var staticdata = { 'ru-RU': { test: 'Test' } };
        var dict = basis.l10n.dictionary(staticdata);
        assert(dict instanceof basis.l10n.Dictionary);
        assert(basis.l10n.dictionary(staticdata) !== basis.l10n.dictionary(staticdata));

        //
        basis.l10n.setCultureList('en-US ru-RU');

        basis.l10n.setCulture('en-US');
        assert(dict.token('test').value === undefined);

        basis.l10n.setCulture('ru-RU');
        assert(dict.token('test').value === 'Test');
      }
    },
    {
      name: 'culture/Culture',
      test: function(){
        basis.l10n.setCultureList('en-US ru-RU');

        basis.l10n.setCulture('en-US');
        assert(basis.l10n.getCulture() === 'en-US');
        assert(basis.l10n.culture.value === 'en-US');
        assert(basis.l10n.culture.get() === 'en-US');
        assert(basis.l10n.culture().name === 'en-US');

        basis.l10n.setCulture('ru-RU');
        assert(basis.l10n.getCulture() === 'ru-RU');
        assert(basis.l10n.culture.value === 'ru-RU');
        assert(basis.l10n.culture.get() === 'ru-RU');
        assert(basis.l10n.culture().name === 'ru-RU');

        basis.l10n.culture.set('en-US');
        assert(basis.l10n.getCulture() === 'en-US');
        assert(basis.l10n.culture.value === 'en-US');
        assert(basis.l10n.culture.get() === 'en-US');
        assert(basis.l10n.culture().name === 'en-US');

        // create culture
        assert((new basis.l10n.Culture('en-US')).name === 'en-US');
        assert((new basis.l10n.Culture('en-US')) !== (new basis.l10n.Culture('en-US')));

        // culture helper
        assert(basis.l10n.culture('ru-RU') === basis.l10n.culture('ru-RU'));
        assert(basis.l10n.culture() === basis.l10n.culture(basis.l10n.getCulture()));
        assert(basis.l10n.culture() instanceof basis.l10n.Culture);
      }
    }
  ]
};
<commit_msg>test: clean up l10n test<commit_after>module.exports = {
  name: 'basis.l10n',

  html: __dirname + 'l10n.html',  // to properly load .l10n file
  init: function(){
    basis.require('basis.l10n');
    basis.require('basis.ui');
  },

  test: [
    {
      name: 'fallback',
      test: [
        {
          name: 'basic',
          test: function(){
            var res = JSON.parse(basis.require('./l10n.l10n').resource.get(true));
            var dict = basis.l10n.dictionary('l10n', basis.resource.virtual('l10n', res));
            basis.l10n.setCulture('en-US');
            assert(dict.token('value').value === 'base');

            basis.l10n.setCultureList('en-US a/b b/c c');

            basis.l10n.setCulture('c');
            assert(dict.token('value').value === 'base');
            basis.l10n.setCulture('b');
            assert(dict.token('value').value === 'base');
            basis.l10n.setCulture('a');
            assert(dict.token('value').value === 'base');

            res.c = { value: 'c' };
            dict.resource.update(JSON.stringify(res));
            basis.l10n.setCulture('c');
            assert(dict.token('value').value === 'c');

            basis.l10n.setCulture('b');
            assert(dict.token('value').value === 'c');
            basis.l10n.setCulture('a');
            assert(dict.token('value').value === 'c');

            res.b = { value: 'b' };
            dict.resource.update(JSON.stringify(res));
            assert(dict.token('value').value === 'b');
            basis.l10n.setCulture('b');
            assert(dict.token('value').value === 'b');
            basis.l10n.setCulture('c');
            assert(dict.token('value').value === 'c');

            res.a = { value: 'a' };
            dict.resource.update(JSON.stringify(res));
            basis.l10n.setCulture('a');
            assert(dict.token('value').value === 'a');
            basis.l10n.setCulture('b');
            assert(dict.token('value').value === 'b');
            basis.l10n.setCulture('c');
            assert(dict.token('value').value === 'c');
          }
        },
        {
          name: 'fallback and compute token',
          test: function(){
            basis.l10n.setCultureList('a/b b');

            var dict = basis.l10n.dictionary(basis.resource.virtual('l10n', {
              a: {
                token: {
                  key1: 'a'
                }
              },
              b: {
                token: {
                  key1: 'b1',
                  key2: 'b2'
                }
              }
            }));

            var checkToken = dict.token('token').computeToken();

            // base culture A
            checkToken.set('key1');
            assert(basis.l10n.getCulture() === 'a');
            assert(checkToken.get() === 'a');

            checkToken.set('key2');
            assert(checkToken.get() === 'b2');

            // set culture B
            basis.l10n.setCulture('b');
            assert(basis.l10n.getCulture() === 'b');
            assert(checkToken.get() === 'b2');

            checkToken.set('key1');
            assert(checkToken.get() === 'b1');

            checkToken.set('key2');
            assert(checkToken.get() === 'b2');

            // set culture A
            basis.l10n.setCulture('a');
            assert(basis.l10n.getCulture() === 'a');
            assert(checkToken.get() === 'b2');

            checkToken.set('key1');
            assert(checkToken.get() === 'a');

            checkToken.set('key2');
            assert(checkToken.get() === 'b2');
          }
        }
      ]
    },
    {
      name: 'dictionary',
      test: function(){
        assert(basis.l10n.dictionary('./l10n.l10n') === basis.l10n.dictionary('./l10n.l10n'));
        assert(basis.l10n.dictionary(basis.resource('./l10n.l10n')) === basis.l10n.dictionary('./l10n.l10n'));

        // path should be normalized
        assert(basis.l10n.dictionary('./foo/../l10n.l10n') === basis.l10n.dictionary('./l10n.l10n'));
        // file extension should be replaced for `.l10n`
        assert(basis.l10n.dictionary('./l10n.l10n') === basis.l10n.dictionary('./l10n.whatever'));
        // if no extension, then `.l10n` should be appended
        assert(basis.l10n.dictionary('./l10n.l10n') === basis.l10n.dictionary('./l10n'));
      }
    },
    {
      name: 'dictionary from static data (experimental, under consideration)',
      test: function(){
        var staticdata = { 'ru-RU': { test: 'Test' } };
        var dict = basis.l10n.dictionary(staticdata);
        assert(dict instanceof basis.l10n.Dictionary);

        // static data should produce the same dictionary (under consideration)
        assert(basis.l10n.dictionary(staticdata) !== basis.l10n.dictionary(staticdata));

        // check dictionary
        basis.l10n.setCultureList('en-US ru-RU');

        basis.l10n.setCulture('en-US');
        assert(dict.token('test').value === undefined);

        basis.l10n.setCulture('ru-RU');
        assert(dict.token('test').value === 'Test');
      }
    },
    {
      name: 'culture/Culture',
      test: function(){
        basis.l10n.setCultureList('en-US ru-RU');

        basis.l10n.setCulture('en-US');
        assert(basis.l10n.getCulture() === 'en-US');
        assert(basis.l10n.culture.value === 'en-US');
        assert(basis.l10n.culture.get() === 'en-US');
        assert(basis.l10n.culture().name === 'en-US');

        basis.l10n.setCulture('ru-RU');
        assert(basis.l10n.getCulture() === 'ru-RU');
        assert(basis.l10n.culture.value === 'ru-RU');
        assert(basis.l10n.culture.get() === 'ru-RU');
        assert(basis.l10n.culture().name === 'ru-RU');

        basis.l10n.culture.set('en-US');
        assert(basis.l10n.getCulture() === 'en-US');
        assert(basis.l10n.culture.value === 'en-US');
        assert(basis.l10n.culture.get() === 'en-US');
        assert(basis.l10n.culture().name === 'en-US');

        // create culture
        assert((new basis.l10n.Culture('en-US')).name === 'en-US');
        assert((new basis.l10n.Culture('en-US')) !== (new basis.l10n.Culture('en-US')));

        // culture helper
        assert(basis.l10n.culture('ru-RU') === basis.l10n.culture('ru-RU'));
        assert(basis.l10n.culture() === basis.l10n.culture(basis.l10n.getCulture()));
        assert(basis.l10n.culture() instanceof basis.l10n.Culture);
      }
    }
  ]
};
<|endoftext|>


<commit_before>var sequelize = require('sequelize');<commit_msg>Basic tables defined.<commit_after>var sequelize = require('sequelize');

var Story = sequelize.define('Story', {
});

var Comment = sequelize.define('Comment', {
});

var Job = sequelize.define('Job', {
});

var Poll = sequelize.define('Poll', {
});

var Pollopt = sequelize.define('Pollopt', {
});

var User = sequelize.define('User', {
});<|endoftext|>


<commit_before>var DateTime = (function(Date,Math,undefined){

	var proto = DateTime.prototype;
	/** methods for get set
	 **/
	var MethodNames = [
	'FullYear',     // 0
	'Month',        // 1
	'Date',         // 2
	'Hours',        // 3
	'Minutes',      // 4
	'Seconds',      // 5
	'Milliseconds', // 6
	'Day',          // 7
	'Year',         // 8
	'Time',
	'TimezoneOffset',
	'UTCDate',
	'UTCDay',
	'UTCMonth',
	'UTCFullYear',
	'UTCHours',
	'UTCMinutes',
	'UTCSeconds',
	'UTCMilliseconds'
	]
	var StringMethodNams = [
		'TimeString',
		'GMTString',
		'UTCString',
		'LocaleString',
		'LocaleTimeString',
		'LocaleDateString',
		'DateString'
	]
	var Format = {
		'Year':/y{4}/g,
		'Short_Year':/y{2}/g,
		'Month':/MM/g,
		'Day':/dd/g,
		'Hour':/HH/g,
		'Minute':/mm/g,
		'Second':/ss/g,
		'Millisecond':/ms/g
	}

	function DateTime(){
		return this._init(arguments);
	}

	DateTime.prototype._init = function(args){
		var length = args.length;
		if(length===0){
			this._date = new Date();
		}else if(length === 1){
			if(isNumber(args[0])|| args[0] instanceof Date){
				this._date = new Date(+args[0]);
			}else if(args[0] instanceof DateTime){
				this._date = args[0]._date;
			}else if(isString(args[0])){
				this._date = new Date(args[0]);
			}
		}else if(length === 3){
			var year = args[0];
			var month = args[1];
			var day = args[2];
			this._date = new Date(year,month,day);
		}else if(length === 6){
			var year = args[0];
			var month = args[1];
			var day = args[2];
			var hour = args[3];
			var min = args[4];
			var sec = args[5];
			this._date = new Date(year,month,day,hour,min,sec);
		}
		//cloneMethod();
		return this;
	}

	cloneMethod(MethodNames,function(name){
		proto['get'+ name] = function(){
			return this._date['get' + name]();
		}
		// need clone set method
		proto['set' + name] = function(value){
			return this._date['set'+ name](value);
		}
	});
	cloneMethod(StringMethodNams,function(name){
		proto['to' + name] = function(){
			return this._date['to' + name]();
		}
	})
	/**
	 * DateTime methods
	 **/
	 proto.toString = function(formatter){
	 	if(formatter === undefined){
	 		return this._date.toString();
	 	}
	 	if(Format.Year.test(formatter)){
	 		formatter = formatter.replace(Format.Year,this._date.getUTCFullYear()+"");
	 	}else if(Format.Short_Year.test(formatter)){
	 		formatter = formatter.replace(Format.Short_Year,(this._date.getUTCFullYear()+"").substr(2,2));
	 	}
	 	return formatter.replace(Format.Month,this._date.getUTCMonth()+1)
	 					.replace(Format.Day,this._date.getUTCDate())
	 					.replace(Format.Hour,this._date.getUTCHours())
	 					.replace(Format.Minute,this._date.getUTCMinutes())
	 					.replace(Format.Second,this._date.getUTCSeconds())
	 					.replace(Format.Millisecond,this._date.getUTCMilliseconds());

	 }
	 proto.parse = function(){

	 }
	 proto.addYears = function(delta){
	 	return this;

	 }
	 proto.addMonths = function(delta){
	 	return this;
	 }
	 proto.addDays = function(delta){
	 	return this;
	 }
	 proto.addHours = function(delta){
	 	return this;
	 }
	 proto.addMinutes = function(delta){
	 	return this;
	 }
	 proto.addSeconds = function(delta){
	 	return this;
	 }
	 proto.addMilliseconds = function(delta){
	 	return this;
	 }
	 proto.spanYears = function(dateTime){

	 }
	 proto.spanMonths = function(dateTime){

	 }
	 proto.spanDays = function(dateTime){

	 }
	 proto.spanHours = function(dateTime){

	 }
	 proto.spanMinutes = function(dateTime){

	 }
	 proto.spanSeconds = function(dateTime){

	 }
	 proto.spanMilliseconds = function(dateTime){

	 }
	 proto.compareTo = function(dateTime){

	 }
	 proto.validDate = function(dateTime){
	 	if(typeof dateTime === undefined){
	 		dateTime = this;
	 	}
	 	return !isNaN(+dateTime._date);
	 }
	 proto.getDayInMonth = function(){

	 }
	 /**
	  * static method
	  **/
	 DateTime.today = function(){

	 }
	 DateTime.now = function(){

	 }
	 /*
	 DateTime.UTC = function(year,month,date,hrs,min,sec){

	 }
	 **/
	 DateTime.clone = function(dateTime){

	 }

	/**
	 * clone get and set methods from Date
	 **/
	 function cloneMethod(names,fun){
	 	for(var i =0;i<names.length;i++){
	 		fun(names[i],i);
	 	}
	 }

	function isNumber(arg){
		return typeof arg === 'number';
	}
	function isString(arg){
		return typeof arg === "string";
	}
	return DateTime;
})(Date,Math)<commit_msg>add parse()<commit_after>var DateTime = (function(Date,Math,undefined){

	var proto = DateTime.prototype;
	/** methods for get set
	 **/
	var MethodNames = [
	'FullYear',     // 0
	'Month',        // 1
	'Date',         // 2
	'Hours',        // 3
	'Minutes',      // 4
	'Seconds',      // 5
	'Milliseconds', // 6
	'Day',          // 7
	'Year',         // 8
	'Time',
	'TimezoneOffset',
	'UTCDate',
	'UTCDay',
	'UTCMonth',
	'UTCFullYear',
	'UTCHours',
	'UTCMinutes',
	'UTCSeconds',
	'UTCMilliseconds'
	]
	var StringMethodNams = [
		'TimeString',
		'GMTString',
		'UTCString',
		'LocaleString',
		'LocaleTimeString',
		'LocaleDateString',
		'DateString'
	]
	var Format = {
		'Year':/y{4}/g,
		'Short_Year':/y{2}/g,
		'Month':/MM/g,
		'Day':/dd/g,
		'Hour':/HH/g,
		'Minute':/mm/g,
		'Second':/ss/g,
		'Millisecond':/ms/g
	}

	function DateTime(){
		return this._init(arguments);
	}

	DateTime.prototype._init = function(args){
		var length = args.length;
		if(length===0){
			this._date = new Date();
		}else if(length === 1){
			if(isNumber(args[0])|| args[0] instanceof Date){
				this._date = new Date(+args[0]);
			}else if(args[0] instanceof DateTime){
				this._date = args[0]._date;
			}else if(isString(args[0])){
				this._date = new Date(args[0]);
			}
		}else if(length === 3){
			var year = args[0];
			var month = args[1];
			var day = args[2];
			this._date = new Date(year,month,day);
		}else if(length === 6){
			var year = args[0];
			var month = args[1];
			var day = args[2];
			var hour = args[3];
			var min = args[4];
			var sec = args[5];
			this._date = new Date(year,month,day,hour,min,sec);
		}
		//cloneMethod();
		return this;
	}

	cloneMethod(MethodNames,function(name){
		proto['get'+ name] = function(){
			return this._date['get' + name]();
		}
		// need clone set method
		proto['set' + name] = function(value){
			return this._date['set'+ name](value);
		}
	});
	cloneMethod(StringMethodNams,function(name){
		proto['to' + name] = function(){
			return this._date['to' + name]();
		}
	})
	/**
	 * DateTime methods
	 **/
	 proto.toString = function(formatter){
	 	if(formatter === undefined){
	 		return this._date.toString();
	 	}
	 	if(Format.Year.test(formatter)){
	 		formatter = formatter.replace(Format.Year,this._date.getUTCFullYear()+"");
	 	}else if(Format.Short_Year.test(formatter)){
	 		formatter = formatter.replace(Format.Short_Year,(this._date.getUTCFullYear()+"").substr(2,2));
	 	}
	 	var monstr = "";
	 	if(this._date.getUTCMonth() + 1< 10){
	 		monstr = "0" + (this._date.getUTCMonth() + 1);
	 	}else{
	 		monstr = '' + this._date.getUtcDate();
	 	}
	 	var daystr = '' + this._date.getUtcDate();
	 	if(this._date.getUTCDate() < 10){
	 		daystr = '0' + daystr;
	 	}
	 	var hourstr = '';
	 	if(this._date.getUTCHours()<10){
	 		hourstr = '0' + this._date.getUTCHours();
	 	}else{
	 		hourstr = "" + this._date.getUTCHours();
	 	}
	 	var minstr = '' + this._date.getUTCMinutes();
	 	if(this._date.getUTCMinutes < 10){
	 		minstr = '0' + minstr;
	 	}
	 	var seconstr = '' + this._date.getUTCSeconds();
	 	if(this._date.getUTCSeconds()<10){
	 		seconstr = '0' + seconstr;
	 	}
	 	var milistr = '' + this._date.getUTCMilliseconds();
	 	if(this._date.getUTCMilliseconds<10){
	 		milistr = '0' + milistr;
	 	}
	 	return formatter.replace(Format.Month,monstr)
	 					.replace(Format.Day,daystr)
	 					.replace(Format.Hour,hourstr)
	 					.replace(Format.Minute,minstr)
	 					.replace(Format.Second,seconstr)
	 					.replace(Format.Millisecond,milistr);

	 }
	 proto.parse = function(datestr,formatter){
	 	if(typeof formatter === undefined){
	 		var tdate = new Date(datestr*1);
	 		return new DateTime(tdate);
	 	}
	 	var year,month,day,hour,minute,second,millisecond;
	 	var result;
	 	if((result = Format.Year.exec(formatter)) !== null){
	 		year = datestr.substr(result.index,result[0].length)*1;
	 	}else if ((result = Format.Short_Year.exec(formatter)) !== null) {
	 		year = datestr.substr(result.index,result[0].length)*1 +2000;
	 	}else{
	 		return null;
	 	}

	 	if ((result = Format.Month.exec(formatter)) !== null) {
	 		month = datestr.substr(result.index,result[0].length)*1;
	 	}else{
	 		return null;
	 	}

	 	if ((result = Format.Day.exec(formatter)) !== null){
	 		day = datestr.substr(result.index,result[0].length)*1;
	 	} else{
	 		return null;
	 	}
	 	if ((result = Format.Hour.exec(formatter)) !== null){
	 		hour = datestr.substr(result.index,result[0].length)*1;
	 	} else{
	 		hour = 0;
	 	}

	 	if ((result = Format.Minute.exec(formatter)) !== null){
	 		minute = datestr.substr(result.index,result[0].length)*1;
	 	} else{
	 		minute = 0;
	 	}

	 	if ((result = Format.Second.exec(formatter)) !== null){
	 		second = datestr.substr(result.index,result[0].length)*1;
	 	} else{
	 		second = 0;
	 	}

	 	return new DateTime(year,month,day,hour,minute,second);

	 }
	 proto.addYears = function(delta){
	 	return this;

	 }
	 proto.addMonths = function(delta){
	 	return this;
	 }
	 proto.addDays = function(delta){
	 	return this;
	 }
	 proto.addHours = function(delta){
	 	return this;
	 }
	 proto.addMinutes = function(delta){
	 	return this;
	 }
	 proto.addSeconds = function(delta){
	 	return this;
	 }
	 proto.addMilliseconds = function(delta){
	 	return this;
	 }
	 proto.spanYears = function(dateTime){

	 }
	 proto.spanMonths = function(dateTime){

	 }
	 proto.spanDays = function(dateTime){

	 }
	 proto.spanHours = function(dateTime){

	 }
	 proto.spanMinutes = function(dateTime){

	 }
	 proto.spanSeconds = function(dateTime){

	 }
	 proto.spanMilliseconds = function(dateTime){

	 }
	 proto.compareTo = function(dateTime){

	 }
	 proto.validDate = function(dateTime){
	 	if(typeof dateTime === undefined){
	 		dateTime = this;
	 	}
	 	return !isNaN(+dateTime._date);
	 }
	 proto.getDayInMonth = function(){

	 }
	 /**
	  * static method
	  **/
	 DateTime.today = function(){

	 }
	 DateTime.now = function(){

	 }
	 /*
	 DateTime.UTC = function(year,month,date,hrs,min,sec){

	 }
	 **/
	 DateTime.clone = function(dateTime){

	 }

	/**
	 * clone get and set methods from Date
	 **/
	 function cloneMethod(names,fun){
	 	for(var i =0;i<names.length;i++){
	 		fun(names[i],i);
	 	}
	 }

	function isNumber(arg){
		return typeof arg === 'number';
	}
	function isString(arg){
		return typeof arg === "string";
	}
	return DateTime;
})(Date,Math)<|endoftext|>


<commit_before>var mongoose = require("mongoose");
var Anime   = require('../models/anime');

// Database
var config = require('../config/config');
mongoose.connect(config.database);

Anime.create({"_id": "20", title: "test", comments: []})

console.log("done")<commit_msg>missing semicolons<commit_after>var mongoose = require("mongoose");
var Anime   = require('../models/anime');

// Database
var config = require('../config/config');
mongoose.connect(config.database);

Anime.create({"_id": "20", title: "test", comments: []});

console.log("done");
<|endoftext|>


<commit_before>define(function(require) {
    'use strict';
    var Fruit = require('./Fruit.js');
    var Utility = require('./../Helper/Utility.js');

    var fruits = [ // Fruit - points
        {
            type: 'orange',
            points: 20
        }, {
            type: 'apple',
            points: 30
        }, {
            type: 'watermelon',
            points: 30
        }
        //            ['orange', 20],
        //            ['apple', 30],
        //            [ /* ... */ ]
    ];

    function getRandomFruit(coordinateBoundaries) {
        var utility = new Utility(),
            randomFruit = fruits[utility.getRandomNumber(0, fruits.length)],
            fruitType = randomFruit.type,
            fruitPoints = randomFruit.points,
            fruitDefaultImage = fruitType + '.png',
            fruitHitImage = fruitType + '-hit.png';

        // ...
        var randomCoordinates = utility.getRandomCoords(coordinateBoundaries),
            randomDirectory = utility.getRandomDirection(randomCoordinates, coordinateBoundaries);

        // ...

        return new Fruit(randomCoordinates.x, randomCoordinates.y, fruitDefaultImage, fruitHitImage, fruitPoints);
    }

    return {
        getRandomFruit: getRandomFruit
    };
});<commit_msg>Fixed wrong var name from randomDirectory to randomDirection<commit_after>define(function (require) {
    'use strict';
    var Fruit = require('./Fruit.js');
    var Utility = require('./../Helper/Utility.js');

    var fruits = [ // Fruit - points
        {
            type: 'orange',
            points: 20
        }, {
            type: 'apple',
            points: 30
        }, {
            type: 'watermelon',
            points: 30
        }
        //            ['orange', 20],
        //            ['apple', 30],
        //            [ /* ... */ ]
    ];

    function getRandomFruit(coordinateBoundaries) {
        var utility = new Utility(),
            randomFruit = fruits[utility.getRandomNumber(0, fruits.length)],
            fruitType = randomFruit.type,
            fruitPoints = randomFruit.points,
            fruitDefaultImage = fruitType + '.png',
            fruitHitImage = fruitType + '-hit.png';

        // ...
        var randomCoordinates = utility.getRandomCoords(coordinateBoundaries),
            randomDirection = utility.getRandomDirection(randomCoordinates, coordinateBoundaries);

        // ...

        return new Fruit(randomCoordinates.x, randomCoordinates.y, fruitDefaultImage, fruitHitImage, fruitPoints);
    }

    return {
        getRandomFruit: getRandomFruit
    };
});<|endoftext|>


<commit_before>import {PropTypes, Component} from 'react';

class Provider extends Component {

  getChildContext() {
    return {
      store: this.props.store
    };
  }

  render() {
    return this.props.children;
  }

}

Provider.childContextTypes = {
  store: PropTypes.object
};

export default Provider;
<commit_msg>add propTypes to Provider<commit_after>import {PropTypes, Component} from 'react';

class Provider extends Component {

  getChildContext() {
    return {
      store: this.props.store
    };
  }

  render() {
    return this.props.children;
  }

}

Provider.propTypes = {
  store: PropTypes.object.isRequired
}

Provider.childContextTypes = {
  store: PropTypes.object
};

export default Provider;
<|endoftext|>


<commit_before>'use strict';

/* Attribution: Cities Weather data provided by OpenWeatherMap API (http://openweathermap.org)
   under Creative Commons Share A Like License (https://creativecommons.org/licenses/by-sa/4.0)
   Changes were made to the original data to work with json-server.
   This does not imply an endorsement by the licensor.

	 This code is distributed under Creative Commons Share A Like License.
*/

var expect = require('chai').expect;
var jq = require('node-jq');
var unirest = require('unirest');
var _ = require('underscore');

describe('cities-jq', function() {
  var req;

  beforeEach(function() {
    req = unirest.get('http://localhost:5000/cities')
      .header('Accept', 'application/json');
  });

  it('should return a 200 response', function(done) {
    req.end(function(res) {
      expect(res.statusCode).to.eql(200);
      expect(res.headers['content-type']).to.eql(
        'application/json; charset=utf-8');
      done();
    });
  });

  it('should return all cities', function(done) {
    req.end(function(res) {
      var cities = res.body;

      //console.log(cities);
      expect(cities.length).to.eql(110);
      done();
    });
  });

  it('should return the last city', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run('.[-1]', cities, {
          input: 'json'
        })
        .then(function(lastCityJson) { // Returns JSON String.
          //console.log(lastCityJson);
          var lastCity = JSON.parse(lastCityJson);
          expect(lastCity.name).to.eql('Moreno Valley');
          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  it('should return the 1st 3 cities', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run('.[:3]', cities, {
          input: 'json'
        })
        .then(function(citiesFirstThreeJson) { // Returns JSON String.
          //console.log(citiesFirstThreeJson);
          var citiesFirstThree = JSON.parse(citiesFirstThreeJson);
          var citiesFirstThreeNames = getCityNamesOnly(
            citiesFirstThree);

          //console.log(citiesFirstThree);
          //console.log(citiesFirstThreeNames);
          expect(citiesFirstThree.length).to.eql(3);
          expect(citiesFirstThreeNames.length).to.eql(3);
          expect(citiesFirstThreeNames).to.eql([
            'Rancho Palos Verdes',
            'San Pedro', 'Rosarito'
          ]);

          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  function getCityNamesOnly(cities) {
    return _.map(cities,
      function(city) {
        return city.name;
      });
  }

  it('should return cities within a temperature range', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run(
          '[.[] | select (.main.temp >= 84 and .main.temp <= 85.5)]',
          cities, {
            input: 'json'
          })
        .then(function(citiesTempRangeJson) { // Returns JSON String.
          //console.log(citiesTempRangeJson);
          var citiesTempRange = JSON.parse(citiesTempRangeJson);

          //console.log(citiesTempRange);
          for (var i = 0; i < citiesTempRange.length; i++) {
            expect(citiesTempRange[i].main.temp).to.be.at.least(
              84);
            expect(citiesTempRange[i].main.temp).to.be.at.most(
              85.5);
          }

          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  it('should return cities with cloudy weather', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run(
          '[.[] | select(.weather[0].main == "Clouds")]',
          cities, {
            input: 'json'
          })
        .then(function(citiesWeatherCloudyJson) { // Returns JSON String.
          //console.log(citiesWeatherCloudyJson);
          var citiesWeatherCloudy = JSON.parse(
            citiesWeatherCloudyJson);

          //console.log(citiesWeatherCloudy);
          checkCitiesWeather(citiesWeatherCloudy);

          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  it('should return cities with cloudy weather using regex', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run(
          '[.[] | select(.weather[0].main | test("^Clo"; "i"))]',
          cities, {
            input: 'json'
          })
        .then(function(citiesWeatherCloudyJson) { // Returns JSON String.
          //console.log(citiesWeatherCloudyJson);
          var citiesWeatherCloudy = JSON.parse(
            citiesWeatherCloudyJson);

          //console.log(citiesWeatherCloudy);
          checkCitiesWeather(citiesWeatherCloudy);

          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  function checkCitiesWeather(cities) {
    //console.log(cities);
    for (var i = 0; i < cities.length; i++) {
      expect(cities[i].weather[0].main).to.eql('Clouds');
    }
  }

});
<commit_msg>Removed a blank line.<commit_after>'use strict';

/* Attribution: Cities Weather data provided by OpenWeatherMap API (http://openweathermap.org)
   under Creative Commons Share A Like License (https://creativecommons.org/licenses/by-sa/4.0)
   Changes were made to the original data to work with json-server.
   This does not imply an endorsement by the licensor.

	 This code is distributed under Creative Commons Share A Like License.
*/

var expect = require('chai').expect;
var jq = require('node-jq');
var unirest = require('unirest');
var _ = require('underscore');

describe('cities-jq', function() {
  var req;

  beforeEach(function() {
    req = unirest.get('http://localhost:5000/cities')
      .header('Accept', 'application/json');
  });

  it('should return a 200 response', function(done) {
    req.end(function(res) {
      expect(res.statusCode).to.eql(200);
      expect(res.headers['content-type']).to.eql(
        'application/json; charset=utf-8');
      done();
    });
  });

  it('should return all cities', function(done) {
    req.end(function(res) {
      var cities = res.body;

      //console.log(cities);
      expect(cities.length).to.eql(110);
      done();
    });
  });

  it('should return the last city', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run('.[-1]', cities, {
          input: 'json'
        })
        .then(function(lastCityJson) { // Returns JSON String.
          //console.log(lastCityJson);
          var lastCity = JSON.parse(lastCityJson);
          expect(lastCity.name).to.eql('Moreno Valley');
          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  it('should return the 1st 3 cities', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run('.[:3]', cities, {
          input: 'json'
        })
        .then(function(citiesFirstThreeJson) { // Returns JSON String.
          //console.log(citiesFirstThreeJson);
          var citiesFirstThree = JSON.parse(citiesFirstThreeJson);
          var citiesFirstThreeNames = getCityNamesOnly(
            citiesFirstThree);

          //console.log(citiesFirstThree);
          //console.log(citiesFirstThreeNames);
          expect(citiesFirstThree.length).to.eql(3);
          expect(citiesFirstThreeNames.length).to.eql(3);
          expect(citiesFirstThreeNames).to.eql([
            'Rancho Palos Verdes',
            'San Pedro', 'Rosarito'
          ]);

          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  function getCityNamesOnly(cities) {
    return _.map(cities,
      function(city) {
        return city.name;
      });
  }

  it('should return cities within a temperature range', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run(
          '[.[] | select (.main.temp >= 84 and .main.temp <= 85.5)]',
          cities, {
            input: 'json'
          })
        .then(function(citiesTempRangeJson) { // Returns JSON String.
          //console.log(citiesTempRangeJson);
          var citiesTempRange = JSON.parse(citiesTempRangeJson);

          //console.log(citiesTempRange);
          for (var i = 0; i < citiesTempRange.length; i++) {
            expect(citiesTempRange[i].main.temp).to.be.at.least(
              84);
            expect(citiesTempRange[i].main.temp).to.be.at.most(
              85.5);
          }

          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  it('should return cities with cloudy weather', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run(
          '[.[] | select(.weather[0].main == "Clouds")]',
          cities, {
            input: 'json'
          })
        .then(function(citiesWeatherCloudyJson) { // Returns JSON String.
          //console.log(citiesWeatherCloudyJson);
          var citiesWeatherCloudy = JSON.parse(
            citiesWeatherCloudyJson);

          //console.log(citiesWeatherCloudy);
          checkCitiesWeather(citiesWeatherCloudy);

          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  it('should return cities with cloudy weather using regex', function(done) {
    req.end(function(res) {
      var cities = res.body;

      jq.run(
          '[.[] | select(.weather[0].main | test("^Clo"; "i"))]',
          cities, {
            input: 'json'
          })
        .then(function(citiesWeatherCloudyJson) { // Returns JSON String.
          //console.log(citiesWeatherCloudyJson);
          var citiesWeatherCloudy = JSON.parse(
            citiesWeatherCloudyJson);

          //console.log(citiesWeatherCloudy);
          checkCitiesWeather(citiesWeatherCloudy);

          done();
        })
        .catch(function(error) {
          console.error(error);
          done(error);
        });
    });
  });

  function checkCitiesWeather(cities) {
    //console.log(cities);
    for (var i = 0; i < cities.length; i++) {
      expect(cities[i].weather[0].main).to.eql('Clouds');
    }
  }

});
<|endoftext|>


<commit_before>let state, authService;

class HeaderController {

    constructor ($state, AuthService) {
        state = $state;
        authService = AuthService;
    }

    getLoginName () {
        return authService.getLoginName();
    }

    isAdmin () {
        return authService.isAdmin();
    }

    isEmployee () {
        return authService.isEmployee();
    }

    isLogged () {
        return authService.isLogged();
    }

    isUser () {
        return authService.isUser();
    }

    logout () {
        authService.logout();
        state.go('login');
    }

}

HeaderController.$inject = ['$state', 'AuthService'];

export default HeaderController;
<commit_msg>Changed auth service name.<commit_after>let state, authService;

class HeaderController {

    constructor ($state, Auth) {
        state = $state;
        authService = Auth;

    }

    getLoginName () {
        return authService.getLoginName();
    }

    isAdmin () {
        return authService.isAdmin();
    }

    isEmployee () {
        return authService.isEmployee();
    }

    isLogged () {
        return authService.isLogged();
    }

    isUser () {
        return authService.isUser();
    }

    logout () {
        authService.logout();
        state.go('login');
    }

}

HeaderController.$inject = ['$state', 'AuthService'];

export default HeaderController;
<|endoftext|>


<commit_before>angular.module('app.leagues.new', ['new.event.create'])
.factory('League', function($http){
  return {
    postLeague: function(league, callback) {
      $http.post('/league', league)
        .success(function(league){
          console.log('successfully posted new league');
          // get league id from league
          callback(false, league);
        })
        .error(function(err){
          console.log(err);
          callback(true, err);
        });
    },
    getLeagueId: function() {
      return league.league_id;
    }
  };

})
.controller('newLeagueController', function ($scope) { //
  $scope.step = 1;
  $scope.league = {};
  $scope.character = {};
  $scope.characters = [];

  $scope.nextStep = function(step) {
    $scope.step = step;
  };
  $scope.setLeague = function(league){
    $scope.league = league;
  };
  $scope.setCharacter = function(character){
    $scope.character = character;
  };
  $scope.appendCharacters = function(character){
    $scope.characters.push(character);
  };
  $scope.checkIfCharacters = function(){
    if ($scope.characters.length) {
      $scope.nextStep(3);
    }
  };
})

.controller('createLeagueCtrl', function ($scope, League) {

  $scope.league = {};
  $scope.saveLeagueInfo = function() {

    League.postLeague($scope.league, function(err, newLeague) {
      if (newLeague) {
        $scope.nextStep(2);
        $scope.setLeague(newLeague);
      }
    });
  };
})

/*
'setCharactersCtrl' - manages characters addition, display and deletion
- currently used on leage creation step2
*/
.controller('setCharactersCtrl', function ($scope, Character) {
  //get league.id from scope
  $scope.character = {};
  $scope.addCharacter = function(){
    Character.saveCharacter($scope.league.id,function(err, character){
      if(character) {
        $scope.setCharacter(character);
        $scope.appendCharacters(character);
        $scope.character = {};
      }
    });
  };
})

.controller('scoreSettingCtrl', function ($scope) {
})

.controller('inviteFriendsCtrl', function ($scope, invite) {
  $scope.invitedUsers = invite.getInvitedUsers();
  $scope.inviteUser = function() {
    invite.inviteUser($scope.league.id, $scope.username);
    $scope.username = "";
  }
})

.factory('invite', function() {
  //should be an empty array once route works
  var invitedUsers = [{username:"richie"}, {username:"antonio"}];

  var inviteUser = function(leagueId, username) {
    //uncomment this when route is working
    // $http({
    //   method: 'POST',
    //   url: '/league/'+leagueId+'/invite'
    // })
    //   .success(function(invitedUser) {
    //     invitedUsers.push(invitedUser);
    //   })
    //delete when route is working
    invitedUsers.push({username: username});
  }

  var getInvitedUsers = function() {
    return invitedUsers;
  }

  return {
    inviteUser: inviteUser,
    getInvitedUsers: getInvitedUsers
  }
})

.factory('Character', function($http) {
  var saveCharacter = function(leagueId, callback){
    $http({
      method: 'POST',
      url: '/league/'+leagueId+'/characters',
    })
    .success(function(character){
      console.log('created a character' , character);
      callback(false, character);
    })
    .error(function(err){
      console.log(err);
      callback(true, err);
    });
  };

  return {
    saveCharacter: saveCharacter
  };
})<commit_msg>[refactor] fixed merge conflict in newLeagueController.js<commit_after>angular.module('app.leagues.new', ['new.event.create'])
.factory('League', function($http){
  return {
    postLeague: function(league, callback) {
      $http.post('/league', league)
        .success(function(league){
          console.log('successfully posted new league');
          // get league id from league
          callback(false, league);
        })
        .error(function(err){
          console.log(err);
          callback(true, err);
        });
    },
    getLeagueId: function() {
      return league.league_id;
    }
  };

})
.controller('newLeagueController', function ($scope) { //
  $scope.step = 1;
  $scope.league = {};
  $scope.character = {};
  $scope.characters = [];

  $scope.nextStep = function(step) {
    $scope.step = step;
  };
  $scope.setLeague = function(league){
    $scope.league = league;
  };
  $scope.setCharacter = function(character){
    $scope.character = character;
  };
  $scope.appendCharacters = function(character){
    $scope.characters.push(character);
  };
  $scope.checkIfCharacters = function(){
    if ($scope.characters.length) {
      $scope.nextStep(3);
    }
  };
})

.controller('createLeagueCtrl', function ($scope, League) {

  $scope.league = {};
  $scope.saveLeagueInfo = function() {

    League.postLeague($scope.league, function(err, newLeague) {
      if (newLeague) {
        $scope.nextStep(2);
        $scope.setLeague(newLeague);
      }
    });
  };
})

/*
'setCharactersCtrl' - manages characters addition, display and deletion
- currently used on leage creation step2
*/
.controller('setCharactersCtrl', function ($scope, Character) {
  //get league.id from scope
  $scope.character = {};
  $scope.addCharacter = function(){
    Character.saveCharacter($scope.league.id,function(err, character){
      if(character) {
        $scope.setCharacter(character);
        $scope.appendCharacters(character);
        $scope.character = {};
      }
    });
  };
})

.controller('scoreSettingCtrl', function ($scope) {
})

.controller('inviteFriendsCtrl', function ($scope, invite) {
  $scope.invitedUsers = invite.getInvitedUsers();

  $scope.inviteUser = function() {
    invite.inviteUser($scope.league.id, $scope.username);
    $scope.username = "";
  }
})

.factory('invite', function($http) {
  //should be an empty array once route works
  var invitedUsers = [{username:"richie"}, {username:"antonio"}];

  var inviteUser = function(leagueId, username) {

    $http.post('/league/' + leagueId + '/invite', {'username': username})
      .success(function(invitedUser){
        invitedUsers.push(invitedUser);
      })
      .error(function(err){
        console.log('error:', err);
      });
  }

  var getInvitedUsers = function() {
    return invitedUsers;
  }

  return {
    inviteUser: inviteUser,
    getInvitedUsers: getInvitedUsers
  }
})

.factory('Character', function($http) {
  var saveCharacter = function(leagueId, callback){
    $http({
      method: 'POST',
      url: '/league/'+leagueId+'/characters',
    })
    .success(function(character){
      console.log('created a character' , character);
      callback(false, character);
    })
    .error(function(err){
      console.log(err);
      callback(true, err);
    });
  };

  return {
    saveCharacter: saveCharacter
  };
})<|endoftext|>


<commit_before>'use strict';
import { _ } from 'meteor/underscore';
import { $ } from 'meteor/jquery';
import { Meteor } from 'meteor/meteor';
import { DocHead } from 'meteor/kadira:dochead';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { dbCompanyArchive } from '/db/dbCompanyArchive';
import { dbLog } from '/db/dbLog';
import { inheritedShowLoadingOnSubscribing } from '../layout/loading';
import { shouldStopSubscribe } from '../utils/idle';
import { investArchiveCompany } from '../utils/methods';
const rShowAllTags = new ReactiveVar(false);

inheritedShowLoadingOnSubscribing(Template.companyArchiveDetail);
Template.companyArchiveDetail.onCreated(function() {
  rShowAllTags.set(false);
  this.autorun(() => {
    const companyId = FlowRouter.getParam('companyId');
    if (companyId) {
      const companyArchiveData = dbCompanyArchive.findOne(companyId);
      if (companyArchiveData) {
        DocHead.setTitle(Meteor.settings.public.websiteName + ' - 「' + companyArchiveData.name + '」保管庫公司資訊');
      }
    }
  });
  this.autorun(() => {
    if (shouldStopSubscribe()) {
      return false;
    }
    const companyId = FlowRouter.getParam('companyId');
    if (companyId) {
      this.subscribe('companyArchiveDetail', companyId);
    }
  });
});
Template.companyArchiveDetail.helpers({
  companyArchiveData() {
    const companyId = FlowRouter.getParam('companyId');

    return dbCompanyArchive.findOne(companyId);
  },
  showAllTags(tags) {
    if (tags.length <= 4) {
      return true;
    }

    return rShowAllTags.get();
  },
  firstFewTags(tags) {
    return tags.slice(0, 3);
  }
});
Template.companyArchiveDetail.events({
  'click [data-action="invest"]'(event) {
    event.preventDefault();
    investArchiveCompany(this);
  },
  'click [data-action="showAllTags"]'(event) {
    event.preventDefault();
    rShowAllTags.set(true);
  }
});

//是否展開面板
const rDisplayPanelList = new ReactiveVar([]);
Template.companyArchiveDetailTable.helpers({
  isDisplayPanel(panelType) {
    return _.contains(rDisplayPanelList.get(), panelType);
  },
  archiveReviveNeedUsers() {
    return Meteor.settings.public.archiveReviveNeedUsers;
  }
});
Template.companyArchiveDetailTable.events({
  'click [data-toggle-panel]'(event) {
    event.preventDefault();
    const $emitter = $(event.currentTarget);
    const panelType = $emitter.attr('data-toggle-panel');
    const displayPanelList = rDisplayPanelList.get();
    if (_.contains(displayPanelList, panelType)) {
      rDisplayPanelList.set(_.without(displayPanelList, panelType));
    }
    else {
      displayPanelList.push(panelType);
      rDisplayPanelList.set(displayPanelList);
    }
  }
});

const rLogOffset = new ReactiveVar(0);
inheritedShowLoadingOnSubscribing(Template.companyArchiveLogList);
Template.companyArchiveLogList.onCreated(function() {
  rLogOffset.set(0);
  this.autorun(() => {
    if (shouldStopSubscribe()) {
      return false;
    }
    const companyId = FlowRouter.getParam('companyId');
    if (companyId) {
      this.subscribe('companyLog', companyId, false, rLogOffset.get());
    }
  });
});
Template.companyArchiveLogList.helpers({
  logList() {
    const companyId = FlowRouter.getParam('companyId');

    return dbLog.find({companyId}, {
      sort: {
        createdAt: -1
      },
      limit: 30
    });
  },
  paginationData() {
    return {
      useVariableForTotalCount: 'totalCountOfcompanyLog',
      dataNumberPerPage: 30,
      offset: rLogOffset
    };
  }
});
<commit_msg>進入一家已進入新創或已上市的保管庫公司細節頁面時，將會自動導覽至適當的頁面。<commit_after>'use strict';
import { _ } from 'meteor/underscore';
import { $ } from 'meteor/jquery';
import { Meteor } from 'meteor/meteor';
import { DocHead } from 'meteor/kadira:dochead';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { dbCompanyArchive } from '/db/dbCompanyArchive';
import { dbLog } from '/db/dbLog';
import { inheritedShowLoadingOnSubscribing } from '../layout/loading';
import { shouldStopSubscribe } from '../utils/idle';
import { investArchiveCompany } from '../utils/methods';
const rShowAllTags = new ReactiveVar(false);

inheritedShowLoadingOnSubscribing(Template.companyArchiveDetail);
Template.companyArchiveDetail.onCreated(function() {
  rShowAllTags.set(false);
  this.autorun(() => {
    const companyId = FlowRouter.getParam('companyId');
    if (companyId) {
      const companyArchiveData = dbCompanyArchive.findOne(companyId);
      if (companyArchiveData) {
        DocHead.setTitle(Meteor.settings.public.websiteName + ' - 「' + companyArchiveData.name + '」保管庫公司資訊');
      }
    }
  });
  this.autorun(() => {
    if (shouldStopSubscribe()) {
      return false;
    }
    const companyId = FlowRouter.getParam('companyId');
    if (companyId) {
      this.subscribe('companyArchiveDetail', companyId);
    }
  });
});
Template.companyArchiveDetail.helpers({
  companyArchiveData() {
    const companyId = FlowRouter.getParam('companyId');

    return dbCompanyArchive.findOne(companyId);
  },
  showAllTags(tags) {
    if (tags.length <= 4) {
      return true;
    }

    return rShowAllTags.get();
  },
  firstFewTags(tags) {
    return tags.slice(0, 3);
  }
});
Template.companyArchiveDetail.events({
  'click [data-action="invest"]'(event) {
    event.preventDefault();
    investArchiveCompany(this);
  },
  'click [data-action="showAllTags"]'(event) {
    event.preventDefault();
    rShowAllTags.set(true);
  }
});

//是否展開面板
const rDisplayPanelList = new ReactiveVar([]);
Template.companyArchiveDetailTable.onRendered(function() {
  switch (this.data.status) {
    case 'market': {
      FlowRouter.go('companyDetail', {
        companyId: this.data._id
      });
      break;
    }
    case 'foundation': {
      FlowRouter.go('foundationDetail', {
        foundationId: this.data._id
      });
      break;
    }
  }
});
Template.companyArchiveDetailTable.helpers({
  isDisplayPanel(panelType) {
    return _.contains(rDisplayPanelList.get(), panelType);
  },
  archiveReviveNeedUsers() {
    return Meteor.settings.public.archiveReviveNeedUsers;
  }
});
Template.companyArchiveDetailTable.events({
  'click [data-toggle-panel]'(event) {
    event.preventDefault();
    const $emitter = $(event.currentTarget);
    const panelType = $emitter.attr('data-toggle-panel');
    const displayPanelList = rDisplayPanelList.get();
    if (_.contains(displayPanelList, panelType)) {
      rDisplayPanelList.set(_.without(displayPanelList, panelType));
    }
    else {
      displayPanelList.push(panelType);
      rDisplayPanelList.set(displayPanelList);
    }
  }
});

const rLogOffset = new ReactiveVar(0);
inheritedShowLoadingOnSubscribing(Template.companyArchiveLogList);
Template.companyArchiveLogList.onCreated(function() {
  rLogOffset.set(0);
  this.autorun(() => {
    if (shouldStopSubscribe()) {
      return false;
    }
    const companyId = FlowRouter.getParam('companyId');
    if (companyId) {
      this.subscribe('companyLog', companyId, false, rLogOffset.get());
    }
  });
});
Template.companyArchiveLogList.helpers({
  logList() {
    const companyId = FlowRouter.getParam('companyId');

    return dbLog.find({companyId}, {
      sort: {
        createdAt: -1
      },
      limit: 30
    });
  },
  paginationData() {
    return {
      useVariableForTotalCount: 'totalCountOfcompanyLog',
      dataNumberPerPage: 30,
      offset: rLogOffset
    };
  }
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import { FormattedMessage, intlShape } from 'react-intl'
import { reduxForm } from 'redux-form'

import serverConfig from '~server/config'
import { FormGroup, ControlLabel, FormControl, UploadImageField } from '~client/components/forms'

const FormShare = ({
  FormComponent,
  fields: {
    facebook_share_image: facebookShareImage,
    facebook_share_title: facebookShareTitle,
    facebook_share_description: facebookShareDescription,
    twitter_share_text: twitterShareText
  },
  intl,
  ...formProps
}) => (
  <FormComponent {...formProps}>

        <FormattedMessage
          id='mobilizations.components--form-share.facebook.title'
          defaultMessage='Share de Facebook'
        />

      <FormattedMessage
        id='mobilizations.components--form-share.facebook.helper-text'
        defaultMessage='Configure o post que será publicado no Facebook sempre que alguém compartilhar a ação. É importante que esses textos sejam cativantes e curtos para não aparecerem cortados. :)'
      />

      <FormattedMessage
        id='mobilizations.components--form-share.facebook.fb.image.helper-text'
        defaultMessage='Use imagens com pelo menos 1200x630 pixels para a melhor exibição em dispositivos de alta resolução. No mínimo, você deve usar imagens que tenham 600x315 pixels para exibir publicações na página com link com imagens maiores. O tamanho máximo das imagens é de 8 MB.'
      />

        <FormattedMessage
          id='mobilizations.components--form-share.facebook.fb.image.link'
          defaultMessage='Saiba mais'
        />

      .

      <FormGroup
        contorlId='facebookShareImage'
        className='facebook-share-image col col-5'
        {...facebookShareImage}
      >
        <ControlLabel>
          <FormattedMessage
            id='mobilizations.components--form-share.facebook.form.share-image.label'
            defaultMessage='Imagem'
          />
        </ControlLabel>
        <UploadImageField signingUrl={`${serverConfig.apiUrl}/uploads`} />
      </FormGroup>

        <FormGroup
          {...facebookShareTitle}
          controlId='facebookShareTitle'
          className='facebook-share-title'
          style={{ paddingLeft: '0' }}
        >
          <ControlLabel className='ml1' maxLength={70}>
            <FormattedMessage
              id='mobilizations.components--form-share.facebook.form.share-title.label'
              defaultMessage='Título do post'
            />
          </ControlLabel>
          <FormControl
            componentClass='textarea'
            rows={2}
            maxLength={70}
            placeholder={
              intl.formatMessage({
                id: 'mobilizations.components--form-share.facebook.form.share-title.placeholder',
                defaultMessage: 'Um título direto que passe a ideia da sua mobilização'
              })
            }
          />
        </FormGroup>

        <FormGroup
          controlId='facebookShareDescription'
          className='facebook-share-description'
          style={{ paddingLeft: '0' }}
          {...facebookShareDescription}
        >
          <ControlLabel className='ml1' maxLength={90}>
            <FormattedMessage
              id='mobilizations.components--form-share.facebook.form.share-description.label'
              defaultMessage='Subtítulo do post'
            />
          </ControlLabel>
          <FormControl
            componentClass='textarea'
            rows={4}
            maxLength={90}
            placeholder={
              intl.formatMessage({
                id: 'mobilizations.components--form-share.facebook.form.share-description.placeholder',
                defaultMessage: 'Complete a informação do título e chame o leitor para a mobilização'
              })
            }
          />
        </FormGroup>

          <FormattedMessage
            id='mobilizations.components--form-share.twitter.title'
            defaultMessage='Share de Twitter'
          />

        <FormattedMessage
          id='mobilizations.components--form-share.twitter.helper-text'
          defaultMessage='Configure a mensagem que será publicada no Twitter sempre que alguém compartilhar sua mobilização.'
        />

      <FormGroup
        controlId='twitterShareText' {...twitterShareText}
        className='twitter-share-text'
      >
        <ControlLabel maxLength={140}>
          <FormattedMessage
            id='mobilizations.components--form-share.twitter.form.share-text.label'
            defaultMessage='Texto do Tweet'
          />
        </ControlLabel>
        <FormControl
          componentClass='textarea'
          rows={5}
          maxLength={140}
          placeholder={
            intl.formatMessage({
              id: 'mobilizations.components--form-share.twitter.form.share-text.placeholder',
              defaultMessage: 'Insira uma frase e chame o leitor para a mobilização'
            })
          }
        />
      </FormGroup>

  </FormComponent>
)

FormShare.propTypes = {
  FormComponent: PropTypes.node,
  fields: PropTypes.shape({
    facebook_share_image: PropTypes.object.isRequired,
    facebook_share_title: PropTypes.object.isRequired,
    facebook_share_description: PropTypes.object.isRequired,
    twitter_share_text: PropTypes.object.isRequired
  }).isRequired,
  // translation
  intl: intlShape.isRequired
}

const fields = [
  'id',
  'facebook_share_image',
  'facebook_share_title',
  'facebook_share_description',
  'twitter_share_text'
]

export default (
  mapStateToProps = () => {},
  mapDispatchToProps = {},
  validate = () => ({})
) => reduxForm(
  { form: 'mobilizationShareForm', fields, validate },
  mapStateToProps,
  mapDispatchToProps
)(FormShare)
<commit_msg>chore(intl): fix form share intl injection #599<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import { FormattedMessage, intlShape, injectIntl } from 'react-intl'
import { reduxForm } from 'redux-form'

import serverConfig from '~server/config'
import { FormGroup, ControlLabel, FormControl, UploadImageField } from '~client/components/forms'

const FormShare = ({
  FormComponent,
  fields: {
    facebook_share_image: facebookShareImage,
    facebook_share_title: facebookShareTitle,
    facebook_share_description: facebookShareDescription,
    twitter_share_text: twitterShareText
  },
  intl,
  ...formProps
}) => (
  <FormComponent {...formProps}>

        <FormattedMessage
          id='mobilizations.components--form-share.facebook.title'
          defaultMessage='Share de Facebook'
        />

      <FormattedMessage
        id='mobilizations.components--form-share.facebook.helper-text'
        defaultMessage='Configure o post que será publicado no Facebook sempre que alguém compartilhar a ação. É importante que esses textos sejam cativantes e curtos para não aparecerem cortados. :)'
      />

      <FormattedMessage
        id='mobilizations.components--form-share.facebook.fb.image.helper-text'
        defaultMessage='Use imagens com pelo menos 1200x630 pixels para a melhor exibição em dispositivos de alta resolução. No mínimo, você deve usar imagens que tenham 600x315 pixels para exibir publicações na página com link com imagens maiores. O tamanho máximo das imagens é de 8 MB.'
      />

        <FormattedMessage
          id='mobilizations.components--form-share.facebook.fb.image.link'
          defaultMessage='Saiba mais'
        />

      .

      <FormGroup
        contorlId='facebookShareImage'
        className='facebook-share-image col col-5'
        {...facebookShareImage}
      >
        <ControlLabel>
          <FormattedMessage
            id='mobilizations.components--form-share.facebook.form.share-image.label'
            defaultMessage='Imagem'
          />
        </ControlLabel>
        <UploadImageField signingUrl={`${serverConfig.apiUrl}/uploads`} />
      </FormGroup>

        <FormGroup
          {...facebookShareTitle}
          controlId='facebookShareTitle'
          className='facebook-share-title'
          style={{ paddingLeft: '0' }}
        >
          <ControlLabel className='ml1' maxLength={70}>
            <FormattedMessage
              id='mobilizations.components--form-share.facebook.form.share-title.label'
              defaultMessage='Título do post'
            />
          </ControlLabel>
          <FormControl
            componentClass='textarea'
            rows={2}
            maxLength={70}
            placeholder={
              intl.formatMessage({
                id: 'mobilizations.components--form-share.facebook.form.share-title.placeholder',
                defaultMessage: 'Um título direto que passe a ideia da sua mobilização'
              })
            }
          />
        </FormGroup>

        <FormGroup
          controlId='facebookShareDescription'
          className='facebook-share-description'
          style={{ paddingLeft: '0' }}
          {...facebookShareDescription}
        >
          <ControlLabel className='ml1' maxLength={90}>
            <FormattedMessage
              id='mobilizations.components--form-share.facebook.form.share-description.label'
              defaultMessage='Subtítulo do post'
            />
          </ControlLabel>
          <FormControl
            componentClass='textarea'
            rows={4}
            maxLength={90}
            placeholder={
              intl.formatMessage({
                id: 'mobilizations.components--form-share.facebook.form.share-description.placeholder',
                defaultMessage: 'Complete a informação do título e chame o leitor para a mobilização'
              })
            }
          />
        </FormGroup>

          <FormattedMessage
            id='mobilizations.components--form-share.twitter.title'
            defaultMessage='Share de Twitter'
          />

        <FormattedMessage
          id='mobilizations.components--form-share.twitter.helper-text'
          defaultMessage='Configure a mensagem que será publicada no Twitter sempre que alguém compartilhar sua mobilização.'
        />

      <FormGroup
        controlId='twitterShareText' {...twitterShareText}
        className='twitter-share-text'
      >
        <ControlLabel maxLength={140}>
          <FormattedMessage
            id='mobilizations.components--form-share.twitter.form.share-text.label'
            defaultMessage='Texto do Tweet'
          />
        </ControlLabel>
        <FormControl
          componentClass='textarea'
          rows={5}
          maxLength={140}
          placeholder={
            intl.formatMessage({
              id: 'mobilizations.components--form-share.twitter.form.share-text.placeholder',
              defaultMessage: 'Insira uma frase e chame o leitor para a mobilização'
            })
          }
        />
      </FormGroup>

  </FormComponent>
)

FormShare.propTypes = {
  FormComponent: PropTypes.node,
  fields: PropTypes.shape({
    facebook_share_image: PropTypes.object.isRequired,
    facebook_share_title: PropTypes.object.isRequired,
    facebook_share_description: PropTypes.object.isRequired,
    twitter_share_text: PropTypes.object.isRequired
  }).isRequired,
  // translation
  intl: intlShape.isRequired
}

const fields = [
  'id',
  'facebook_share_image',
  'facebook_share_title',
  'facebook_share_description',
  'twitter_share_text'
]

export default (
  mapStateToProps = () => {},
  mapDispatchToProps = {},
  validate = () => ({})
) => reduxForm(
  { form: 'mobilizationShareForm', fields, validate },
  mapStateToProps,
  mapDispatchToProps
)(injectIntl(FormShare))
<|endoftext|>