<commit_before>var _ = require('lodash');
var expect = require('chai').expect;
var monoxide = require('..');
var testSetup = require('./setup');

describe('monoxide.queryBuilder (promises)', function() {
	before(testSetup.init);
	before(done => monoxide.use('promises', done));
	after(testSetup.teardown);

	it('should return a true promise class', function() {
		var req = monoxide.models.users.count();
		expect(req).to.have.property('then');
		expect(req.then).to.be.a('function');
		expect(req).to.be.an.instanceOf(Promise);
	});

	it('should query the users model as a promise (via promise())', function(finish) {
		monoxide.models.users
			.find()
			.promise()
			.then(user => {
				expect(user).to.be.an('array');
				expect(user).to.have.length(2);
				finish();
			})
			.catch(()=> expect.fail())
	});

	it('should query the users model as a promise (via then())', function(finish) {
		monoxide.models.users
			.find()
			.then(user => {
				expect(user).to.be.an('array');
				expect(user).to.have.length(2);
				finish();
			})
			.catch(()=> expect.fail())
	});

	it('should query the users model as a promise (via catch())', function(finish) {
		monoxide.models.users
			.find()
			.catch(()=> expect.fail())
			.then(user => {
				expect(user).to.be.an('array');
				expect(user).to.have.length(2);
				finish();
			})
	});

	it('should query the users model as a promise (via finally())', function(finish) {
		monoxide.models.users
			.find()
			.catch(()=> expect.fail())
			.then(user => {
				expect(user).to.be.an('array');
				expect(user).to.have.length(2);
				finish();
			})
	});

	it('should return results and process them as promises', function(finish) {
		monoxide.models.users
			.findOne()
			.then(user => {
				expect(user).to.be.an('object');
				expect(user).to.have.property('_id');
				var saver = user.save();
				expect(saver).to.be.a('promise');
				return saver;
			})
			.then(()=> finish())
			.catch(()=> expect.fail())
	});

	it('should manage additional arguments after find()', function(finish) {
		var users;
		monoxide.models.users.find()
			.then(res => users = res)
			.then(()=> monoxide.models.users
				.findOneByID(users[0]._id)
				.populate('favourite')
				.limit(1)
			)
			.then(user => {
				expect(user).to.be.an('object');
				expect(user).to.have.property('_id');
				expect(user).to.have.property('favourite');
				expect(user.favourite).to.be.an('object');
			})
			.then(()=> finish())
			.catch(()=> expect.fail())
	});
});
<commit_msg>TEST: Added tests for findOneByID + filtering<commit_after>var _ = require('lodash');
var expect = require('chai').expect;
var monoxide = require('..');
var testSetup = require('./setup');

describe('monoxide.queryBuilder (promises)', function() {
	before(testSetup.init);
	before(done => monoxide.use('promises', done));
	after(testSetup.teardown);

	var users;
	before('should find a list of users', function() {
		return monoxide.models.users
			.find()
			.then(res => users = res)
			.then(()=> expect(users).to.be.an('array'))
			.then(()=> expect(users).to.have.length.above(1))
	});

	it('should return a true promise class', function() {
		var req = monoxide.models.users.count();
		expect(req).to.have.property('then');
		expect(req.then).to.be.a('function');
		expect(req).to.be.an.instanceOf(Promise);
	});

	it('should query the users model as a promise (via promise())', function(finish) {
		monoxide.models.users
			.find()
			.promise()
			.then(user => {
				expect(user).to.be.an('array');
				expect(user).to.have.length(2);
				finish();
			})
			.catch(()=> expect.fail())
	});

	it('should query the users model as a promise (via then())', function(finish) {
		monoxide.models.users
			.find()
			.then(user => {
				expect(user).to.be.an('array');
				expect(user).to.have.length(2);
				finish();
			})
			.catch(()=> expect.fail())
	});

	it('should query the users model as a promise (via catch())', function(finish) {
		monoxide.models.users
			.find()
			.catch(()=> expect.fail())
			.then(user => {
				expect(user).to.be.an('array');
				expect(user).to.have.length(2);
				finish();
			})
	});

	it('should query the users model as a promise (via finally())', function(finish) {
		monoxide.models.users
			.find()
			.catch(()=> expect.fail())
			.then(user => {
				expect(user).to.be.an('array');
				expect(user).to.have.length(2);
				finish();
			})
	});

	it('should return results and process them as promises', function(finish) {
		monoxide.models.users
			.findOne()
			.then(user => {
				expect(user).to.be.an('object');
				expect(user).to.have.property('_id');
				var saver = user.save();
				expect(saver).to.be.a('promise');
				return saver;
			})
			.then(()=> finish())
			.catch(()=> expect.fail())
	});

	it('should find one user by ID', function(finish) {
		monoxide.models.users
			.findOneByID(users[0]._id)
			.then(user => {
				expect(user).to.be.an('object');
				expect(user).to.have.property('_id', users[0]._id);
				finish();
			})
			.catch(()=> expect.fail())
	});

	it('should find one user by ID with filtering', function(finish) {
		monoxide.models.users
			.findOneByID(users[0]._id)
			.select('name')
			.then(user => {
				expect(user).to.be.an('object');
				expect(user).to.have.property('_id', users[0]._id);
				expect(Object.keys(user).sort()).to.be.deep.equal(['_id', 'name']);
				finish();
			})
			.catch(()=> expect.fail())
	});

	it('should manage additional arguments after find()', function(finish) {
		var users;
		monoxide.models.users.find()
			.then(res => users = res)
			.then(()=> monoxide.models.users
				.findOneByID(users[0]._id)
				.populate('favourite')
				.limit(1)
			)
			.then(user => {
				expect(user).to.be.an('object');
				expect(user).to.have.property('_id');
				expect(user).to.have.property('favourite');
				expect(user.favourite).to.be.an('object');
			})
			.then(()=> finish())
			.catch(()=> expect.fail())
	});
});
<|endoftext|>


<commit_before>var expect = require('expect.js');
var server = require('./server');

var ROOT_URL = '/';

var PlexAPI = require('..');

describe('putQuery()', function() {
	var api;

	beforeEach(function() {
		server.expectsPut();

		api = new PlexAPI('localhost');
	});

	afterEach(server.stop);

	it('should exist', function() {
		expect(api.putQuery).to.be.a('function');
	});

	describe('parameters', function() {
		it('requires url parameter', function() {
			expect(function() {
				api.putQuery();
			}).to.throwException('TypeError');
		});

		it('can accept url parameter as only parameter', function() {
			return api.putQuery('/');
		});

		it('can accept url parameter as part of a parameter object', function() {
			return api.putQuery({uri: '/'});
		});

		it('uses extra headers passed in parameters', function() {
			server.stop();
			var nockServer = server.expectsPut({'reqheaders': {
				'X-TEST-HEADER':'X-TEST-HEADER-VAL'
			}});

			return api.putQuery({uri: '/', extraHeaders: {'X-TEST-HEADER':'X-TEST-HEADER-VAL'}}).then(function(result) {
				nockServer.done();
				return result;
			});
		});
	});

	it('promise should fail when server responds with failure status code', function() {
        return api.putQuery(ROOT_URL).fail(function(err) {
			expect(err).not.to.be(null);
		});
	});

	it('promise should succeed when request response status code is 200', function() {
		return api.putQuery(ROOT_URL);
	});

	it('promise should succeed when request response status code is 201', function() {
		server.stop();
		server.expectsPut({statusCode: 201});
		return api.putQuery(ROOT_URL);
	});

	it('should result in a POST request', function() {
		return api.putQuery(ROOT_URL);
	});
});
<commit_msg>Fixed typo (PUT instead of POST).<commit_after>var expect = require('expect.js');
var server = require('./server');

var ROOT_URL = '/';

var PlexAPI = require('..');

describe('putQuery()', function() {
	var api;

	beforeEach(function() {
		server.expectsPut();

		api = new PlexAPI('localhost');
	});

	afterEach(server.stop);

	it('should exist', function() {
		expect(api.putQuery).to.be.a('function');
	});

	describe('parameters', function() {
		it('requires url parameter', function() {
			expect(function() {
				api.putQuery();
			}).to.throwException('TypeError');
		});

		it('can accept url parameter as only parameter', function() {
			return api.putQuery('/');
		});

		it('can accept url parameter as part of a parameter object', function() {
			return api.putQuery({uri: '/'});
		});

		it('uses extra headers passed in parameters', function() {
			server.stop();
			var nockServer = server.expectsPut({'reqheaders': {
				'X-TEST-HEADER':'X-TEST-HEADER-VAL'
			}});

			return api.putQuery({uri: '/', extraHeaders: {'X-TEST-HEADER':'X-TEST-HEADER-VAL'}}).then(function(result) {
				nockServer.done();
				return result;
			});
		});
	});

	it('promise should fail when server responds with failure status code', function() {
        return api.putQuery(ROOT_URL).fail(function(err) {
			expect(err).not.to.be(null);
		});
	});

	it('promise should succeed when request response status code is 200', function() {
		return api.putQuery(ROOT_URL);
	});

	it('promise should succeed when request response status code is 201', function() {
		server.stop();
		server.expectsPut({statusCode: 201});
		return api.putQuery(ROOT_URL);
	});

	it('should result in a PUT request', function() {
		return api.putQuery(ROOT_URL);
	});
});
<|endoftext|>


<commit_before>var assert      = require('assert');
var browserify  = require('browserify');
var coffeeify   = require('coffeeify');
var reactify    = require('../index');

describe('reactify', function() {

  function bundle(entry, cb) {
    return b = browserify(entry, {basedir: __dirname})
      .transform(coffeeify)
      .transform(reactify)
      .bundle(cb);
  };

  function assertContains(bundle, code) {
    assert(bundle.indexOf(code) > -1, "bundle does not contain: " + code);
  }

  it('works for *.js with pragma', function(done) {
    return bundle('./fixtures/main.js', function(err, result) {
      assert(!err);
      assert(result);
      assertContains(result, 'React.DOM.h1(null, "Hello, world!")');
      done();
    });
  });

  it('works for *.jsx', function(done) {
    return bundle('./fixtures/main.jsx', function(err, result) {
      assert(!err);
      assert(result);
      assertContains(result, 'React.DOM.h1(null, "Hello, world!")');
      done();
    });
  });

  it('works for plain *.js', function(done) {
    return bundle('./fixtures/simple.js', function(err, result) {
      assert(!err);
      assert(result);
      assertContains(result, 'React.DOM.h1(null, "Hello, world!")');
      done();
    });
  });

  it('works for *.coffee', function(done) {
    return bundle('./fixtures/coffee.coffee', function(err, result) {
      assert(!err);
      assert(result);
      assertContains(result, 'React.DOM.span( {class:"caret"})');
      done();
    });
  });

  it('returns error on invalid JSX', function(done) {
    return bundle('./fixtures/invalid.js', function(err, result) {
      assert(err);
      assertContains(String(err), 'Parse Error: Line 6: Unexpected token');
      assert(!result);
      done();
    });
  });

  return it('works for *.js without pragma when we ask it so', function(done) {
    return browserify('./fixtures/main.jsnox', {basedir: __dirname})
      .transform({extension: 'jsnox'}, reactify)
      .bundle(function(err, result) {
        assert(!err);
        assert(result);
        assertContains(result, 'React.DOM.h1(null, "Hello, world!")');
        return done();
      });
  });

});
<commit_msg>tests: gardening<commit_after>var assert      = require('assert');
var browserify  = require('browserify');
var coffeeify   = require('coffeeify');
var reactify    = require('../index');

describe('reactify', function() {

  function bundle(entry, cb) {
    return b = browserify(entry, {basedir: __dirname})
      .transform(coffeeify)
      .transform(reactify)
      .bundle(cb);
  };

  function assertContains(bundle, code) {
    assert(bundle.indexOf(code) > -1, "bundle does not contain: " + code);
  }

  it('works for *.js with pragma', function(done) {
    bundle('./fixtures/main.js', function(err, result) {
      assert(!err);
      assert(result);
      assertContains(result, 'React.DOM.h1(null, "Hello, world!")');
      done();
    });
  });

  it('works for *.jsx', function(done) {
    bundle('./fixtures/main.jsx', function(err, result) {
      assert(!err);
      assert(result);
      assertContains(result, 'React.DOM.h1(null, "Hello, world!")');
      done();
    });
  });

  it('works for plain *.js', function(done) {
    bundle('./fixtures/simple.js', function(err, result) {
      assert(!err);
      assert(result);
      assertContains(result, 'React.DOM.h1(null, "Hello, world!")');
      done();
    });
  });

  it('works for *.coffee', function(done) {
    bundle('./fixtures/coffee.coffee', function(err, result) {
      assert(!err);
      assert(result);
      assertContains(result, 'React.DOM.span( {class:"caret"})');
      done();
    });
  });

  it('returns error on invalid JSX', function(done) {
    bundle('./fixtures/invalid.js', function(err, result) {
      assert(err);
      assertContains(String(err), 'Parse Error: Line 6: Unexpected token');
      assert(!result);
      done();
    });
  });

  it('works for *.js without pragma when we ask it so', function(done) {
    browserify('./fixtures/main.jsnox', {basedir: __dirname})
      .transform({extension: 'jsnox'}, reactify)
      .bundle(function(err, result) {
        assert(!err);
        assert(result);
        assertContains(result, 'React.DOM.h1(null, "Hello, world!")');
        return done();
      });
  });

});
<|endoftext|>


<commit_before>'use strict';

var lab = exports.lab = require('lab').script();
var expect = require('code').expect;

var describe = lab.describe;
var it = lab.it;
var before = lab.before;
var beforeEach = lab.beforeEach;
var after = lab.after;
var afterEach = lab.afterEach;

var Undertaker = require('../');

var DefaultRegistry = require('undertaker-registry');
var CommonRegistry = require('undertaker-common-tasks');

function noop(){}

function CustomRegistry(){}
CustomRegistry.prototype.get = noop;
CustomRegistry.prototype.set = noop;
CustomRegistry.prototype.tasks = noop;

function InvalidRegistry(){}

describe('registry', function(){

  describe('method', function(){

    it('should return the current registry when no arguments are given', function(done){
      var taker = new Undertaker();
      expect(taker.registry()).to.equal(taker._registry);
      done();
    });

    it('should set the registry to the given registry instance argument', function(done){
      var taker = new Undertaker();
      var customRegistry = new CustomRegistry();
      taker.registry(customRegistry);
      expect(taker.registry()).to.equal(customRegistry);
      done();
    });

    it('should validate the custom registry instance', function(done){
      var taker = new Undertaker();
      var invalid = new InvalidRegistry();

      function invalidSet(){
        taker.registry(invalid);
      }

      expect(invalidSet).to.throw(Error, 'Custom registry must have `get` function');
      done();
    });

    it('should transfer all tasks from old registry to new', function(done){
      var taker = new Undertaker(CommonRegistry);
      var customRegistry = new DefaultRegistry();
      taker.registry(customRegistry);

      expect(customRegistry.get('clean')).to.be.a.function();
      expect(customRegistry.get('serve')).to.be.a.function();
      done();
    });
  });

  describe('constructor', function(){

    it('should take a custom registry constructor on instantiation', function(done){
      var taker = new Undertaker(CustomRegistry);
      expect(taker.registry()).to.be.an.instanceof(CustomRegistry);
      expect(taker.registry()).to.not.be.an.instanceof(DefaultRegistry);
      done();
    });

    it('should default to undertaker-registry if not constructed with custom registry', function(done){
      var taker = new Undertaker();
      expect(taker.registry()).to.be.an.instanceof(DefaultRegistry);
      expect(taker.registry()).to.not.be.an.instanceof(CustomRegistry);
      done();
    });

    it('should take a registry that pre-defines tasks', function(done){
      var taker = new Undertaker(CommonRegistry);
      expect(taker.registry()).to.be.an.instanceof(CommonRegistry);
      expect(taker.registry()).to.be.an.instanceof(DefaultRegistry);
      expect(taker.get('clean')).to.be.a.function();
      expect(taker.get('serve')).to.be.a.function();
      done();
    });

    it('should throw upon invalid registry', function(done){
      function noGet(){
        var taker = new Undertaker(InvalidRegistry);
      }

      expect(noGet).to.throw(Error, 'Custom registry must have `get` function');
      InvalidRegistry.prototype.get = noop;

      function noSet(){
        var taker = new Undertaker(InvalidRegistry);
      }

      expect(noSet).to.throw(Error, 'Custom registry must have `set` function');
      InvalidRegistry.prototype.set = noop;

      function noTasks(){
        var taker = new Undertaker(InvalidRegistry);
      }

      expect(noTasks).to.throw(Error, 'Custom registry must have `tasks` function');
      InvalidRegistry.prototype.tasks = noop;

      var taker = new Undertaker(InvalidRegistry);
      done();
    });
  });

});
<commit_msg>Update: Add test for multiple registry support<commit_after>'use strict';

var lab = exports.lab = require('lab').script();
var expect = require('code').expect;

var describe = lab.describe;
var it = lab.it;
var before = lab.before;
var beforeEach = lab.beforeEach;
var after = lab.after;
var afterEach = lab.afterEach;

var Undertaker = require('../');

var DefaultRegistry = require('undertaker-registry');
var CommonRegistry = require('undertaker-common-tasks');
var MetadataRegistry = require('undertaker-task-metadata');

function noop(){}

function CustomRegistry(){}
CustomRegistry.prototype.get = noop;
CustomRegistry.prototype.set = noop;
CustomRegistry.prototype.tasks = noop;

function InvalidRegistry(){}

describe('registry', function(){

  describe('method', function(){

    it('should return the current registry when no arguments are given', function(done){
      var taker = new Undertaker();
      expect(taker.registry()).to.equal(taker._registry);
      done();
    });

    it('should set the registry to the given registry instance argument', function(done){
      var taker = new Undertaker();
      var customRegistry = new CustomRegistry();
      taker.registry(customRegistry);
      expect(taker.registry()).to.equal(customRegistry);
      done();
    });

    it('should validate the custom registry instance', function(done){
      var taker = new Undertaker();
      var invalid = new InvalidRegistry();

      function invalidSet(){
        taker.registry(invalid);
      }

      expect(invalidSet).to.throw(Error, 'Custom registry must have `get` function');
      done();
    });

    it('should transfer all tasks from old registry to new', function(done){
      var taker = new Undertaker(CommonRegistry);
      var customRegistry = new DefaultRegistry();
      taker.registry(customRegistry);

      expect(taker.get('clean')).to.be.a.function();
      expect(taker.get('serve')).to.be.a.function();
      done();
    });

    it('allows multiple custom registries to used', function(done){
      var taker = new Undertaker();
      taker.registry(new CommonRegistry());

      expect(taker.get('clean')).to.be.a.function();
      expect(taker.get('serve')).to.be.a.function();

      taker.registry(new MetadataRegistry());
      taker.set('context', function(cb){
        expect(this).to.deep.equal({ name: 'context' });
        cb();
        done();
      });

      taker.registry(new DefaultRegistry());

      expect(taker.get('clean')).to.be.a.function();
      expect(taker.get('serve')).to.be.a.function();
      expect(taker.get('context')).to.be.a.function();

      taker.series('context')();
    });
  });

  describe('constructor', function(){

    it('should take a custom registry constructor on instantiation', function(done){
      var taker = new Undertaker(CustomRegistry);
      expect(taker.registry()).to.be.an.instanceof(CustomRegistry);
      expect(taker.registry()).to.not.be.an.instanceof(DefaultRegistry);
      done();
    });

    it('should default to undertaker-registry if not constructed with custom registry', function(done){
      var taker = new Undertaker();
      expect(taker.registry()).to.be.an.instanceof(DefaultRegistry);
      expect(taker.registry()).to.not.be.an.instanceof(CustomRegistry);
      done();
    });

    it('should take a registry that pre-defines tasks', function(done){
      var taker = new Undertaker(CommonRegistry);
      expect(taker.registry()).to.be.an.instanceof(CommonRegistry);
      expect(taker.registry()).to.be.an.instanceof(DefaultRegistry);
      expect(taker.get('clean')).to.be.a.function();
      expect(taker.get('serve')).to.be.a.function();
      done();
    });

    it('should throw upon invalid registry', function(done){
      function noGet(){
        var taker = new Undertaker(InvalidRegistry);
      }

      expect(noGet).to.throw(Error, 'Custom registry must have `get` function');
      InvalidRegistry.prototype.get = noop;

      function noSet(){
        var taker = new Undertaker(InvalidRegistry);
      }

      expect(noSet).to.throw(Error, 'Custom registry must have `set` function');
      InvalidRegistry.prototype.set = noop;

      function noTasks(){
        var taker = new Undertaker(InvalidRegistry);
      }

      expect(noTasks).to.throw(Error, 'Custom registry must have `tasks` function');
      InvalidRegistry.prototype.tasks = noop;

      var taker = new Undertaker(InvalidRegistry);
      done();
    });
  });

});
<|endoftext|>


<commit_before>'use strict';

var base    = require('yeoman-generator').generators.Base;
var sinon   = require('sinon');
var helpers = require('./helpers');

var scaffoldApplication    = helpers.scaffoldApp;
var verifyApplicationFiles = helpers.verifyFiles;
var verifyConfiguration    = helpers.verifyConfiguration;

describe('app', function() {
    var stub;
    var APPDIR;
    var CONFIGURED;
    var CSS_PROCESSOR;
    var SCRIPT_BUNDLER;
    describe('when all options are true (with less support)', function() {
        before(function(done) {
            stub = sinon.stub(base.prototype.user.git, 'name');
            stub.returns(null);
            CONFIGURED     = true;
            APPDIR         = './';
            SCRIPT_BUNDLER = 'browserify';
            CSS_PROCESSOR  = 'less';
            scaffoldApplication({
                appDirectory:   APPDIR,
                scriptBundler:  SCRIPT_BUNDLER,
                styleProcessor: CSS_PROCESSOR,
                allAnswersTrue: true
            }).on('end', done);
        });
        after(function() {
            stub.restore();
        });
        it('creates and configures files', function() {
            verifyApplicationFiles(APPDIR);
        });
        it('configures workflow and tool-chain', function() {
            verifyConfiguration({
                appDirectory:   APPDIR,
                workflow:       CONFIGURED,
                scriptBundler:  SCRIPT_BUNDLER,
                styleProcessor: CSS_PROCESSOR
            });
        });
    });
    describe('when all options are false', function() {
        before(function(done) {
                CONFIGURED     = false;
                APPDIR         = './';
                SCRIPT_BUNDLER = 'requirejs';
                CSS_PROCESSOR  = 'none';
                scaffoldApplication({
                    appDirectory:   APPDIR,
                    scriptBundler:  SCRIPT_BUNDLER,
                    styleProcessor: CSS_PROCESSOR,
                    allAnswersTrue: false
                }).on('end', done);
        });
        it('creates and configures files', function() {
            verifyApplicationFiles(APPDIR);
        });
        it('configures workflow and tool-chain', function() {
            verifyConfiguration({
                appDirectory:   APPDIR,
                workflow:       CONFIGURED,
                scriptBundler:  SCRIPT_BUNDLER,
                styleProcessor: CSS_PROCESSOR
            });
        });
    });
    describe('when the application directory is changed (with Sass support)', function() {
        before(function(done) {
                CONFIGURED     = false;
                APPDIR         = 'webapp';
                SCRIPT_BUNDLER = 'requirejs';
                CSS_PROCESSOR  = 'sass';
                scaffoldApplication({
                    appDirectory:   APPDIR,
                    scriptBundler:  SCRIPT_BUNDLER,
                    styleProcessor: CSS_PROCESSOR,
                    allAnswersTrue: false
                }).on('end', done);
        });
        it('creates and configures files', function() {
            verifyApplicationFiles(APPDIR);
        });
        it('configures workflow and tool-chain', function() {
            verifyConfiguration({
                appDirectory:   APPDIR,
                workflow:       CONFIGURED,
                scriptBundler:  SCRIPT_BUNDLER,
                styleProcessor: CSS_PROCESSOR
            });
        });
    });
});
<commit_msg>Disabled mocha timeout on app tests<commit_after>'use strict';

var base    = require('yeoman-generator').generators.Base;
var sinon   = require('sinon');
var helpers = require('./helpers');

var scaffoldApplication    = helpers.scaffoldApp;
var verifyApplicationFiles = helpers.verifyFiles;
var verifyConfiguration    = helpers.verifyConfiguration;

describe('app', function() {
    this.timeout(0)
    var stub;
    var APPDIR;
    var CONFIGURED;
    var CSS_PROCESSOR;
    var SCRIPT_BUNDLER;
    describe('when all options are true (with less support)', function() {
        before(function(done) {
            stub = sinon.stub(base.prototype.user.git, 'name');
            stub.returns(null);
            CONFIGURED     = true;
            APPDIR         = './';
            SCRIPT_BUNDLER = 'browserify';
            CSS_PROCESSOR  = 'less';
            scaffoldApplication({
                appDirectory:   APPDIR,
                scriptBundler:  SCRIPT_BUNDLER,
                styleProcessor: CSS_PROCESSOR,
                allAnswersTrue: true
            }).on('end', done);
        });
        after(function() {
            stub.restore();
        });
        it('creates and configures files', function() {
            verifyApplicationFiles(APPDIR);
        });
        it('configures workflow and tool-chain', function() {
            verifyConfiguration({
                appDirectory:   APPDIR,
                workflow:       CONFIGURED,
                scriptBundler:  SCRIPT_BUNDLER,
                styleProcessor: CSS_PROCESSOR
            });
        });
    });
    describe('when all options are false', function() {
        before(function(done) {
                CONFIGURED     = false;
                APPDIR         = './';
                SCRIPT_BUNDLER = 'requirejs';
                CSS_PROCESSOR  = 'none';
                scaffoldApplication({
                    appDirectory:   APPDIR,
                    scriptBundler:  SCRIPT_BUNDLER,
                    styleProcessor: CSS_PROCESSOR,
                    allAnswersTrue: false
                }).on('end', done);
        });
        it('creates and configures files', function() {
            verifyApplicationFiles(APPDIR);
        });
        it('configures workflow and tool-chain', function() {
            verifyConfiguration({
                appDirectory:   APPDIR,
                workflow:       CONFIGURED,
                scriptBundler:  SCRIPT_BUNDLER,
                styleProcessor: CSS_PROCESSOR
            });
        });
    });
    describe('when the application directory is changed (with Sass support)', function() {
        before(function(done) {
                CONFIGURED     = false;
                APPDIR         = 'webapp';
                SCRIPT_BUNDLER = 'requirejs';
                CSS_PROCESSOR  = 'sass';
                scaffoldApplication({
                    appDirectory:   APPDIR,
                    scriptBundler:  SCRIPT_BUNDLER,
                    styleProcessor: CSS_PROCESSOR,
                    allAnswersTrue: false
                }).on('end', done);
        });
        it('creates and configures files', function() {
            verifyApplicationFiles(APPDIR);
        });
        it('configures workflow and tool-chain', function() {
            verifyConfiguration({
                appDirectory:   APPDIR,
                workflow:       CONFIGURED,
                scriptBundler:  SCRIPT_BUNDLER,
                styleProcessor: CSS_PROCESSOR
            });
        });
    });
});
<|endoftext|>


<commit_before>import { withSeriesType } from 'react-jsx-highcharts';
export {
  Chart,
  Credits,
  Debug,
  Loading,
  Legend,
  Series,
  Subtitle,
  Title,
  Tooltip,
  provideHighcharts,
  provideChart,
  provideAxis,
  provideSeries,
  withHighcharts as withHighmaps,
  withSeriesType
} from 'react-jsx-highcharts';

// Charts
export { default as HighchartsMapChart } from './components/HighchartsMapChart';

// Graph Parts
export { default as MapNavigation } from './components/MapNavigation';
export { default as XAxis } from './components/XAxis';
export { default as YAxis } from './components/YAxis';

// Series
const parentAxisId = { axisId: 'yAxis' };
export const MapBubbleSeries = withSeriesType('MapBubble', parentAxisId);
export const MapLineSeries = withSeriesType('MapLine', parentAxisId);
export const MapPointSeries = withSeriesType('MapPoint', parentAxisId);
export const MapSeries = withSeriesType('Map', parentAxisId);
<commit_msg>Expose context in maps package<commit_after>import { withSeriesType } from 'react-jsx-highcharts';
export {
  Chart,
  Credits,
  Debug,
  Loading,
  Legend,
  Series,
  Subtitle,
  Title,
  Tooltip,
  HighchartsContext,
  HighchartsChartContext,
  HighchartsAxisContext,
  HighchartsSeriesContext,
  provideHighcharts,
  provideChart,
  provideAxis,
  provideSeries,
  withHighcharts as withHighmaps,
  withSeriesType
} from 'react-jsx-highcharts';

// Charts
export { default as HighchartsMapChart } from './components/HighchartsMapChart';

// Graph Parts
export { default as MapNavigation } from './components/MapNavigation';
export { default as XAxis } from './components/XAxis';
export { default as YAxis } from './components/YAxis';

// Series
const parentAxisId = { axisId: 'yAxis' };
export const MapBubbleSeries = withSeriesType('MapBubble', parentAxisId);
export const MapLineSeries = withSeriesType('MapLine', parentAxisId);
export const MapPointSeries = withSeriesType('MapPoint', parentAxisId);
export const MapSeries = withSeriesType('Map', parentAxisId);
<|endoftext|>


<commit_before>/**
 * A map describing parentheses-like grouping characters and their behavior. The
 * keys are the group's start character and the value's `end` property contains
 * the end character. The `matchNestedParens` property indicates whether or not
 * other grouping characters nested in the group retain their grouping behavior
 * within that group - i.e. if nested grouping characters need to be matched.
 *
 * @type {!Map<string, {end: string, matchNestedParens: boolean}>}
 */
const PARENS = new Map([
  ['(', {end: ')', matchNestedParens: true}],
  ['[', {end: ']', matchNestedParens: true}],
  ['"', {end: '"', matchNestedParens: false}],
  ["'", {end: "'", matchNestedParens: false}],
]);

/**
 * Finds the first character of `queryChars` within `str` from index `start`
 * onwards that is _not_ nested within any parentheses, brackets, or
 * single/double-quoted strings or part of an escape sequence.
 *
 * If the end of the string is reached without finding a character in
 * `queryChars`, the length of the string is returned.
 *
 * @param {string} str
 * @param {number} start
 * @param {!Array<string>} queryChars
 * @param {boolean} matchNestedParens
 * @return {number}
 */
const findNext = (str, start, queryChars, matchNestedParens = true) => {
  for (let i = start; i < str.length; i++) {
    if (str[i] === '\\' && i < str.length - 1 && str[i + 1] !== '\n') {
      // Skip escape sequences.
      i++;
    } else if (queryChars.indexOf(str[i]) !== -1) {
      // One of `queryChars` was found.
      return i;
    } else if (matchNestedParens && PARENS.has(str[i])) {
      // Handle any grouping characters by skipping over the group.
      const parenInfo = PARENS.get(str[i]);
      i = findNext(str, i + 1, [parenInfo.end], parenInfo.matchNestedParens);
      continue;
    }

    // Do nothing, let `i++` happen.
  }

  // Reached the end of the string without finding a final char.
  return str.length;
};

/**
 * Arrays of compound selectors and combinators that form a complex selector
 * when interleaved.
 *
 * @typedef {{
 *   compoundSelectors: !Array<string>,
 *   combinators: !Array<string>,
 * }}
 */
export let ComplexSelectorParts;

/**
 * Splits a selector list into individual complex selectors and creates a
 * `ComplexSelectorParts` for each.
 *
 * @param {string} str
 * @return {!Array<!ComplexSelectorParts>}
 */
export const parseSelectorList = (str) => {
  /**
   * @type {!Array<!ComplexSelectorParts>}
   */
  const results = [];

  /**
   * Compound selectors and combinators parsed from the current complex
   * selector.
   *
   * @type {!Array<string>}
   */
  const chunks = [];

  /**
   * Creates a new `ComplexSelectorParts` from the current `chunks`, pushes it
   * into `results` and resets `chunks`.
   */
  const endComplexSelector = () => {
    if (chunks.length > 0) {
      while (chunks[chunks.length - 1] === ' ') {
        chunks.pop();
      }
      results.push({
        compoundSelectors: chunks.filter((x, i) => i % 2 === 0),
        combinators: chunks.filter((x, i) => i % 2 === 1),
      });
      chunks.length = 0;
    }
  };

  for (let i = 0; i < str.length; ) {
    const prevChunk = chunks[chunks.length - 1];
    // `nextIndex` is the next complex selector boundary, combinator, or
    // whitespace that isn't inside other grouping characters.
    const nextIndex = findNext(str, i, [',', ' ', '>', '+', '~']);
    // If `nextIndex` is `i`, then the chunk we're considering is only the next
    // single character.
    const nextChunk = nextIndex === i ? str[i] : str.substring(i, nextIndex);

    if (nextChunk === ',') {
      endComplexSelector();
    } else if (
      [undefined, ' ', '>', '+', '~'].indexOf(prevChunk) !== -1 &&
      nextChunk === ' '
    ) {
      // Ignore leading whitespace and whitespace directly after combinators.
    } else if (prevChunk === ' ' && ['>', '+', '~'].indexOf(nextChunk) !== -1) {
      // If the last chunk was whitespace and this chunk is a non-whitespace
      // combinator, replace the whitespace with this combinator.
      chunks[chunks.length - 1] = nextChunk;
    } else {
      chunks.push(nextChunk);
    }

    i = nextIndex + (nextIndex === i ? 1 : 0);
  }

  endComplexSelector();

  return results;
};
<commit_msg>IE 11 doesn't support `Map`'s constructor parameter.<commit_after>/**
 * A map describing parentheses-like grouping characters and their behavior. The
 * keys are the group's start character and the value's `end` property contains
 * the end character. The `matchNestedParens` property indicates whether or not
 * other grouping characters nested in the group retain their grouping behavior
 * within that group - i.e. if nested grouping characters need to be matched.
 *
 * @type {!Map<string, {end: string, matchNestedParens: boolean}>}
 */
const PARENS = new Map();
// IE 11 doesn't support `Map`'s constructor parameter.
[
  ['(', {end: ')', matchNestedParens: true}],
  ['[', {end: ']', matchNestedParens: true}],
  ['"', {end: '"', matchNestedParens: false}],
  ["'", {end: "'", matchNestedParens: false}],
].forEach(([k, v]) => {
  PARENS.set(k, v);
});

/**
 * Finds the first character of `queryChars` within `str` from index `start`
 * onwards that is _not_ nested within any parentheses, brackets, or
 * single/double-quoted strings or part of an escape sequence.
 *
 * If the end of the string is reached without finding a character in
 * `queryChars`, the length of the string is returned.
 *
 * @param {string} str
 * @param {number} start
 * @param {!Array<string>} queryChars
 * @param {boolean} matchNestedParens
 * @return {number}
 */
const findNext = (str, start, queryChars, matchNestedParens = true) => {
  for (let i = start; i < str.length; i++) {
    if (str[i] === '\\' && i < str.length - 1 && str[i + 1] !== '\n') {
      // Skip escape sequences.
      i++;
    } else if (queryChars.indexOf(str[i]) !== -1) {
      // One of `queryChars` was found.
      return i;
    } else if (matchNestedParens && PARENS.has(str[i])) {
      // Handle any grouping characters by skipping over the group.
      const parenInfo = PARENS.get(str[i]);
      i = findNext(str, i + 1, [parenInfo.end], parenInfo.matchNestedParens);
      continue;
    }

    // Do nothing, let `i++` happen.
  }

  // Reached the end of the string without finding a final char.
  return str.length;
};

/**
 * Arrays of compound selectors and combinators that form a complex selector
 * when interleaved.
 *
 * @typedef {{
 *   compoundSelectors: !Array<string>,
 *   combinators: !Array<string>,
 * }}
 */
export let ComplexSelectorParts;

/**
 * Splits a selector list into individual complex selectors and creates a
 * `ComplexSelectorParts` for each.
 *
 * @param {string} str
 * @return {!Array<!ComplexSelectorParts>}
 */
export const parseSelectorList = (str) => {
  /**
   * @type {!Array<!ComplexSelectorParts>}
   */
  const results = [];

  /**
   * Compound selectors and combinators parsed from the current complex
   * selector.
   *
   * @type {!Array<string>}
   */
  const chunks = [];

  /**
   * Creates a new `ComplexSelectorParts` from the current `chunks`, pushes it
   * into `results` and resets `chunks`.
   */
  const endComplexSelector = () => {
    if (chunks.length > 0) {
      while (chunks[chunks.length - 1] === ' ') {
        chunks.pop();
      }
      results.push({
        compoundSelectors: chunks.filter((x, i) => i % 2 === 0),
        combinators: chunks.filter((x, i) => i % 2 === 1),
      });
      chunks.length = 0;
    }
  };

  for (let i = 0; i < str.length; ) {
    const prevChunk = chunks[chunks.length - 1];
    // `nextIndex` is the next complex selector boundary, combinator, or
    // whitespace that isn't inside other grouping characters.
    const nextIndex = findNext(str, i, [',', ' ', '>', '+', '~']);
    // If `nextIndex` is `i`, then the chunk we're considering is only the next
    // single character.
    const nextChunk = nextIndex === i ? str[i] : str.substring(i, nextIndex);

    if (nextChunk === ',') {
      endComplexSelector();
    } else if (
      [undefined, ' ', '>', '+', '~'].indexOf(prevChunk) !== -1 &&
      nextChunk === ' '
    ) {
      // Ignore leading whitespace and whitespace directly after combinators.
    } else if (prevChunk === ' ' && ['>', '+', '~'].indexOf(nextChunk) !== -1) {
      // If the last chunk was whitespace and this chunk is a non-whitespace
      // combinator, replace the whitespace with this combinator.
      chunks[chunks.length - 1] = nextChunk;
    } else {
      chunks.push(nextChunk);
    }

    i = nextIndex + (nextIndex === i ? 1 : 0);
  }

  endComplexSelector();

  return results;
};
<|endoftext|>


<commit_before>import { resolve, join as pathJoin } from "path";
import { isEmpty } from "lodash";
import chokidar from "chokidar";
import seedBuilder from "snowboard-seeder";
import { spinner, toc } from "snowboard-helper";
import { read } from "snowboard-reader";
import { parse, fromRefract } from "snowboard-parser";
import { cp, tmpdir, mkdirp, writeFile, jsonStringify } from "snowboard-helper";

const dirNames = {
  html: "html",
  jsonHtml: "html/__json__",
  json: "json",
  tmp: "tmp"
};

export async function setupDir(output) {
  await Promise.all(
    Object.values(dirNames).map(dirName => {
      return mkdirp(resolve(output, dirName));
    })
  );

  const tmpDir = resolve(output, dirNames.tmp);
  const buildDir = await tmpdir({ dir: tmpDir, prefix: "build-" });

  return {
    buildDir,
    outDir: resolve(output),
    htmlDir: resolve(output, dirNames.html)
  };
}

export async function buildSeed(input, config, { quiet }) {
  const element = await spinner(load(input), "Parsing input", {
    success: "Input parsed",
    quiet
  });

  const { transitions, ...seeds } = await seedBuilder(element, { config });

  seeds.uuids = Object.fromEntries(
    transitions.map(({ permalink, uuid }) => [permalink, uuid])
  );

  seeds.descriptionToc = await toc(seeds.description);

  return [seeds, transitions];
}

export async function writeSeed(buildDir, seeds, { optimized }) {
  const data = `const seeds = ${jsonStringify(seeds, optimized)};
export default seeds;
  `;

  return writeFile(resolve(buildDir, "seeds.js"), data, "utf8");
}

export async function writeJSON(
  outDir,
  transitionSeeds,
  uuidMap,
  { optimized }
) {
  const jsonDir = resolve(outDir, dirNames.json);
  const jsonHtmlDir = resolve(outDir, dirNames.jsonHtml);

  await Promise.all(
    transitionSeeds.map(async transition => {
      const filename = `${uuidMap[transition.permalink]}.json`;

      await writeFile(
        pathJoin(jsonDir, filename),
        jsonStringify(transition, optimized),
        "utf8"
      );
    })
  );

  await cp(jsonDir, jsonHtmlDir);
}

async function load(input) {
  const source = await read(input);
  const result = await parse(source);

  return fromRefract(result);
}

export function watchTemplate(tplDir, buildDir) {
  const watcher = chokidar.watch(tplDir, {
    persistent: true
  });

  watcher.on("change", async path => {
    await cp(path, path.replace(tplDir, buildDir));
  });

  return watcher;
}

export function watchOverrides(overrides, buildDir) {
  if (isEmpty(overrides)) {
    return null;
  }

  const watcher = chokidar.watch(Object.values(overrides), {
    persistent: true
  });

  watcher.on("change", async path => {
    await cp(path, resolve(buildDir, keyByValue(overrides, path)));
  });

  return watcher;
}

function keyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}

export function watchInput(
  input,
  config,
  outDir,
  buildDir,
  { optimized, quiet }
) {
  const watcher = chokidar.watch(input, {
    persistent: true
  });

  watcher.on("change", async path => {
    const [seeds, transitionSeeds] = await buildSeed(path, config, { quiet });

    await writeSeed(buildDir, seeds, { optimized });
    await writeJSON(transitionSeeds, seeds.uuids, outDir, { optimized });
  });

  return watcher;
}
<commit_msg>update output directory<commit_after>import { resolve, join as pathJoin } from "path";
import { isEmpty } from "lodash";
import chokidar from "chokidar";
import seedBuilder from "snowboard-seeder";
import { spinner, toc } from "snowboard-helper";
import { read } from "snowboard-reader";
import { parse, fromRefract } from "snowboard-parser";
import { cp, tmpdir, mkdirp, writeFile, jsonStringify } from "snowboard-helper";

export async function setupDir(output) {
  const buildDir = await tmpdir({ prefix: "snowboard-build-" });

  return {
    buildDir,
    outDir: resolve(output)
  };
}

export async function buildSeed(input, config, { quiet }) {
  const element = await spinner(load(input), "Parsing input", {
    success: "Input parsed",
    quiet
  });

  const { transitions, ...seeds } = await seedBuilder(element, { config });

  seeds.uuids = Object.fromEntries(
    transitions.map(({ permalink, uuid }) => [permalink, uuid])
  );

  seeds.descriptionToc = await toc(seeds.description);

  return [seeds, transitions];
}

export async function writeSeed(buildDir, seeds, { optimized }) {
  const data = `const seeds = ${jsonStringify(seeds, optimized)};
export default seeds;
  `;

  return writeFile(resolve(buildDir, "seeds.js"), data, "utf8");
}

export async function writeJSON(
  outDir,
  transitionSeeds,
  uuidMap,
  { optimized }
) {
  const jsonDir = resolve(outDir, "__json__");

  await mkdirp(jsonDir);
  await Promise.all(
    transitionSeeds.map(async transition => {
      const filename = `${uuidMap[transition.permalink]}.json`;

      await writeFile(
        pathJoin(jsonDir, filename),
        jsonStringify(transition, optimized),
        "utf8"
      );
    })
  );
}

async function load(input) {
  const source = await read(input);
  const result = await parse(source);

  return fromRefract(result);
}

export function watchTemplate(tplDir, buildDir) {
  const watcher = chokidar.watch(tplDir, {
    persistent: true
  });

  watcher.on("change", async path => {
    await cp(path, path.replace(tplDir, buildDir));
  });

  return watcher;
}

export function watchOverrides(overrides, buildDir) {
  if (isEmpty(overrides)) {
    return null;
  }

  const watcher = chokidar.watch(Object.values(overrides), {
    persistent: true
  });

  watcher.on("change", async path => {
    await cp(path, resolve(buildDir, keyByValue(overrides, path)));
  });

  return watcher;
}

function keyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}

export function watchInput(
  input,
  config,
  outDir,
  buildDir,
  { optimized, quiet }
) {
  const watcher = chokidar.watch(input, {
    persistent: true
  });

  watcher.on("change", async path => {
    const [seeds, transitionSeeds] = await buildSeed(path, config, { quiet });

    await writeSeed(buildDir, seeds, { optimized });
    await writeJSON(transitionSeeds, seeds.uuids, outDir, { optimized });
  });

  return watcher;
}
<|endoftext|>


<commit_before>// Subscribe to Provider data
Meteor.subscribe('providers');
Meteor.subscribe('counties');

var Counties  = new Mongo.Collection('counties'),

// Providers cursor
providers,

// Map handler
map = {},

// Initialize Google Maps API
initialize = function () {
    // Map Initialization function
    var initialize = function () {
        var mapElement = document.querySelector('#mapCanvas'),

        // Map options
        options = {
            scrollwheel : false,
            zoom        : 12,
            center      : new google.maps.LatLng(43.1, -89.4),
            zoomControl : true,
            minZoom     : 6,
            maxZoom     : 13,
            streetViewControl: false,
            zoomControlOptions: {
                style: 3
            },
        };

        // Map instance
        map = new google.maps.Map(mapElement, options);

       //var ctaLayer = new google.maps.KmlLayer({ url: 'data/wisconsin_counties.kml'});
        //ctaLayer.setMap(map);

        //Map Options
        map.set('styles', [
            {
                "featureType": "poi",
                "elementType": "labels",
                "stylers": [{ "visibility": "off" }]
            },
            {
                "stylers": [
                    { "gamma": 0.78 },
                    { "lightness": 5 },
                    { "saturation": 22 }
                ]
            },
            {
                "featureType": "water",
                "stylers": [
                    { "hue": "#00ddff" },
                    { "color": "#04648d" },
                    { "saturation": -23 },
                    { "lightness": 17 },
                    { "gamma": 1.94 }
                ]
            }
        ]);

        // Wait for collection to become available before acting on it
        Deps.autorun(function (c) {
            // Get all providers' IDs, names, and coordinates
            providers = Providers.find({}, { name: 1, coordinates: 1});

            // If collection not ready, try again
            if ( !providers.count() ) return;

            // Create map markers for each provider
            providers.forEach(function (provider) {
                var marker = new google.maps.Marker({
                    position : new google.maps.LatLng(provider.coordinates[0],
                            provider.coordinates[1]),
                    icon     : createPin('#00b7c5','#004146'),
                    animation: google.maps.Animation.DROP,
                    title    : provider.name,
                    id       : provider._id
                });

                // Add hover effect
                google.maps.event.addListener(marker, 'mouseover', mouseover);
                google.maps.event.addListener(marker, 'mouseout',  mouseout);

                // Display Label
                google.maps.event.addListener(marker, 'mouseover', displayLabel);

                // Add to map
                marker.setMap(map);

                //Click Marker
                marker.addListener('click', function() {
                    fullMap(false);
                    google.maps.event.trigger(map,'resize');
                    map.setZoom(12);
                    map.panTo(marker.getPosition());

                    // Show results if the result has an ID
                    if (this.id)
                        Session.set('currentProvider', Providers.findOne({ _id: this.id }));
                });
            });

            // Stop
            c.stop();
            var infoWindow = new google.maps.InfoWindow({map: map});
            // Geolocation
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    var closest,

                    // Get the distance from current location for each provider
                    providers = Providers.find({}, { coordinates: 1 }).map(function (provider) {
                        // Calculate distance
                        var distance = google.maps.geometry.spherical.computeDistanceBetween(
                            new google.maps.LatLng(position.coords.latitude,
                                position.coords.longitude),
                            new google.maps.LatLng(provider.coordinates[0],
                                provider.coordinates[1])
                        );

                        return { id: provider._id, distance: distance };
                    });

                    // Sort array
                    providers.sort(function (a, b) { return a.distance - b.distance; });

                    // Get closest provider
                    closest = Providers.findOne({ _id: providers[0].id });

                    // Center on it
                    map.panTo(new google.maps.LatLng(
                        closest.coordinates[0],
                        closest.coordinates[1]
                    ));

                    // Show results
                    Session.set('currentProvider', closest);
                }, function() {
                    handleLocationError(true, infoWindow, map.getCenter());
                });
            } else{
                handleLocationError(false, infoWindow, map.getCenter());
            }
        });

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
          document.getElementById("service-providers").classList.add("full-view");
          if (map.getZoom() > 0) map.setZoom(7);
          map.setCenter(new google.maps.LatLng(44.863579, -89.574563));
      }

        // Create a WCASA map marker
        (function () {
            var marker = new google.maps.Marker({
                position : new google.maps.LatLng(43.0346679, -89.4252416),
                icon     : createPin('#062131','##062131'),
                animation: google.maps.Animation.DROP,
                title    : 'WCASA'
            });

            // Display Label
            google.maps.event.addListener(marker, 'mouseover', displayLabel);
            google.maps.event.addListener(marker, 'mouseout',  hideLabel);

            // Add to map
            marker.setMap(map);
        })();

    },

    // Create SVG Marker Pin
    createPin = function (fillColor,strokeColor) {
        return {
            // SVG Path
            path: 'M 24,4.1C21.2,1.4,17.9,0,14,0c-3.9,0-7.2,1.4-9.9,4.1C1.4,6.9,0,10.2,0,14c0,2,0.3,3.6,0.9,4.9l10,21.2c0.3,0.6,0.7,1.1,1.3,1.4c0.6,0.3,1.2,0.5,1.9,0.5c0.7,0,1.3-0.2,1.9-0.5c0.6-0.3,1-0.8,1.3-1.4l10-21.2c0.6-1.3,0.9-2.9,0.9-4.9C28.1,10.2,26.7,6.9,24,4.1L24,4.1z M19,19c-1.4,1.4-3,2.1-5,2.1c-1.9,0-3.6-0.7-5-2.1C7.7,17.6,7,16,7,14c0-1.9,0.7-3.6,2.1-5c1.4-1.4,3-2.1,5-2.1c1.9,0,3.6,0.7,5,2.1c1.4,1.4,2.1,3,2.1,5C21.1,16,20.4,17.6,19,19L19,19z M19,19',

            // Attributes
            fillColor   : fillColor,
            fillOpacity : 1,
            scale       : 0.9,
            //shape     : shape,
            strokeWeight: 2,
            strokeColor : strokeColor,

            // Pin Position/Offset Controls
            size        : new google.maps.Size(29, 43),
            origin      : new google.maps.Point(0,0),
            anchor      : new google.maps.Point(14, 43)
        }
    },

    // Hover effects
    mouseover = function () {
        this.setIcon(createPin('#00cad9','#004146'), this);
    },
    mouseout = function () {
        this.setIcon(createPin('#00b7c5','#004146'), this);
    },

    // Display info label on hover
    displayLabel = function () {
        // Close any existing infowindow
        if (map.infowindow)
            map.infowindow.close();

        // Create new infowindow
        map.infowindow = new google.maps.InfoWindow({
            content: '
' + this.title + '
'
        });

        // Open new infowindow
        map.infowindow.open(this.get('map'), this);

    },

    // Create maps API script
    script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
        '&libraries=geometry&callback=initializeMap';
    document.body.appendChild(script);

    // Maps API will look for initialize script in global scope
    window.initializeMap = initialize;
},

// Helper for moving map based on provider locations
moveMap = function (county) {
    var providers = [], x = [], y = [];

    // Mutual Suspician
    county = '' + county;
    if (!county) throw new Error('Invalid county');

    // Get coordinates for all providers for that county
    providers = Providers.find({ counties: { $elemMatch: { $in: [county] }}},
        { coordinates: 1, name:1 }).map(function (provider) {
            // We only care about the coordinates
            return {
                coordinates: provider.coordinates,
                id: provider._id,
                name: provider.name
            };
    });

    // Calculate bounding box
    // Determine lowest and highest Lat values
    providers.sort(function (a, b) {
        return b.coordinates[0] - a.coordinates[0];
    });
    x = [ providers[0].coordinates[0], providers[providers.length - 1].coordinates[0] ];

    // Determine lowest and highest Lon values
    providers.sort(function (a, b) {
        return b.coordinates[1] - a.coordinates[1];
    });
    y = [ providers[0].coordinates[1], providers[providers.length - 1].coordinates[1] ];

    // Bounds
    map.fitBounds(new google.maps.LatLngBounds(
        new google.maps.LatLng( x[1], y[1] ), // Southwest
        new google.maps.LatLng( x[0], y[0] )  // to Northeast
    ));

    // If there was only one result, click on it for the user
    if (providers.length === 1){
        Session.set('currentProvider', Providers.findOne({ _id: providers[0].id }));
    } else{
        document.getElementById("service-providers").classList.add("full-view");
    }
},

// Setting the map view to full
fullMap = function (condition) {
    if (condition == true){
        document.getElementById("service-providers").classList.add("full-view");
        if (map.getZoom() > 0) map.setZoom(7);
        map.setCenter(new google.maps.LatLng(44.863579, -89.574563));
    } else{
        document.getElementById("service-providers").classList.remove("full-view");
    }
},

// Hide info label on mouseout
hideLabel = function () {
    if (map.infowindow)
        map.infowindow.close();
},

// Get X and Y Coordinates based on web mercator projection
getXY = function (lat, lon) {
    console.info('Meters per pixel', 156543.03392 * Math.cos(lat * Math.PI / 180)
        / Math.pow(2, 12));
    return [
        128 / Math.PI * Math.pow(2, 12) * (lon + Math.PI),
        128 / Math.PI * Math.pow(2, 12) * (Math.PI -
            Math.log( Math.tan( Math.PI / 4 + lat / 2 ) ))
    ];
},

// Get county from ZIP code number
getCounty = function (zip) {
    var county = '';

    // Mutual Suspicion
    if (!zip) throw new Error('No ZIP element?');

    // Get county
    county = Counties.findOne({ zips:
        // Minimongo doesn't support $eq for some reason
        { $elemMatch: { $in: [zip] } }});

    // Now get providers that support that county
    moveMap(county.name);
},

outlineCounty = function () {
    //County Data
    var ctaLayer = new google.maps.KmlLayer({
        url: '/packages/$USER_$PACKAGENAME/lib/client/data/wisconsin_counties.kml',
        map: map
    });
    ctaLayer.setMap(map);
};

// On proper initialization (meteor sucks at handling race conditions)
//Template.body.onRendered(function () {
    Template.providers.onRendered(initialize);
//});

Template.providers.events({
    // County drop-down list
    'change #county': function (event) {
        openDetails();
        var name = event.target.value;

        // Mutual Suspician
        if (!name) throw new Error('Invalid county');

        moveMap(name);
        outlineCounty();
        // Close search field
        closeMapSearch();
        document.body.classList.remove('providersListOpen');
    },
    'click .mapView': function (event) {
        event.stopPropagation();event.preventDefault();
        document.body.classList.remove('providersListOpen');
        document.getElementById("service-providers").classList.add("full-view");
        google.maps.event.trigger(map,'resize');
        hideLabel();
        fullMap(true);
    },
    'click .fullMap': function (event){
        event.stopPropagation();event.preventDefault();
        document.body.classList.remove('providersListOpen');
        document.getElementById("service-providers").classList.add("full-view");
        google.maps.event.trigger(map,'resize');
        hideLabel();
        fullMap(true);
    },
    // Clicking ZIP Code GO button
    'click #zip + .submit': function (event) {
        // Stop form submission
        event.preventDefault();

        getCounty(event.currentTarget.parentElement.querySelector('#zip').value);

        // Close search field
        closeMapSearch();
        openDetails();
    },
    // Reaching 5 digits
    'keyup #zip': function (event) {
        if (event.currentTarget.value.length === 5) {
            openDetails();
            getCounty(event.currentTarget.value);
            document.body.classList.remove('providersListOpen');
            // Close search field
            closeMapSearch();
            google.maps.event.trigger(map,'resize');
        }
    }
});

/**
 * Follow Provider link to pin on map
 * @method
 *   @param {$.Event} event - jQuery event passed to handler
 */
Template.providerListViewItem.events({
    'click div.pad': function (event) {
        if ( !(event instanceof $.Event) ) return;
        event.stopPropagation();
        event.preventDefault();

        // Update info section
        Session.set('currentProvider', Providers.findOne({ _id: this._id }));

        // Update map
        map.panTo(new google.maps.LatLng(
            this.coordinates[0],
            this.coordinates[1]
        ));

        // Close providers section
        document.body.classList.remove('providersListOpen');
    }
});
<commit_msg>Added county line support. Fixes Issue #105.<commit_after>// Subscribe to Provider data
Meteor.subscribe('providers');
Meteor.subscribe('counties');

var Counties  = new Mongo.Collection('counties'),

// Providers cursor
providers,

// Map handler
map = {},

// Initialize Google Maps API
initialize = function () {
    // Map Initialization function
    var initialize = function () {
        var mapElement = document.querySelector('#mapCanvas'),

        // Map options
        options = {
            scrollwheel : false,
            zoom        : 12,
            center      : new google.maps.LatLng(43.1, -89.4),
            zoomControl : true,
            minZoom     : 6,
            maxZoom     : 13,
            streetViewControl: false,
            zoomControlOptions: {
                style: 3
            },
        };

        // Map instance
        map = new google.maps.Map(mapElement, options);

        // County Layer
        var countyLayer = new geoXML3.parser({map: map});
        //countyLayer.parse('/packages/thriver_maps/lib/client/data/wisconsin_counties.kml');

        //Map Options
        map.set('styles', [
            {
                "featureType": "poi",
                "elementType": "labels",
                "stylers": [{ "visibility": "off" }]
            },
            {
                "stylers": [
                    { "gamma": 0.78 },
                    { "lightness": 5 },
                    { "saturation": 22 }
                ]
            },
            {
                "featureType": "water",
                "stylers": [
                    { "hue": "#00ddff" },
                    { "color": "#04648d" },
                    { "saturation": -23 },
                    { "lightness": 17 },
                    { "gamma": 1.94 }
                ]
            }
        ]);

        // Wait for collection to become available before acting on it
        Deps.autorun(function (c) {
            // Get all providers' IDs, names, and coordinates
            providers = Providers.find({}, { name: 1, coordinates: 1});

            // If collection not ready, try again
            if ( !providers.count() ) return;

            // Create map markers for each provider
            providers.forEach(function (provider) {
                var marker = new google.maps.Marker({
                    position : new google.maps.LatLng(provider.coordinates[0],
                            provider.coordinates[1]),
                    icon     : createPin('#00b7c5','#004146'),
                    animation: google.maps.Animation.DROP,
                    title    : provider.name,
                    id       : provider._id
                });

                // Add hover effect
                google.maps.event.addListener(marker, 'mouseover', mouseover);
                google.maps.event.addListener(marker, 'mouseout',  mouseout);

                // Display Label
                google.maps.event.addListener(marker, 'mouseover', displayLabel);

                // Add to map
                marker.setMap(map);

                //Click Marker
                marker.addListener('click', function() {
                    fullMap(false);
                    google.maps.event.trigger(map,'resize');
                    map.setZoom(12);
                    map.panTo(marker.getPosition());

                    // Show results if the result has an ID
                    if (this.id)
                        Session.set('currentProvider', Providers.findOne({ _id: this.id }));
                });
            });

            // Stop
            c.stop();
            var infoWindow = new google.maps.InfoWindow({map: map});
            // Geolocation
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    var closest,

                    // Get the distance from current location for each provider
                    providers = Providers.find({}, { coordinates: 1 }).map(function (provider) {
                        // Calculate distance
                        var distance = google.maps.geometry.spherical.computeDistanceBetween(
                            new google.maps.LatLng(position.coords.latitude,
                                position.coords.longitude),
                            new google.maps.LatLng(provider.coordinates[0],
                                provider.coordinates[1])
                        );

                        return { id: provider._id, distance: distance };
                    });

                    // Sort array
                    providers.sort(function (a, b) { return a.distance - b.distance; });

                    // Get closest provider
                    closest = Providers.findOne({ _id: providers[0].id });

                    // Center on it
                    map.panTo(new google.maps.LatLng(
                        closest.coordinates[0],
                        closest.coordinates[1]
                    ));

                    // Show results
                    Session.set('currentProvider', closest);
                }, function() {
                    handleLocationError(true, infoWindow, map.getCenter());
                });
            } else{
                handleLocationError(false, infoWindow, map.getCenter());
            }
        });

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
          document.getElementById("service-providers").classList.add("full-view");
          if (map.getZoom() > 0) map.setZoom(7);
          map.setCenter(new google.maps.LatLng(44.863579, -89.574563));
      }

        // Create a WCASA map marker
        (function () {
            var marker = new google.maps.Marker({
                position : new google.maps.LatLng(43.0346679, -89.4252416),
                icon     : createPin('#062131','##062131'),
                animation: google.maps.Animation.DROP,
                title    : 'WCASA'
            });

            // Display Label
            google.maps.event.addListener(marker, 'mouseover', displayLabel);
            google.maps.event.addListener(marker, 'mouseout',  hideLabel);

            // Add to map
            marker.setMap(map);
        })();

    },

    // Create SVG Marker Pin
    createPin = function (fillColor,strokeColor) {
        return {
            // SVG Path
            path: 'M 24,4.1C21.2,1.4,17.9,0,14,0c-3.9,0-7.2,1.4-9.9,4.1C1.4,6.9,0,10.2,0,14c0,2,0.3,3.6,0.9,4.9l10,21.2c0.3,0.6,0.7,1.1,1.3,1.4c0.6,0.3,1.2,0.5,1.9,0.5c0.7,0,1.3-0.2,1.9-0.5c0.6-0.3,1-0.8,1.3-1.4l10-21.2c0.6-1.3,0.9-2.9,0.9-4.9C28.1,10.2,26.7,6.9,24,4.1L24,4.1z M19,19c-1.4,1.4-3,2.1-5,2.1c-1.9,0-3.6-0.7-5-2.1C7.7,17.6,7,16,7,14c0-1.9,0.7-3.6,2.1-5c1.4-1.4,3-2.1,5-2.1c1.9,0,3.6,0.7,5,2.1c1.4,1.4,2.1,3,2.1,5C21.1,16,20.4,17.6,19,19L19,19z M19,19',

            // Attributes
            fillColor   : fillColor,
            fillOpacity : 1,
            scale       : 0.9,
            //shape     : shape,
            strokeWeight: 2,
            strokeColor : strokeColor,

            // Pin Position/Offset Controls
            size        : new google.maps.Size(29, 43),
            origin      : new google.maps.Point(0,0),
            anchor      : new google.maps.Point(14, 43)
        }
    },

    // Hover effects
    mouseover = function () {
        this.setIcon(createPin('#00cad9','#004146'), this);
    },
    mouseout = function () {
        this.setIcon(createPin('#00b7c5','#004146'), this);
    },

    // Display info label on hover
    displayLabel = function () {
        // Close any existing infowindow
        if (map.infowindow)
            map.infowindow.close();

        // Create new infowindow
        map.infowindow = new google.maps.InfoWindow({
            content: '
' + this.title + '
'
        });

        // Open new infowindow
        map.infowindow.open(this.get('map'), this);

    },

    // Create maps API script
    script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
        '&libraries=geometry&callback=initializeMap';
    document.body.appendChild(script);

    // Maps API will look for initialize script in global scope
    window.initializeMap = initialize;
},

// Helper for moving map based on provider locations
moveMap = function (county) {
    var providers = [], x = [], y = [];

    // Mutual Suspician
    county = '' + county;
    if (!county) throw new Error('Invalid county');

    // Get coordinates for all providers for that county
    providers = Providers.find({ counties: { $elemMatch: { $in: [county] }}},
        { coordinates: 1, name:1 }).map(function (provider) {
            // We only care about the coordinates
            return {
                coordinates: provider.coordinates,
                id: provider._id,
                name: provider.name
            };
    });

    // Calculate bounding box
    // Determine lowest and highest Lat values
    providers.sort(function (a, b) {
        return b.coordinates[0] - a.coordinates[0];
    });
    x = [ providers[0].coordinates[0], providers[providers.length - 1].coordinates[0] ];

    // Determine lowest and highest Lon values
    providers.sort(function (a, b) {
        return b.coordinates[1] - a.coordinates[1];
    });
    y = [ providers[0].coordinates[1], providers[providers.length - 1].coordinates[1] ];

    // Bounds
    map.fitBounds(new google.maps.LatLngBounds(
        new google.maps.LatLng( x[1], y[1] ), // Southwest
        new google.maps.LatLng( x[0], y[0] )  // to Northeast
    ));

    // If there was only one result, click on it for the user
    if (providers.length === 1){
        Session.set('currentProvider', Providers.findOne({ _id: providers[0].id }));
    } else{
        document.getElementById("service-providers").classList.add("full-view");
    }
},

// Setting the map view to full
fullMap = function (condition) {
    if (condition == true){
        document.getElementById("service-providers").classList.add("full-view");
        if (map.getZoom() > 0) map.setZoom(7);
        map.setCenter(new google.maps.LatLng(44.863579, -89.574563));
    } else{
        document.getElementById("service-providers").classList.remove("full-view");
    }
},

// Hide info label on mouseout
hideLabel = function () {
    if (map.infowindow)
        map.infowindow.close();
},

// Get X and Y Coordinates based on web mercator projection
getXY = function (lat, lon) {
    console.info('Meters per pixel', 156543.03392 * Math.cos(lat * Math.PI / 180)
        / Math.pow(2, 12));
    return [
        128 / Math.PI * Math.pow(2, 12) * (lon + Math.PI),
        128 / Math.PI * Math.pow(2, 12) * (Math.PI -
            Math.log( Math.tan( Math.PI / 4 + lat / 2 ) ))
    ];
},

// Get county from ZIP code number
getCounty = function (zip) {
    var county = '';

    // Mutual Suspicion
    if (!zip) throw new Error('No ZIP element?');

    // Get county
    county = Counties.findOne({ zips:
        // Minimongo doesn't support $eq for some reason
        { $elemMatch: { $in: [zip] } }});

    // Now get providers that support that county
    moveMap(county.name);
},

outlineCounty = function () {
    //County Data
    var ctaLayer = new google.maps.KmlLayer({
        url: '/packages/$USER_$PACKAGENAME/lib/client/data/wisconsin_counties.kml',
        map: map
    });
    ctaLayer.setMap(map);
};

// On proper initialization (meteor sucks at handling race conditions)
//Template.body.onRendered(function () {
    Template.providers.onRendered(initialize);
//});

Template.providers.events({
    // County drop-down list
    'change #county': function (event) {
        openDetails();
        var name = event.target.value;

        // Mutual Suspician
        if (!name) throw new Error('Invalid county');

        moveMap(name);
        outlineCounty();
        // Close search field
        closeMapSearch();
        document.body.classList.remove('providersListOpen');
    },
    'click .mapView': function (event) {
        event.stopPropagation();event.preventDefault();
        document.body.classList.remove('providersListOpen');
        document.getElementById("service-providers").classList.add("full-view");
        google.maps.event.trigger(map,'resize');
        hideLabel();
        fullMap(true);
    },
    'click .fullMap': function (event){
        event.stopPropagation();event.preventDefault();
        document.body.classList.remove('providersListOpen');
        document.getElementById("service-providers").classList.add("full-view");
        google.maps.event.trigger(map,'resize');
        hideLabel();
        fullMap(true);
    },
    // Clicking ZIP Code GO button
    'click #zip + .submit': function (event) {
        // Stop form submission
        event.preventDefault();

        getCounty(event.currentTarget.parentElement.querySelector('#zip').value);

        // Close search field
        closeMapSearch();
        openDetails();
    },
    // Reaching 5 digits
    'keyup #zip': function (event) {
        if (event.currentTarget.value.length === 5) {
            openDetails();
            getCounty(event.currentTarget.value);
            document.body.classList.remove('providersListOpen');
            // Close search field
            closeMapSearch();
            google.maps.event.trigger(map,'resize');
        }
    }
});

/**
 * Follow Provider link to pin on map
 * @method
 *   @param {$.Event} event - jQuery event passed to handler
 */
Template.providerListViewItem.events({
    'click div.pad': function (event) {
        if ( !(event instanceof $.Event) ) return;
        event.stopPropagation();
        event.preventDefault();

        // Update info section
        Session.set('currentProvider', Providers.findOne({ _id: this._id }));

        // Update map
        map.panTo(new google.maps.LatLng(
            this.coordinates[0],
            this.coordinates[1]
        ));

        // Close providers section
        document.body.classList.remove('providersListOpen');
    }
});
<|endoftext|>


<commit_before>var assert = require("chai").assert;
var util = require("./util");

describe("Deployments", function() {
  var Example;
  var web3;
  var providerOptions = { vmErrorsOnRPCResponse: false };

  before(async function() {
    this.timeout(20000);

    Example = await util.createExample();

    const result = await util.setUpProvider(Example, providerOptions);
    web3 = result.web3;
  });

  describe(".at() [ @geth ]", function() {
    it("should return a usable duplicate instance with at()", async function() {
      const example = await Example.new(1);
      const copy = await Example.at(example.address);
      let value = await copy.value.call();

      // This value was set during Example's initialization;
      assert.equal(parseInt(value), 1, "Starting value should be 1");

      // Set via example
      await example.setValue(5);

      // Retrieve set value from copy
      value = await copy.value.call();
      assert.equal(parseInt(value), 5, "Ending value should be five");
    });
  });

  describe(".new(): success [ @geth ]", function() {
    it("should set the tx hash of the new contract instance", async function() {
      const example = await Example.new(1);

      assert(example.transactionHash, "transactionHash should be non-empty");
    });

    it("should estimate gas cost of deployment", async function() {
      const estimate = await Example.new.estimateGas(5);

      assert.isNumber(estimate, "Estimate should be a number");
      assert.isAbove(estimate, 0, "Estimate should be non-zero");
    });

    it("should emit the tx hash & set it on the resolved instance", async function() {
      let txHash;
      const example = await Example.new(1).on(
        "transactionHash",
        hash => (txHash = hash)
      );

      assert.equal(
        example.transactionHash,
        txHash,
        "contract tx hash should be emitted tx hash"
      );
    });

    it("should fire the confirmations event handler repeatedly", function(done) {
      Example.new(5)
        .on("confirmation", function(number, receipt) {
          if (number === 3) {
            assert(receipt.status === true);
            this.removeAllListeners();
            done();
          }
        })
        .then(async instance => {
          await instance.setValue(5);
          await instance.setValue(10);
          await instance.setValue(15);
        });
    });
  });

  describe(".new(): errors [ @geth ]", function() {
    it("should reject on OOG", async function() {
      try {
        await Example.new(1, { gas: 10 });
        assert.fail();
      } catch (error) {
        const errorCorrect =
          error.message.includes("exceeds gas limit") ||
          error.message.includes("intrinsic gas too low");

        assert(errorCorrect, "Should OOG");
      }
    });

    it("should emit OOG errors", function(done) {
      Example.new(1, { gas: 10 })
        .on("error", error => {
          const errorCorrect =
            error.message.includes("exceeds gas limit") ||
            error.message.includes("intrinsic gas too low");

          assert(errorCorrect, "Should OOG");
          done();
        })
        .catch(() => null);
    });

    it("Errors with gas limit error if constructor reverts", async function() {
      try {
        await Example.new(13); // 13 fails a require gate
        assert.fail();
      } catch (e) {
        const errorCorrect =
          e.message.includes("exceeds gas limit") ||
          e.message.includes("intrinsic gas too low");

        assert(errorCorrect, "Expected gas limit error");
        assert(e.receipt === undefined, "Expected no receipt");
      }
    });

    // This example contains a reason string when run with ganache but no
    // reason strings when run vs geth.
    it("Handles absence of reason string gracefully", async function() {
      try {
        await Example.new(2001); // 2001 fails a require gate
        assert.fail();
      } catch (e) {
        const errorCorrect =
          e.message.includes("exceeds gas limit") ||
          e.message.includes("intrinsic gas too low");

        assert(errorCorrect, "Expected gas limit error");
        assert(e.receipt === undefined, "Expected no receipt");
      }
    });

    // NB: constructor (?) message is unhelpful:
    // "Error: Invalid number of parameters for "undefined". Got 2 expected 1!""
    it("should reject with web3 validation errors (constructor params)", async function() {
      try {
        await Example.new(25, 25);
        assert.fail();
      } catch (e) {
        assert(
          e.message.includes("Invalid number of parameters"),
          "web3 should validate"
        );
      }
    });
  });

  describe(".new(): revert with reasonstring (ganache only)", function() {
    it("should reject with reason string on revert", async function() {
      try {
        await Example.new(2001); // Triggers error with a normal reason string
        assert.fail();
      } catch (error) {
        assert(error.message.includes("check your gas limit"));
        assert(error.message.includes("reasonstring"));
        assert(error.receipt === undefined, "Expected no receipt");
        assert(error.reason === "reasonstring");
      }
    });

    it("should reject with long reason string on revert", async function() {
      try {
        await Example.new(20001); // Triggers error with a long reason string
        assert.fail();
      } catch (error) {
        assert(error.message.includes("check your gas limit"));
        assert(
          error.message.includes(
            "solidity storage is a fun lesson in endianness"
          )
        );
        assert(error.receipt === undefined, "Expected no receipt");
        assert(
          error.reason === "solidity storage is a fun lesson in endianness"
        );
      }
    });
  });

  describe("pre-flight gas estimation", function() {
    it("should automatically fund a deployment [ @geth ]", async function() {
      const estimate = await Example.new.estimateGas(1);
      const defaults = Example.defaults;

      assert(defaults.gas === undefined, "Should not have a gas default");
      assert(estimate > 90000, "Should be more expensive than default tx");

      await Example.new(1);
    });

    it("should be possible to turn gas estimation on and off", async function() {
      Example.autoGas = false;

      try {
        await Example.new(1);
        assert.fail();
      } catch (err) {
        assert(err.message.includes("exceeds gas limit"), "Should OOG");
      }

      Example.autoGas = true;
      await Example.new(1);

      const estimate = await Example.new.estimateGas(1);

      Example.autoGas = false;
      await Example.new(1, { gas: estimate });

      Example.autoGas = true;
    });

    // Constructor in this test consumes ~6437823 (ganache) vs blockLimit of 6721975.
    it("should not multiply past the blockLimit", async function() {
      this.timeout(50000);
      let iterations = 1000; // # of times to set a uint in a loop, consuming gas.

      const estimate = await Example.new.estimateGas(iterations);
      const block = await web3.eth.getBlock("latest");
      const multiplier = Example.gasMultiplier;

      assert(multiplier === 1.25, "Multiplier should be initialized to 1.25");
      assert(
        multiplier * estimate > block.gasLimit,
        "Multiplied estimate should be too high"
      );
      assert(estimate < block.gasLimit, "Estimate on it's own should be ok");

      await Example.new(iterations);
    });
  });

  describe("web3 timeout overrides", function() {
    it("should override 50 blocks err / return a usable instance", async function() {
      this.timeout(50000);

      // Mock web3 non-response, fire error @ block 50, resolve receipt @ block 52.
      const tempSendTransaction = Example.web3.eth.sendTransaction;
      const tempGetTransactionReceipt = Example.web3.eth.getTransactionReceipt;

      Example.web3.eth.sendTransaction = util.fakeSendTransaction;
      Example.web3.eth.getTransactionReceipt = util.fakeNoReceipt;
      Example.timeoutBlocks = 52;

      const example = await Example.new(1).on(
        "transactionHash",
        async function() {
          for (var i = 1; i < 50; i++) {
            await util.evm_mine();
          }
          await util.fakeReject();
          await util.evm_mine();
          await util.evm_mine();
          Example.web3.eth.getTransactionReceipt = util.fakeGotReceipt;
          await util.evm_mine();
        }
      );

      // Restore web3
      Example.web3.eth.sendTransaction = tempSendTransaction;
      Example.web3.eth.getTransactionReceipt = tempGetTransactionReceipt;

      await example.setValue(77);
      const newValue = await example.value();
      assert.equal(
        newValue,
        77,
        "Should have returned a usable contract instance"
      );
    });
  });
});
<commit_msg>update gas limit err msg<commit_after>var assert = require("chai").assert;
var util = require("./util");

describe("Deployments", function() {
  var Example;
  var web3;
  var providerOptions = { vmErrorsOnRPCResponse: false };

  before(async function() {
    this.timeout(20000);

    Example = await util.createExample();

    const result = await util.setUpProvider(Example, providerOptions);
    web3 = result.web3;
  });

  describe(".at() [ @geth ]", function() {
    it("should return a usable duplicate instance with at()", async function() {
      const example = await Example.new(1);
      const copy = await Example.at(example.address);
      let value = await copy.value.call();

      // This value was set during Example's initialization;
      assert.equal(parseInt(value), 1, "Starting value should be 1");

      // Set via example
      await example.setValue(5);

      // Retrieve set value from copy
      value = await copy.value.call();
      assert.equal(parseInt(value), 5, "Ending value should be five");
    });
  });

  describe(".new(): success [ @geth ]", function() {
    it("should set the tx hash of the new contract instance", async function() {
      const example = await Example.new(1);

      assert(example.transactionHash, "transactionHash should be non-empty");
    });

    it("should estimate gas cost of deployment", async function() {
      const estimate = await Example.new.estimateGas(5);

      assert.isNumber(estimate, "Estimate should be a number");
      assert.isAbove(estimate, 0, "Estimate should be non-zero");
    });

    it("should emit the tx hash & set it on the resolved instance", async function() {
      let txHash;
      const example = await Example.new(1).on(
        "transactionHash",
        hash => (txHash = hash)
      );

      assert.equal(
        example.transactionHash,
        txHash,
        "contract tx hash should be emitted tx hash"
      );
    });

    it("should fire the confirmations event handler repeatedly", function(done) {
      Example.new(5)
        .on("confirmation", function(number, receipt) {
          if (number === 3) {
            assert(receipt.status === true);
            this.removeAllListeners();
            done();
          }
        })
        .then(async instance => {
          await instance.setValue(5);
          await instance.setValue(10);
          await instance.setValue(15);
        });
    });
  });

  describe(".new(): errors [ @geth ]", function() {
    it("should reject on OOG", async function() {
      try {
        await Example.new(1, { gas: 10 });
        assert.fail();
      } catch (error) {
        const errorCorrect =
          error.message.includes("exceeds gas limit") ||
          error.message.includes("intrinsic gas too low");

        assert(errorCorrect, "Should OOG");
      }
    });

    it("should emit OOG errors", function(done) {
      Example.new(1, { gas: 10 })
        .on("error", error => {
          const errorCorrect =
            error.message.includes("exceeds gas limit") ||
            error.message.includes("intrinsic gas too low");

          assert(errorCorrect, "Should OOG");
          done();
        })
        .catch(() => null);
    });

    it("Errors with gas limit error if constructor reverts", async function() {
      try {
        await Example.new(13); // 13 fails a require gate
        assert.fail();
      } catch (e) {
        const errorCorrect =
          e.message.includes("gas required exceeds allowance") ||
          e.message.includes("intrinsic gas too low");

        assert(errorCorrect, "Expected gas limit error");
        assert(e.receipt === undefined, "Expected no receipt");
      }
    });

    // This example contains a reason string when run with ganache but no
    // reason strings when run vs geth.
    it("Handles absence of reason string gracefully", async function() {
      try {
        await Example.new(2001); // 2001 fails a require gate
        assert.fail();
      } catch (e) {
        const errorCorrect =
          e.message.includes("gas required exceeds allowance") ||
          e.message.includes("intrinsic gas too low");

        assert(errorCorrect, "Expected gas limit error");
        assert(e.receipt === undefined, "Expected no receipt");
      }
    });

    // NB: constructor (?) message is unhelpful:
    // "Error: Invalid number of parameters for "undefined". Got 2 expected 1!""
    it("should reject with web3 validation errors (constructor params)", async function() {
      try {
        await Example.new(25, 25);
        assert.fail();
      } catch (e) {
        assert(
          e.message.includes("Invalid number of parameters"),
          "web3 should validate"
        );
      }
    });
  });

  describe(".new(): revert with reasonstring (ganache only)", function() {
    it("should reject with reason string on revert", async function() {
      try {
        await Example.new(2001); // Triggers error with a normal reason string
        assert.fail();
      } catch (error) {
        assert(error.message.includes("check your gas limit"));
        assert(error.message.includes("reasonstring"));
        assert(error.receipt === undefined, "Expected no receipt");
        assert(error.reason === "reasonstring");
      }
    });

    it("should reject with long reason string on revert", async function() {
      try {
        await Example.new(20001); // Triggers error with a long reason string
        assert.fail();
      } catch (error) {
        assert(error.message.includes("check your gas limit"));
        assert(
          error.message.includes(
            "solidity storage is a fun lesson in endianness"
          )
        );
        assert(error.receipt === undefined, "Expected no receipt");
        assert(
          error.reason === "solidity storage is a fun lesson in endianness"
        );
      }
    });
  });

  describe("pre-flight gas estimation", function() {
    it("should automatically fund a deployment [ @geth ]", async function() {
      const estimate = await Example.new.estimateGas(1);
      const defaults = Example.defaults;

      assert(defaults.gas === undefined, "Should not have a gas default");
      assert(estimate > 90000, "Should be more expensive than default tx");

      await Example.new(1);
    });

    it("should be possible to turn gas estimation on and off", async function() {
      Example.autoGas = false;

      try {
        await Example.new(1);
        assert.fail();
      } catch (err) {
        assert(err.message.includes("exceeds gas limit"), "Should OOG");
      }

      Example.autoGas = true;
      await Example.new(1);

      const estimate = await Example.new.estimateGas(1);

      Example.autoGas = false;
      await Example.new(1, { gas: estimate });

      Example.autoGas = true;
    });

    // Constructor in this test consumes ~6437823 (ganache) vs blockLimit of 6721975.
    it("should not multiply past the blockLimit", async function() {
      this.timeout(50000);
      let iterations = 1000; // # of times to set a uint in a loop, consuming gas.

      const estimate = await Example.new.estimateGas(iterations);
      const block = await web3.eth.getBlock("latest");
      const multiplier = Example.gasMultiplier;

      assert(multiplier === 1.25, "Multiplier should be initialized to 1.25");
      assert(
        multiplier * estimate > block.gasLimit,
        "Multiplied estimate should be too high"
      );
      assert(estimate < block.gasLimit, "Estimate on it's own should be ok");

      await Example.new(iterations);
    });
  });

  describe("web3 timeout overrides", function() {
    it("should override 50 blocks err / return a usable instance", async function() {
      this.timeout(50000);

      // Mock web3 non-response, fire error @ block 50, resolve receipt @ block 52.
      const tempSendTransaction = Example.web3.eth.sendTransaction;
      const tempGetTransactionReceipt = Example.web3.eth.getTransactionReceipt;

      Example.web3.eth.sendTransaction = util.fakeSendTransaction;
      Example.web3.eth.getTransactionReceipt = util.fakeNoReceipt;
      Example.timeoutBlocks = 52;

      const example = await Example.new(1).on(
        "transactionHash",
        async function() {
          for (var i = 1; i < 50; i++) {
            await util.evm_mine();
          }
          await util.fakeReject();
          await util.evm_mine();
          await util.evm_mine();
          Example.web3.eth.getTransactionReceipt = util.fakeGotReceipt;
          await util.evm_mine();
        }
      );

      // Restore web3
      Example.web3.eth.sendTransaction = tempSendTransaction;
      Example.web3.eth.getTransactionReceipt = tempGetTransactionReceipt;

      await example.setValue(77);
      const newValue = await example.value();
      assert.equal(
        newValue,
        77,
        "Should have returned a usable contract instance"
      );
    });
  });
});
<|endoftext|>


<commit_before>var ModuleTestREPOSITORY_NAME = (function(global) {

var _isNodeOrNodeWebKit = !!global.global;
var _runOnNodeWebKit =  _isNodeOrNodeWebKit &&  /native/.test(setTimeout);
var _runOnNode       =  _isNodeOrNodeWebKit && !/native/.test(setTimeout);
var _runOnWorker     = !_isNodeOrNodeWebKit && "WorkerLocation" in global;
var _runOnBrowser    = !_isNodeOrNodeWebKit && "document" in global;

var test = new Test("REPOSITORY_NAME", {
        disable:    false, // disable all tests.
        browser:    true,  // enable browser test.
        worker:     true,  // enable worker test.
        node:       true,  // enable node test.
        nw:         true,  // enable nw.js test.
        button:     true,  // show button.
        both:       true,  // test the primary and secondary modules.
        ignoreError:false, // ignore error.
    }).add([
        testREPOSITORY_NAME_value,
        testREPOSITORY_NAME_concat,
        testREPOSITORY_NAME_concat$,
    ]);

if (_runOnBrowser || _runOnNodeWebKit) {
    //test.add([]);
} else if (_runOnWorker) {
    //test.add([]);
} else if (_runOnNode) {
    //test.add([]);
}

return test.run().clone();

function testREPOSITORY_NAME_value(test, pass, miss) {

    var instance = new REPOSITORY_NAME("a");

    if (instance.value === "a") {
        instance.value = "b";

        if (instance.value === "b") {
            test.done(pass());
            return;
        }
    }
    test.done(miss());
}

function testREPOSITORY_NAME_concat(test, pass, miss) {

    var result = {
            0: new REPOSITORY_NAME(   ).concat("a") === "a", // true
            1: new REPOSITORY_NAME("b").concat("b") === "bb" // true
        };

    if (/false/.test(JSON.stringify(result, null, 2))) {
        test.done(miss());
    } else {
        test.done(pass());
    }
}

function testREPOSITORY_NAME_concat$(test, pass, miss) {

    var result = {
            0: new REPOSITORY_NAME(   ).concat$("a").value === "a", // true
            1: new REPOSITORY_NAME("b").concat$("b").value === "bb" // true
        };

    if (/false/.test(JSON.stringify(result, null, 2))) {
        test.done(miss());
    } else {
        test.done(pass());
    }
}

})(WEBMODULE_IDIOM);

<commit_msg>cleanup<commit_after>var ModuleTestREPOSITORY_NAME = (function(global) {

var _isNodeOrNodeWebKit = !!global.global;
var _runOnNodeWebKit =  _isNodeOrNodeWebKit &&  /native/.test(setTimeout);
var _runOnNode       =  _isNodeOrNodeWebKit && !/native/.test(setTimeout);
var _runOnWorker     = !_isNodeOrNodeWebKit && "WorkerLocation" in global;
var _runOnBrowser    = !_isNodeOrNodeWebKit && "document" in global;

var test = new Test("REPOSITORY_NAME", {
        disable:    false, // disable all tests.
        browser:    true,  // enable browser test.
        worker:     true,  // enable worker test.
        node:       true,  // enable node test.
        nw:         true,  // enable nw.js test.
        button:     true,  // show button.
        both:       true,  // test the primary and secondary modules.
        ignoreError:false, // ignore error.
    }).add([
        testREPOSITORY_NAME_value,
        testREPOSITORY_NAME_concat,
        testREPOSITORY_NAME_concat$,
    ]);

if (_runOnBrowser || _runOnNodeWebKit) {
    //test.add([]);
} else if (_runOnWorker) {
    //test.add([]);
} else if (_runOnNode) {
    //test.add([]);
}

// --- test cases ------------------------------------------
function testREPOSITORY_NAME_value(test, pass, miss) {

    var instance = new REPOSITORY_NAME("a");

    if (instance.value === "a") {
        instance.value = "b";

        if (instance.value === "b") {
            test.done(pass());
            return;
        }
    }
    test.done(miss());
}

function testREPOSITORY_NAME_concat(test, pass, miss) {

    var result = {
            0: new REPOSITORY_NAME(   ).concat("a") === "a", // true
            1: new REPOSITORY_NAME("b").concat("b") === "bb" // true
        };

    if (/false/.test(JSON.stringify(result, null, 2))) {
        test.done(miss());
    } else {
        test.done(pass());
    }
}

function testREPOSITORY_NAME_concat$(test, pass, miss) {

    var result = {
            0: new REPOSITORY_NAME(   ).concat$("a").value === "a", // true
            1: new REPOSITORY_NAME("b").concat$("b").value === "bb" // true
        };

    if (/false/.test(JSON.stringify(result, null, 2))) {
        test.done(miss());
    } else {
        test.done(pass());
    }
}

return test.run().clone();

})(WEBMODULE_IDIOM);

<|endoftext|>


<commit_before>import {Inject} from 'meteor/meteorhacks:inject-initial';
import { SyncedCron } from 'meteor/percolatestudio:synced-cron';
import { getSetting, registerSetting } from 'meteor/vulcan:lib';

import {
  populateComponentsApp,
  populateRoutesApp,
  initializeFragments
} from 'meteor/vulcan:lib';

registerSetting('mailUrl', null, 'The SMTP URL used to send out email');

if (getSetting('mailUrl')) {
  process.env.MAIL_URL = getSetting('mailUrl');
}

Meteor.startup(function() {
  if (typeof SyncedCron !== 'undefined') {
    SyncedCron.start();
  }

  // init the application components and routes, including components & routes from 3rd-party packages
  initializeFragments();
  populateComponentsApp();
  populateRoutesApp();
});

Inject.obj('serverTimezoneOffset', {offset: new Date().getTimezoneOffset()});
<commit_msg>revert start change<commit_after>import {Inject} from 'meteor/meteorhacks:inject-initial';
import { SyncedCron } from 'meteor/percolatestudio:synced-cron';
import { getSetting, registerSetting } from 'meteor/vulcan:lib';

registerSetting('mailUrl', null, 'The SMTP URL used to send out email');

if (getSetting('mailUrl')) {
  process.env.MAIL_URL = getSetting('mailUrl');
}

Meteor.startup(function() {
  if (typeof SyncedCron !== 'undefined') {
    SyncedCron.start();
  }
});

Inject.obj('serverTimezoneOffset', {offset: new Date().getTimezoneOffset()});
<|endoftext|>