<commit_before>function Robot(x, y, dir = 0)
{
	this.x = x;		//x coordinate
	this.y = y;		//y coordinate
	this.dir = dir;	//orientation in radians

	this.lastScan = Date.now();	//time of last sense in millis

	this.senseCircle = 10 + 5;
	this.lastMove = Date.now();	//last time change direction, in millis
	this.lastX = this.x;
	this.lastY = this.y;
	this.lastDir = this.dir;
	this.moveCD = Robot.randMoveCD();

	this.strideNoise = getStrideNoise();
	this.turnNoise = getTurnNoise();
	this.particles = new Array(getParticleCount());

	//generate initial particles
	for (var i = this.particles.length - 1; i >= 0; i--)
	{
		this.particles[i] = new Particle(this.x, this.y, this.dir, 1);
	}
}

Robot.size = 10;
Robot.sensorRadius = 150;
Robot.scanInterval = 2500;
Robot.stride = 1

Robot.randMoveCD = function()
{
	return 1500 + (gaussian() * 150);
}

let cos = Math.cos;
let sin = Math.sin;
let abs = Math.abs;

Robot.prototype.setStrideNoise = function(noise)
{
	this.strideNoise = noise;
}

Robot.prototype.setTurnNoise = function(noise)
{
	this.turnNoise = noise;
}

Robot.prototype.checkCollision = function()
{
	var dx = cos(this.dir);
	var dy = sin(this.dir);
	var offset = 0;

	var collide = false;
	if(this.x < Robot.size)
	{
		dx = abs(dx);
		collide = true;
	}else if(this.x+Robot.size >= canvas.width)
	{
		dx = -abs(dx);
		offset = Math.PI;
		collide = true;
	}else if(this.y < Robot.size)
	{
		dy = abs(dy);
		if(dx < 0)
			offset = Math.PI;
		collide = true;
	}else if(this.y+Robot.size >= canvas.height)
	{
		dy = -abs(dy);
		if(dx < 0)
			offset = Math.PI;
		collide = true;
	}
	if(collide)
	{
		this.dir = Math.atan(dy/dx) + offset;
		this.lastMove = Date.now();
		this.moveCD = Robot.randMoveCD();
	}
}

Robot.prototype.update = function()
{
	//Move the robot
	this.x += cos(this.dir) * Robot.stride;
	this.y += sin(this.dir) * Robot.stride;

	this.updateParticles();

	//Collision with a wall
	this.checkCollision();

	//Update robot's direction if necessary
	if(this.lastMove + this.moveCD <= Date.now())
	{

		this.dir += gaussian() * Math.PI;
		this.lastMove = Date.now();
		this.moveCD = Robot.randMoveCD();
	}

	//Update the sense circle
	if(this.senseCircle > Robot.sensorRadius)
	{
		if(Date.now() - this.lastScan >= Robot.scanInterval)
		{
			this.senseCircle %= Robot.sensorRadius;
			this.lastScan = Date.now();
		}
	}
	this.senseCircle += 1;
}

Robot.prototype.updateParticles = function()
{
	//This is how we simulate odometry....
	var dx = this.x - this.lastX;
	var dy = this.y - this.lastY;
	var dd = Math.sqrt(dx*dx + dy*dy);
	var da = this.dir - this.lastDir;

	//get noise parameters
	var strideNoise = this.strideNoise;
	var turnNoise = this.turnNoise;

	for (var i = this.particles.length - 1; i >= 0; i--)
	{
		//generate motion with gaussian noise
		var dist = dd + dd * gaussian() * strideNoise;
		var newDir = this.particles[i].dir + da + gaussian() * da * turnNoise
		this.particles[i].x += dist * cos(newDir);
		this.particles[i].y += dist * sin(newDir)
		this.particles[i].dir = newDir;
	}

	this.lastX = this.x;
	this.lastY = this.y;
	this.lastDir = this.dir;
}

Robot.prototype.draw = function(ctx)
{
	ctx.strokeStyle = 'black';
	if(Date.now() - this.lastMove < 200)
		ctx.strokeStyle = 'red';

	ctx.beginPath();

	var x = Math.floor(this.x);
	var y = Math.floor(this.y);

	//The robot's main circle
	ctx.arc(x, y, Robot.size, 0, Math.PI * 2, true);

	//draw a line to show Robot's orientation
	ctx.moveTo(x, y);
	ctx.lineTo(Math.floor(this.x + cos(this.dir) * Robot.size), Math.floor(this.y + sin(this.dir) * Robot.size));

	ctx.stroke();

	ctx.strokeStyle = 'rgba(0, 0, 255, '+ (1-this.senseCircle/Robot.sensorRadius) +')';
	ctx.beginPath();
	//draw Robot's sensing circle
	ctx.arc(x, y, this.senseCircle, 0, Math.PI*2, false);
	ctx.stroke();

	for (var i = this.particles.length - 1; i >= 0; i--)
	{
		var p = this.particles[i];
		p.draw(ctx);
	}
}<commit_msg>use atan2 to simplify code<commit_after>function Robot(x, y, dir = 0)
{
	this.x = x;		//x coordinate
	this.y = y;		//y coordinate
	this.dir = dir;	//orientation in radians

	this.lastScan = Date.now();	//time of last sense in millis

	this.senseCircle = 10 + 5;
	this.lastMove = Date.now();	//last time change direction, in millis
	this.lastX = this.x;
	this.lastY = this.y;
	this.lastDir = this.dir;
	this.moveCD = Robot.randMoveCD();

	this.strideNoise = getStrideNoise();
	this.turnNoise = getTurnNoise();
	this.particles = new Array(getParticleCount());

	//generate initial particles
	for (var i = this.particles.length - 1; i >= 0; i--)
	{
		this.particles[i] = new Particle(this.x, this.y, this.dir, 1);
	}
}

Robot.size = 10;
Robot.sensorRadius = 150;
Robot.scanInterval = 2500;
Robot.stride = 1

Robot.randMoveCD = function()
{
	return 1500 + (gaussian() * 150);
}

let cos = Math.cos;
let sin = Math.sin;
let abs = Math.abs;

Robot.prototype.setStrideNoise = function(noise)
{
	this.strideNoise = noise;
}

Robot.prototype.setTurnNoise = function(noise)
{
	this.turnNoise = noise;
}

Robot.prototype.checkCollision = function()
{
	var dx = cos(this.dir);
	var dy = sin(this.dir);

	var collide = false;
	if(this.x < Robot.size)
	{
		dx = abs(dx);
		collide = true;
	}else if(this.x+Robot.size >= canvas.width)
	{
		dx = -abs(dx);
		collide = true;
	}else if(this.y < Robot.size)
	{
		dy = abs(dy);
		collide = true;
	}else if(this.y+Robot.size >= canvas.height)
	{
		dy = -abs(dy);
		collide = true;
	}
	if(collide)
	{
		this.dir = Math.atan2(dy, dx);
		this.lastMove = Date.now();
		this.moveCD = Robot.randMoveCD();
	}
}

Robot.prototype.update = function()
{
	//Move the robot
	this.x += cos(this.dir) * Robot.stride;
	this.y += sin(this.dir) * Robot.stride;

	this.updateParticles();

	//Collision with a wall
	this.checkCollision();

	//Update robot's direction if necessary
	if(this.lastMove + this.moveCD <= Date.now())
	{

		this.dir += gaussian() * Math.PI;
		this.lastMove = Date.now();
		this.moveCD = Robot.randMoveCD();
	}

	//Update the sense circle
	if(this.senseCircle > Robot.sensorRadius)
	{
		if(Date.now() - this.lastScan >= Robot.scanInterval)
		{
			this.senseCircle %= Robot.sensorRadius;
			this.lastScan = Date.now();
		}
	}
	this.senseCircle += 1;
}

Robot.prototype.updateParticles = function()
{
	//This is how we simulate odometry....
	var dx = this.x - this.lastX;
	var dy = this.y - this.lastY;
	var dd = Math.sqrt(dx*dx + dy*dy);
	var da = this.dir - this.lastDir;

	//get noise parameters
	var strideNoise = this.strideNoise;
	var turnNoise = this.turnNoise;

	for (var i = this.particles.length - 1; i >= 0; i--)
	{
		//generate motion with gaussian noise
		var dist = dd + dd * gaussian() * strideNoise;
		var newDir = this.particles[i].dir + da + gaussian() * da * turnNoise
		this.particles[i].x += dist * cos(newDir);
		this.particles[i].y += dist * sin(newDir)
		this.particles[i].dir = newDir;
	}

	this.lastX = this.x;
	this.lastY = this.y;
	this.lastDir = this.dir;
}

Robot.prototype.draw = function(ctx)
{
	ctx.strokeStyle = 'black';
	if(Date.now() - this.lastMove < 200)
		ctx.strokeStyle = 'red';

	ctx.beginPath();

	var x = Math.floor(this.x);
	var y = Math.floor(this.y);

	//The robot's main circle
	ctx.arc(x, y, Robot.size, 0, Math.PI * 2, true);

	//draw a line to show Robot's orientation
	ctx.moveTo(x, y);
	ctx.lineTo(Math.floor(this.x + cos(this.dir) * Robot.size), Math.floor(this.y + sin(this.dir) * Robot.size));

	ctx.stroke();

	ctx.strokeStyle = 'rgba(0, 0, 255, '+ (1-this.senseCircle/Robot.sensorRadius) +')';
	ctx.beginPath();
	//draw Robot's sensing circle
	ctx.arc(x, y, this.senseCircle, 0, Math.PI*2, false);
	ctx.stroke();

	for (var i = this.particles.length - 1; i >= 0; i--)
	{
		var p = this.particles[i];
		p.draw(ctx);
	}
}<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var harness = require('./harness.js');

var Vq = harness.lib.ViewQuery;

describe('#Querying', function() {
  function allTests(H) {
    describe('#View Queries', function () {
      it('should set ddoc/name properly', function () {
        var q = Vq.from('d', 'v');
        assert.equal(q.ddoc, 'd');
        assert.equal(q.name, 'v');
      });
      it('should set stale to ok properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.NONE);
        assert.equal(q.options.stale, 'ok');
      });
      it('should set stale to false properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.BEFORE);
        assert.equal(q.options.stale, 'false');
      });
      it('should set stale to update_after properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.AFTER);
        assert.equal(q.options.stale, 'update_after');
      });
      it('should fail with incorrect stale parameter', function () {
        assert.throws(function () {
          Vq.from('d', 'v').stale('foo');
        }, TypeError);
      });
      it('should set skip properly', function () {
        var q = Vq.from('d', 'v').skip(11);
        assert.equal(q.options.skip, 11);
      });
      it('should set limit properly', function () {
        var q = Vq.from('d', 'v').limit(11);
        assert.equal(q.options.limit, 11);
      });
      it('should work with ascending order', function () {
        var q = Vq.from('d', 'v').order(Vq.Order.DESCENDING);
        assert.equal(q.options.descending, true);
      });
      it('should work with ascending order', function () {
        var q = Vq.from('d', 'v').order(Vq.Order.ASCENDING);
        assert.equal(q.options.descending, false);
      });
      it('should fail with incorrect order parameter', function () {
        assert.throws(function () {
          Vq.from('d', 'v').order('foo');
        }, TypeError);
      });
      it('should work with reduce as true', function () {
        var q = Vq.from('d', 'v').reduce(true);
        assert.equal(q.options.reduce, true);
      });
      it('should work with reduce as false', function () {
        var q = Vq.from('d', 'v').reduce(false);
        assert.equal(q.options.reduce, false);
      });
      it('should work with grouping off', function () {
        var q = Vq.from('d', 'v').group(-1);
        assert.equal(q.options.group, true);
        assert.equal(q.options.group_level, 0);
      });
      it('should work with key', function () {
        var q = Vq.from('d', 'v').key('test1');
        assert.equal(q.options.key, '"test1"');
      });
      it('should work with keys', function () {
        var q = Vq.from('d', 'v').keys(['test1', 'test2']);
        assert.equal(q.postoptions.keys, ['test1','test2']);
      });
      it('should work with grouping set', function () {
        var q = Vq.from('d', 'v').group(3);
        assert.equal(q.options.group, false);
        assert.equal(q.options.group_level, 3);
      });
      it('should work with range begin', function () {
        var q = Vq.from('d', 'v').range('test1');
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, undefined);
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with range end', function () {
        var q = Vq.from('d', 'v').range(undefined, 'test1');
        assert.equal(q.options.startkey, undefined);
        assert.equal(q.options.endkey, '"test1"');
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with range between', function () {
        var q = Vq.from('d', 'v').range('test1', 'test2');
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, '"test2"');
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with inclusive end', function () {
        var q = Vq.from('d', 'v').range('test1', 'test2', true);
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, '"test2"');
        assert.equal(q.options.inclusive_end, 'true');
      });
      it('should work with id range begin', function () {
        var q = Vq.from('d', 'v').id_range('test1');
        assert.equal(q.options.startkey_docid, 'test1');
        assert.equal(q.options.endkey_docid, undefined);
      });
      it('should work with id range end', function () {
        var q = Vq.from('d', 'v').id_range(undefined, 'test1');
        assert.equal(q.options.startkey_docid, undefined);
        assert.equal(q.options.endkey_docid, 'test1');
      });
      it('should work with id range between', function () {
        var q = Vq.from('d', 'v').id_range('test1', 'test2');
        assert.equal(q.options.startkey_docid, 'test1');
        assert.equal(q.options.endkey_docid, 'test2');
      });
      it('should work with full_set (default)', function () {
        var q = Vq.from('d', 'v').full_set();
        assert.equal(q.options.full_set, 'true');
      });
      it('should work with full_set', function () {
        var q = Vq.from('d', 'v').full_set(true);
        assert.equal(q.options.full_set, 'true');
      });
      it('should work with on_error stop', function () {
        var q = Vq.from('d', 'v').on_error(Vq.ErrorMode.STOP);
        assert.equal(q.options.on_error, 'stop');
      });
      it('should work with on_error continue', function () {
        var q = Vq.from('d', 'v').on_error(Vq.ErrorMode.CONTINUE);
        assert.equal(q.options.on_error, 'continue');
      });
      it('should set custom options properly', function () {
        var q = Vq.from('d', 'v').custom({x: 4, y: 'hi'});
        assert.equal(q.options.x, 4);
        assert.equal(q.options.y, 'hi');
      });
      it('should work for spatial queries', function () {
        var q = Vq.fromSpatial('d', 'v').bbox([1, 2, 3, 4]);
        assert.equal(q.options.bbox, '1,2,3,4');
      });
    });
    describe('#View Queries (slow)', function () {
      var key = H.key();
      var ddKey = H.key();
      var ddKeyGeo = H.key();
      var bm = H.b.manager();
      before(function (done) {
        this.timeout(8000);
        bm.insertDesignDocument(ddKey, {
          views: {
            simple: {
              map: 'function(doc, meta){emit(meta.id);}'
            }
          }
        }, function (err, res) {
          assert(!err);
          assert(res);
          bm.insertDesignDocument(ddKeyGeo, {
            spatial: {
              'simpleGeo': 'function(doc, meta){emit({type:"Point",coordinates:doc.loc},[meta.id, doc.loc]);}'
            }
          }, function(err, res) {
            assert(!err);
            assert(res);
            H.b.insert(key, 'foo', H.okCallback(function() {
              setTimeout(function () {
                H.b.query(
                    Vq.from(ddKey, 'simple').stale(Vq.Update.BEFORE).limit(1),
                    function (err) {
                      assert(!err);
                      done();
                    });
              }, 3000);
            }));
          });
        });
      });
      after(function (done) {
        H.b.remove(key, H.okCallback(function() {
          bm.removeDesignDocument(ddKeyGeo, function(err, res) {
            assert.ifError(err);
            assert(res);
            bm.removeDesignDocument(ddKey, function(err, res) {
              assert.ifError(err);
              assert(res);
              done();
            });
          });
        }));
      });

      it('should fail for invalid query objects', function () {
        assert.throws(function () {
          H.b.query({}, H.noCallback())
              .on('row', H.noCallback())
              .on('rows', H.noCallback())
              .on('end', H.noCallback())
              .on('error', H.noCallback());
        }, TypeError);
      });
      it('view queries should callback', function (done) {
        H.b.query(Vq.from(ddKey, 'simple').limit(1),
            function (err, res, meta) {
              assert(!err);
              assert(res);
              assert(meta);
              assert(meta.total_rows > 0);
              done();
            });
      });

      it('view queries should callback on error', function (done) {
        H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1),
            function (err, res) {
              assert(err);
              assert(!res);
              done();
            });
      });

      it('view queries should emit individual rows', function (done) {
        var rowCount = 0;
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('row', function (row) {
              assert(row);
              rowCount++;
            }).on('end', function () {
              assert(rowCount > 0);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should emit a rows events', function (done) {
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('rows', function (rows, meta) {
              assert(rows);
              assert(meta);
              assert(meta.total_rows > 0);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should be able to emit all events', function (done) {
        var rowCount = 0;
        var rowsMeta = null;
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('row', function (row) {
              assert(row);
              rowCount++;
            }).on('rows', function (rows, meta) {
              assert(rows);
              assert(meta);
              assert(meta.total_rows > 0);
              rowsMeta = meta;
            }).on('end', function (meta) {
              assert(rowCount > 0);
              assert(meta, rowsMeta);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should emit an error event with a row handler',
          function (done) {
            H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1))
                .on('row', function (rows) {
                  // Do Nothing
                }).on('error', function (err) {
                  assert(err);
                  done();
                });
          });

      it('view queries should emit an error event with a rows handler',
          function (done) {
            H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1))
                .on('rows', function (rows) {
                  // Do Nothing
                }).on('error', function (err) {
                  assert(err);
                  done();
                });
          });

      /*
       * Disabled because Couchbase Server isn't allowing it to work
       *   properly at the moment...
       */
      it.skip('spatial queries should work', function (done) {
        this.timeout(4000);
        H.b.query(Vq.fromSpatial(ddKeyGeo, 'simpleGeo'),
            function (err, rows, meta) {
              assert(!err);
              assert(rows);
              assert(meta);
              done();
            });
      });
    });
  }

  describe('#RealBucket', allTests.bind(this, harness));
  describe('#MockBucket', allTests.bind(this, harness.mock));
});
<commit_msg>JSCBC-403: Fix broken test in view query system.<commit_after>'use strict';

var assert = require('assert');
var harness = require('./harness.js');

var Vq = harness.lib.ViewQuery;

describe('#Querying', function() {
  function allTests(H) {
    describe('#View Queries', function () {
      it('should set ddoc/name properly', function () {
        var q = Vq.from('d', 'v');
        assert.equal(q.ddoc, 'd');
        assert.equal(q.name, 'v');
      });
      it('should set stale to ok properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.NONE);
        assert.equal(q.options.stale, 'ok');
      });
      it('should set stale to false properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.BEFORE);
        assert.equal(q.options.stale, 'false');
      });
      it('should set stale to update_after properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.AFTER);
        assert.equal(q.options.stale, 'update_after');
      });
      it('should fail with incorrect stale parameter', function () {
        assert.throws(function () {
          Vq.from('d', 'v').stale('foo');
        }, TypeError);
      });
      it('should set skip properly', function () {
        var q = Vq.from('d', 'v').skip(11);
        assert.equal(q.options.skip, 11);
      });
      it('should set limit properly', function () {
        var q = Vq.from('d', 'v').limit(11);
        assert.equal(q.options.limit, 11);
      });
      it('should work with ascending order', function () {
        var q = Vq.from('d', 'v').order(Vq.Order.DESCENDING);
        assert.equal(q.options.descending, true);
      });
      it('should work with ascending order', function () {
        var q = Vq.from('d', 'v').order(Vq.Order.ASCENDING);
        assert.equal(q.options.descending, false);
      });
      it('should fail with incorrect order parameter', function () {
        assert.throws(function () {
          Vq.from('d', 'v').order('foo');
        }, TypeError);
      });
      it('should work with reduce as true', function () {
        var q = Vq.from('d', 'v').reduce(true);
        assert.equal(q.options.reduce, true);
      });
      it('should work with reduce as false', function () {
        var q = Vq.from('d', 'v').reduce(false);
        assert.equal(q.options.reduce, false);
      });
      it('should work with grouping off', function () {
        var q = Vq.from('d', 'v').group(-1);
        assert.equal(q.options.group, true);
        assert.equal(q.options.group_level, 0);
      });
      it('should work with key', function () {
        var q = Vq.from('d', 'v').key('test1');
        assert.equal(q.options.key, '"test1"');
      });
      it('should work with keys', function () {
        var q = Vq.from('d', 'v').keys(['test1', 'test2']);
        assert.deepEqual(q.postoptions.keys, ['test1','test2']);
      });
      it('should work with grouping set', function () {
        var q = Vq.from('d', 'v').group(3);
        assert.equal(q.options.group, false);
        assert.equal(q.options.group_level, 3);
      });
      it('should work with range begin', function () {
        var q = Vq.from('d', 'v').range('test1');
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, undefined);
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with range end', function () {
        var q = Vq.from('d', 'v').range(undefined, 'test1');
        assert.equal(q.options.startkey, undefined);
        assert.equal(q.options.endkey, '"test1"');
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with range between', function () {
        var q = Vq.from('d', 'v').range('test1', 'test2');
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, '"test2"');
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with inclusive end', function () {
        var q = Vq.from('d', 'v').range('test1', 'test2', true);
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, '"test2"');
        assert.equal(q.options.inclusive_end, 'true');
      });
      it('should work with id range begin', function () {
        var q = Vq.from('d', 'v').id_range('test1');
        assert.equal(q.options.startkey_docid, 'test1');
        assert.equal(q.options.endkey_docid, undefined);
      });
      it('should work with id range end', function () {
        var q = Vq.from('d', 'v').id_range(undefined, 'test1');
        assert.equal(q.options.startkey_docid, undefined);
        assert.equal(q.options.endkey_docid, 'test1');
      });
      it('should work with id range between', function () {
        var q = Vq.from('d', 'v').id_range('test1', 'test2');
        assert.equal(q.options.startkey_docid, 'test1');
        assert.equal(q.options.endkey_docid, 'test2');
      });
      it('should work with full_set (default)', function () {
        var q = Vq.from('d', 'v').full_set();
        assert.equal(q.options.full_set, 'true');
      });
      it('should work with full_set', function () {
        var q = Vq.from('d', 'v').full_set(true);
        assert.equal(q.options.full_set, 'true');
      });
      it('should work with on_error stop', function () {
        var q = Vq.from('d', 'v').on_error(Vq.ErrorMode.STOP);
        assert.equal(q.options.on_error, 'stop');
      });
      it('should work with on_error continue', function () {
        var q = Vq.from('d', 'v').on_error(Vq.ErrorMode.CONTINUE);
        assert.equal(q.options.on_error, 'continue');
      });
      it('should set custom options properly', function () {
        var q = Vq.from('d', 'v').custom({x: 4, y: 'hi'});
        assert.equal(q.options.x, 4);
        assert.equal(q.options.y, 'hi');
      });
      it('should work for spatial queries', function () {
        var q = Vq.fromSpatial('d', 'v').bbox([1, 2, 3, 4]);
        assert.equal(q.options.bbox, '1,2,3,4');
      });
    });
    describe('#View Queries (slow)', function () {
      var key = H.key();
      var ddKey = H.key();
      var ddKeyGeo = H.key();
      var bm = H.b.manager();
      before(function (done) {
        this.timeout(8000);
        bm.insertDesignDocument(ddKey, {
          views: {
            simple: {
              map: 'function(doc, meta){emit(meta.id);}'
            }
          }
        }, function (err, res) {
          assert(!err);
          assert(res);
          bm.insertDesignDocument(ddKeyGeo, {
            spatial: {
              'simpleGeo': 'function(doc, meta){emit({type:"Point",coordinates:doc.loc},[meta.id, doc.loc]);}'
            }
          }, function(err, res) {
            assert(!err);
            assert(res);
            H.b.insert(key, 'foo', H.okCallback(function() {
              setTimeout(function () {
                H.b.query(
                    Vq.from(ddKey, 'simple').stale(Vq.Update.BEFORE).limit(1),
                    function (err) {
                      assert(!err);
                      done();
                    });
              }, 3000);
            }));
          });
        });
      });
      after(function (done) {
        H.b.remove(key, H.okCallback(function() {
          bm.removeDesignDocument(ddKeyGeo, function(err, res) {
            assert.ifError(err);
            assert(res);
            bm.removeDesignDocument(ddKey, function(err, res) {
              assert.ifError(err);
              assert(res);
              done();
            });
          });
        }));
      });

      it('should fail for invalid query objects', function () {
        assert.throws(function () {
          H.b.query({}, H.noCallback())
              .on('row', H.noCallback())
              .on('rows', H.noCallback())
              .on('end', H.noCallback())
              .on('error', H.noCallback());
        }, TypeError);
      });
      it('view queries should callback', function (done) {
        H.b.query(Vq.from(ddKey, 'simple').limit(1),
            function (err, res, meta) {
              assert(!err);
              assert(res);
              assert(meta);
              assert(meta.total_rows > 0);
              done();
            });
      });

      it('view queries should callback on error', function (done) {
        H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1),
            function (err, res) {
              assert(err);
              assert(!res);
              done();
            });
      });

      it('view queries should emit individual rows', function (done) {
        var rowCount = 0;
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('row', function (row) {
              assert(row);
              rowCount++;
            }).on('end', function () {
              assert(rowCount > 0);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should emit a rows events', function (done) {
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('rows', function (rows, meta) {
              assert(rows);
              assert(meta);
              assert(meta.total_rows > 0);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should be able to emit all events', function (done) {
        var rowCount = 0;
        var rowsMeta = null;
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('row', function (row) {
              assert(row);
              rowCount++;
            }).on('rows', function (rows, meta) {
              assert(rows);
              assert(meta);
              assert(meta.total_rows > 0);
              rowsMeta = meta;
            }).on('end', function (meta) {
              assert(rowCount > 0);
              assert(meta, rowsMeta);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should emit an error event with a row handler',
          function (done) {
            H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1))
                .on('row', function (rows) {
                  // Do Nothing
                }).on('error', function (err) {
                  assert(err);
                  done();
                });
          });

      it('view queries should emit an error event with a rows handler',
          function (done) {
            H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1))
                .on('rows', function (rows) {
                  // Do Nothing
                }).on('error', function (err) {
                  assert(err);
                  done();
                });
          });

      /*
       * Disabled because Couchbase Server isn't allowing it to work
       *   properly at the moment...
       */
      it.skip('spatial queries should work', function (done) {
        this.timeout(4000);
        H.b.query(Vq.fromSpatial(ddKeyGeo, 'simpleGeo'),
            function (err, rows, meta) {
              assert(!err);
              assert(rows);
              assert(meta);
              done();
            });
      });
    });
  }

  describe('#RealBucket', allTests.bind(this, harness));
  describe('#MockBucket', allTests.bind(this, harness.mock));
});
<|endoftext|>


<commit_before>function config($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('index', {
            abstract: true,
            url: "/",
            templateUrl: "views/common/content.html"
        })
        .state('intro', {
            url: "/intro",
            templateUrl: "views/intro.html"
        })
        .state('index.home', {
            url: "home",
            templateUrl: "views/home.html"
        })
        .state('index.project', {
            url: "project",
            templateUrl: "views/project.html"
        })
        .state('index.project.floorplan', {
            url: "/floorplan",
            templateUrl: "views/project-floorplan.html"
        })
        .state('index.project.overview', {
            url: "/overview",
            templateUrl: "views/project-overview.html"
        })
        .state('index.project.gallery', {
            url: "/gallery",
            templateUrl: "views/project-gallery.html"
        })
        .state('index.location', {
            url: "location",
            templateUrl: "views/location.html"
        })
        .state('index.contact', {
            url: "contact",
            templateUrl: "views/contact.html"
        })
        .state('index.register', {
            url: "register",
            templateUrl: "views/register.html"
        })
};

angular.module('alpina').config(config).run(['$rootScope', '$location', '$window', function($rootScope, $location, $window){
     $rootScope
        .$on('$stateChangeSuccess',
            function(event){
                if (!$window.ga)
                    return;
                $window.ga('send', 'pageview', { page: $location.path() });
        });
}]);<commit_msg>Default enter page to intro<commit_after>function config($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/intro');
    $stateProvider
        .state('index', {
            abstract: true,
            url: "/",
            templateUrl: "views/common/content.html"
        })
        .state('intro', {
            url: "/intro",
            templateUrl: "views/intro.html"
        })
        .state('index.home', {
            url: "home",
            templateUrl: "views/home.html"
        })
        .state('index.project', {
            url: "project",
            templateUrl: "views/project.html"
        })
        .state('index.project.floorplan', {
            url: "/floorplan",
            templateUrl: "views/project-floorplan.html"
        })
        .state('index.project.overview', {
            url: "/overview",
            templateUrl: "views/project-overview.html"
        })
        .state('index.project.gallery', {
            url: "/gallery",
            templateUrl: "views/project-gallery.html"
        })
        .state('index.location', {
            url: "location",
            templateUrl: "views/location.html"
        })
        .state('index.contact', {
            url: "contact",
            templateUrl: "views/contact.html"
        })
        .state('index.register', {
            url: "register",
            templateUrl: "views/register.html"
        })
};

angular.module('alpina').config(config).run(['$rootScope', '$location', '$window', function($rootScope, $location, $window){
     $rootScope
        .$on('$stateChangeSuccess',
            function(event){
                if (!$window.ga)
                    return;
                $window.ga('send', 'pageview', { page: $location.path() });
        });
}]);<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var harness = require('./harness.js');

var Vq = harness.lib.ViewQuery;

describe('#Querying', function() {
  function allTests(H) {
    describe('#View Queries', function () {
      it('should set ddoc/name properly', function () {
        var q = Vq.from('d', 'v');
        assert.equal(q.ddoc, 'd');
        assert.equal(q.name, 'v');
      });
      it('should set stale to ok properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.NONE);
        assert.equal(q.options.stale, 'ok');
      });
      it('should set stale to false properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.BEFORE);
        assert.equal(q.options.stale, 'false');
      });
      it('should set stale to update_after properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.AFTER);
        assert.equal(q.options.stale, 'update_after');
      });
      it('should fail with incorrect stale parameter', function () {
        assert.throws(function () {
          Vq.from('d', 'v').stale('foo');
        }, TypeError);
      });
      it('should set skip properly', function () {
        var q = Vq.from('d', 'v').skip(11);
        assert.equal(q.options.skip, 11);
      });
      it('should set limit properly', function () {
        var q = Vq.from('d', 'v').limit(11);
        assert.equal(q.options.limit, 11);
      });
      it('should work with ascending order', function () {
        var q = Vq.from('d', 'v').order(Vq.Order.DESCENDING);
        assert.equal(q.options.descending, true);
      });
      it('should work with ascending order', function () {
        var q = Vq.from('d', 'v').order(Vq.Order.ASCENDING);
        assert.equal(q.options.descending, false);
      });
      it('should fail with incorrect order parameter', function () {
        assert.throws(function () {
          Vq.from('d', 'v').order('foo');
        }, TypeError);
      });
      it('should work with reduce as true', function () {
        var q = Vq.from('d', 'v').reduce(true);
        assert.equal(q.options.reduce, true);
      });
      it('should work with reduce as false', function () {
        var q = Vq.from('d', 'v').reduce(false);
        assert.equal(q.options.reduce, false);
      });
      it('should work with grouping off', function () {
        var q = Vq.from('d', 'v').group(-1);
        assert.equal(q.options.group, true);
        assert.equal(q.options.group_level, 0);
      });
      it('should work with key', function () {
        var q = Vq.from('d', 'v').key('test1');
        assert.equal(q.options.key, '"test1"');
      });
      it('should work with keys', function () {
        var q = Vq.from('d', 'v').keys(['test1', 'test2']);
        assert.equal(q.options.keys, '["test1","test2"]');
      });
      it('should work with grouping set', function () {
        var q = Vq.from('d', 'v').group(3);
        assert.equal(q.options.group, false);
        assert.equal(q.options.group_level, 3);
      });
      it('should work with range begin', function () {
        var q = Vq.from('d', 'v').range('test1');
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, undefined);
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with range end', function () {
        var q = Vq.from('d', 'v').range(undefined, 'test1');
        assert.equal(q.options.startkey, undefined);
        assert.equal(q.options.endkey, '"test1"');
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with range between', function () {
        var q = Vq.from('d', 'v').range('test1', 'test2');
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, '"test2"');
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with inclusive end', function () {
        var q = Vq.from('d', 'v').range('test1', 'test2', true);
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, '"test2"');
        assert.equal(q.options.inclusive_end, 'true');
      });
      it('should work with id range begin', function () {
        var q = Vq.from('d', 'v').id_range('test1');
        assert.equal(q.options.startkey_docid, 'test1');
        assert.equal(q.options.endkey_docid, undefined);
      });
      it('should work with id range end', function () {
        var q = Vq.from('d', 'v').id_range(undefined, 'test1');
        assert.equal(q.options.startkey_docid, undefined);
        assert.equal(q.options.endkey_docid, 'test1');
      });
      it('should work with id range between', function () {
        var q = Vq.from('d', 'v').id_range('test1', 'test2');
        assert.equal(q.options.startkey_docid, 'test1');
        assert.equal(q.options.endkey_docid, 'test2');
      });
      it('should work with full_set (default)', function () {
        var q = Vq.from('d', 'v').full_set();
        assert.equal(q.options.full_set, 'true');
      });
      it('should work with full_set', function () {
        var q = Vq.from('d', 'v').full_set(true);
        assert.equal(q.options.full_set, 'true');
      });
      it('should work with on_error stop', function () {
        var q = Vq.from('d', 'v').on_error(Vq.ErrorMode.STOP);
        assert.equal(q.options.on_error, 'stop');
      });
      it('should work with on_error continue', function () {
        var q = Vq.from('d', 'v').on_error(Vq.ErrorMode.CONTINUE);
        assert.equal(q.options.on_error, 'continue');
      });
      it('should set custom options properly', function () {
        var q = Vq.from('d', 'v').custom({x: 4, y: 'hi'});
        assert.equal(q.options.x, 4);
        assert.equal(q.options.y, 'hi');
      });
      it('should work for spatial queries', function () {
        var q = Vq.fromSpatial('d', 'v').bbox([1, 2, 3, 4]);
        assert.equal(q.options.bbox, '1,2,3,4');
      });
    });
    describe('#View Queries (slow)', function () {
      var key = H.key();
      var ddKey = H.key();
      var ddKeyGeo = H.key();
      var bm = H.b.manager();
      before(function (done) {
        this.timeout(8000);
        bm.insertDesignDocument(ddKey, {
          views: {
            simple: {
              map: 'function(doc, meta){emit(meta.id);}'
            }
          }
        }, function (err, res) {
          assert(!err);
          assert(res);
          bm.insertDesignDocument(ddKeyGeo, {
            spatial: {
              'simpleGeo': 'function(doc, meta){emit({type:"Point",coordinates:doc.loc},[meta.id, doc.loc]);}'
            }
          }, function(err, res) {
            assert(!err);
            assert(res);
            H.b.insert(key, 'foo', H.okCallback(function() {
              setTimeout(function () {
                H.b.query(
                    Vq.from(ddKey, 'simple').stale(Vq.Update.BEFORE).limit(1),
                    function (err) {
                      assert(!err);
                      done();
                    });
              }, 3000);
            }));
          });
        });
      });
      after(function (done) {
        H.b.remove(key, H.okCallback(function() {
          bm.removeDesignDocument(ddKeyGeo, function(err, res) {
            assert.ifError(err);
            assert(res);
            bm.removeDesignDocument(ddKey, function(err, res) {
              assert.ifError(err);
              assert(res);
              done();
            });
          });
        }));
      });

      it('should fail for invalid query objects', function () {
        assert.throws(function () {
          H.b.query({}, H.noCallback())
              .on('row', H.noCallback())
              .on('rows', H.noCallback())
              .on('end', H.noCallback())
              .on('error', H.noCallback());
        }, TypeError);
      });
      it('view queries should callback', function (done) {
        H.b.query(Vq.from(ddKey, 'simple').limit(1),
            function (err, res, meta) {
              assert(!err);
              assert(res);
              assert(meta);
              assert(meta.total_rows > 0);
              done();
            });
      });

      it('view queries should callback on error', function (done) {
        H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1),
            function (err, res) {
              assert(err);
              assert(!res);
              done();
            });
      });

      it('view queries should emit individual rows', function (done) {
        var rowCount = 0;
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('row', function (row) {
              assert(row);
              rowCount++;
            }).on('end', function () {
              assert(rowCount > 0);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should emit a rows events', function (done) {
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('rows', function (rows, meta) {
              assert(rows);
              assert(meta);
              assert(meta.total_rows > 0);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should be able to emit all events', function (done) {
        var rowCount = 0;
        var rowsMeta = null;
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('row', function (row) {
              assert(row);
              rowCount++;
            }).on('rows', function (rows, meta) {
              assert(rows);
              assert(meta);
              assert(meta.total_rows > 0);
              rowsMeta = meta;
            }).on('end', function (meta) {
              assert(rowCount > 0);
              assert(meta, rowsMeta);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should emit an error event with a row handler',
          function (done) {
            H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1))
                .on('row', function (rows) {
                  // Do Nothing
                }).on('error', function (err) {
                  assert(err);
                  done();
                });
          });

      it('view queries should emit an error event with a rows handler',
          function (done) {
            H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1))
                .on('rows', function (rows) {
                  // Do Nothing
                }).on('error', function (err) {
                  assert(err);
                  done();
                });
          });

      /*
       * Disabled because Couchbase Server isn't allowing it to work
       *   properly at the moment...
       */
      it.skip('spatial queries should work', function (done) {
        this.timeout(4000);
        H.b.query(Vq.fromSpatial(ddKeyGeo, 'simpleGeo'),
            function (err, rows, meta) {
              assert(!err);
              assert(rows);
              assert(meta);
              done();
            });
      });
    });
  }

  describe('#RealBucket', allTests.bind(this, harness));
  describe('#MockBucket', allTests.bind(this, harness.mock));
});
<commit_msg>JSCBC-403: Fix test errors from recent view query change.<commit_after>'use strict';

var assert = require('assert');
var harness = require('./harness.js');

var Vq = harness.lib.ViewQuery;

describe('#Querying', function() {
  function allTests(H) {
    describe('#View Queries', function () {
      it('should set ddoc/name properly', function () {
        var q = Vq.from('d', 'v');
        assert.equal(q.ddoc, 'd');
        assert.equal(q.name, 'v');
      });
      it('should set stale to ok properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.NONE);
        assert.equal(q.options.stale, 'ok');
      });
      it('should set stale to false properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.BEFORE);
        assert.equal(q.options.stale, 'false');
      });
      it('should set stale to update_after properly', function () {
        var q = Vq.from('d', 'v').stale(Vq.Update.AFTER);
        assert.equal(q.options.stale, 'update_after');
      });
      it('should fail with incorrect stale parameter', function () {
        assert.throws(function () {
          Vq.from('d', 'v').stale('foo');
        }, TypeError);
      });
      it('should set skip properly', function () {
        var q = Vq.from('d', 'v').skip(11);
        assert.equal(q.options.skip, 11);
      });
      it('should set limit properly', function () {
        var q = Vq.from('d', 'v').limit(11);
        assert.equal(q.options.limit, 11);
      });
      it('should work with ascending order', function () {
        var q = Vq.from('d', 'v').order(Vq.Order.DESCENDING);
        assert.equal(q.options.descending, true);
      });
      it('should work with ascending order', function () {
        var q = Vq.from('d', 'v').order(Vq.Order.ASCENDING);
        assert.equal(q.options.descending, false);
      });
      it('should fail with incorrect order parameter', function () {
        assert.throws(function () {
          Vq.from('d', 'v').order('foo');
        }, TypeError);
      });
      it('should work with reduce as true', function () {
        var q = Vq.from('d', 'v').reduce(true);
        assert.equal(q.options.reduce, true);
      });
      it('should work with reduce as false', function () {
        var q = Vq.from('d', 'v').reduce(false);
        assert.equal(q.options.reduce, false);
      });
      it('should work with grouping off', function () {
        var q = Vq.from('d', 'v').group(-1);
        assert.equal(q.options.group, true);
        assert.equal(q.options.group_level, 0);
      });
      it('should work with key', function () {
        var q = Vq.from('d', 'v').key('test1');
        assert.equal(q.options.key, '"test1"');
      });
      it('should work with keys', function () {
        var q = Vq.from('d', 'v').keys(['test1', 'test2']);
        assert.equal(q.postoptions.keys, ['test1','test2']);
      });
      it('should work with grouping set', function () {
        var q = Vq.from('d', 'v').group(3);
        assert.equal(q.options.group, false);
        assert.equal(q.options.group_level, 3);
      });
      it('should work with range begin', function () {
        var q = Vq.from('d', 'v').range('test1');
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, undefined);
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with range end', function () {
        var q = Vq.from('d', 'v').range(undefined, 'test1');
        assert.equal(q.options.startkey, undefined);
        assert.equal(q.options.endkey, '"test1"');
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with range between', function () {
        var q = Vq.from('d', 'v').range('test1', 'test2');
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, '"test2"');
        assert.equal(q.options.inclusive_end, undefined);
      });
      it('should work with inclusive end', function () {
        var q = Vq.from('d', 'v').range('test1', 'test2', true);
        assert.equal(q.options.startkey, '"test1"');
        assert.equal(q.options.endkey, '"test2"');
        assert.equal(q.options.inclusive_end, 'true');
      });
      it('should work with id range begin', function () {
        var q = Vq.from('d', 'v').id_range('test1');
        assert.equal(q.options.startkey_docid, 'test1');
        assert.equal(q.options.endkey_docid, undefined);
      });
      it('should work with id range end', function () {
        var q = Vq.from('d', 'v').id_range(undefined, 'test1');
        assert.equal(q.options.startkey_docid, undefined);
        assert.equal(q.options.endkey_docid, 'test1');
      });
      it('should work with id range between', function () {
        var q = Vq.from('d', 'v').id_range('test1', 'test2');
        assert.equal(q.options.startkey_docid, 'test1');
        assert.equal(q.options.endkey_docid, 'test2');
      });
      it('should work with full_set (default)', function () {
        var q = Vq.from('d', 'v').full_set();
        assert.equal(q.options.full_set, 'true');
      });
      it('should work with full_set', function () {
        var q = Vq.from('d', 'v').full_set(true);
        assert.equal(q.options.full_set, 'true');
      });
      it('should work with on_error stop', function () {
        var q = Vq.from('d', 'v').on_error(Vq.ErrorMode.STOP);
        assert.equal(q.options.on_error, 'stop');
      });
      it('should work with on_error continue', function () {
        var q = Vq.from('d', 'v').on_error(Vq.ErrorMode.CONTINUE);
        assert.equal(q.options.on_error, 'continue');
      });
      it('should set custom options properly', function () {
        var q = Vq.from('d', 'v').custom({x: 4, y: 'hi'});
        assert.equal(q.options.x, 4);
        assert.equal(q.options.y, 'hi');
      });
      it('should work for spatial queries', function () {
        var q = Vq.fromSpatial('d', 'v').bbox([1, 2, 3, 4]);
        assert.equal(q.options.bbox, '1,2,3,4');
      });
    });
    describe('#View Queries (slow)', function () {
      var key = H.key();
      var ddKey = H.key();
      var ddKeyGeo = H.key();
      var bm = H.b.manager();
      before(function (done) {
        this.timeout(8000);
        bm.insertDesignDocument(ddKey, {
          views: {
            simple: {
              map: 'function(doc, meta){emit(meta.id);}'
            }
          }
        }, function (err, res) {
          assert(!err);
          assert(res);
          bm.insertDesignDocument(ddKeyGeo, {
            spatial: {
              'simpleGeo': 'function(doc, meta){emit({type:"Point",coordinates:doc.loc},[meta.id, doc.loc]);}'
            }
          }, function(err, res) {
            assert(!err);
            assert(res);
            H.b.insert(key, 'foo', H.okCallback(function() {
              setTimeout(function () {
                H.b.query(
                    Vq.from(ddKey, 'simple').stale(Vq.Update.BEFORE).limit(1),
                    function (err) {
                      assert(!err);
                      done();
                    });
              }, 3000);
            }));
          });
        });
      });
      after(function (done) {
        H.b.remove(key, H.okCallback(function() {
          bm.removeDesignDocument(ddKeyGeo, function(err, res) {
            assert.ifError(err);
            assert(res);
            bm.removeDesignDocument(ddKey, function(err, res) {
              assert.ifError(err);
              assert(res);
              done();
            });
          });
        }));
      });

      it('should fail for invalid query objects', function () {
        assert.throws(function () {
          H.b.query({}, H.noCallback())
              .on('row', H.noCallback())
              .on('rows', H.noCallback())
              .on('end', H.noCallback())
              .on('error', H.noCallback());
        }, TypeError);
      });
      it('view queries should callback', function (done) {
        H.b.query(Vq.from(ddKey, 'simple').limit(1),
            function (err, res, meta) {
              assert(!err);
              assert(res);
              assert(meta);
              assert(meta.total_rows > 0);
              done();
            });
      });

      it('view queries should callback on error', function (done) {
        H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1),
            function (err, res) {
              assert(err);
              assert(!res);
              done();
            });
      });

      it('view queries should emit individual rows', function (done) {
        var rowCount = 0;
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('row', function (row) {
              assert(row);
              rowCount++;
            }).on('end', function () {
              assert(rowCount > 0);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should emit a rows events', function (done) {
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('rows', function (rows, meta) {
              assert(rows);
              assert(meta);
              assert(meta.total_rows > 0);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should be able to emit all events', function (done) {
        var rowCount = 0;
        var rowsMeta = null;
        H.b.query(Vq.from(ddKey, 'simple').limit(1))
            .on('row', function (row) {
              assert(row);
              rowCount++;
            }).on('rows', function (rows, meta) {
              assert(rows);
              assert(meta);
              assert(meta.total_rows > 0);
              rowsMeta = meta;
            }).on('end', function (meta) {
              assert(rowCount > 0);
              assert(meta, rowsMeta);
              done();
            }).on('error', function () {
              assert();
            });
      });

      it('view queries should emit an error event with a row handler',
          function (done) {
            H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1))
                .on('row', function (rows) {
                  // Do Nothing
                }).on('error', function (err) {
                  assert(err);
                  done();
                });
          });

      it('view queries should emit an error event with a rows handler',
          function (done) {
            H.b.query(Vq.from(ddKey, 'no_exist_view').limit(1))
                .on('rows', function (rows) {
                  // Do Nothing
                }).on('error', function (err) {
                  assert(err);
                  done();
                });
          });

      /*
       * Disabled because Couchbase Server isn't allowing it to work
       *   properly at the moment...
       */
      it.skip('spatial queries should work', function (done) {
        this.timeout(4000);
        H.b.query(Vq.fromSpatial(ddKeyGeo, 'simpleGeo'),
            function (err, rows, meta) {
              assert(!err);
              assert(rows);
              assert(meta);
              done();
            });
      });
    });
  }

  describe('#RealBucket', allTests.bind(this, harness));
  describe('#MockBucket', allTests.bind(this, harness.mock));
});
<|endoftext|>


<commit_before>var camera, controls, scene, renderer, clock, stats, listener, audioLoader;

var environment = {};
var tick = 0;

var nightMode = false;

function nightModeSet(value) {
    nightMode = value;
}

init();
render();
animate();

function createUI() {
    stats = new Stats();
    stats.showPanel( 0 );
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.display = 'none';
    stats.domElement.style.margin = '10px 15px auto';
    document.body.appendChild( stats.domElement );

    var generate = new CRGButton( 'Regenerate', function ( btn ) {
        createEnvironment( 70, 50, 2 );
    });

    generate.addElement( new CRGDropdownButton( 'Night Mode', function( btn ) {
        if (nightMode == true) {
            nightModeSet(false);
            btn.setTextNode( 'Night Mode' );
        } else {
            nightModeSet(true);
            btn.setTextNode( 'Day Mode' );
        }
    }));
    UIaddElement( generate );

    var tools = new CRGDropdown( 'Tools' );
    tools.addElement( new CRGDropdownButton( 'Show FPS', function( btn ) {
        if (stats.domElement.style.display === 'none') {
            stats.domElement.style.display = 'block';
            btn.setTextNode( 'Hide FPS' );
        } else {
            stats.domElement.style.display = 'none';
            btn.setTextNode( 'Show FPS' );
        }
    }));

    tools.addElement( new CRGDropdownButton( 'Stop Audio', function( btn ) {
        if ( listener.getMasterVolume() > 0 ) {
            listener.setMasterVolume( 0 );
            btn.setTextNode( 'Play Audio' );
        } else {
            listener.setMasterVolume( 1 );
            btn.setTextNode( 'Stop Audio' );
        }
    }));

    UIaddElement( tools );

    UIgenerate();
}

function videoKilledTheRadioStar() {
    scene.traverse( function ( obj ) {
        var sound = obj.userData.sound;
        if ( typeof sound !== 'undefined' ) {
            obj.remove( sound );
        }
    } );
}

function init() {
    createUI();

    clock = new THREE.Clock();

    camera = new THREE.PerspectiveCamera( 45,
                                          window.innerWidth / window.innerHeight,
                                          1,
                                          1000 );

    camera.up = new THREE.Vector3( 0, 0, 1 );
    camera.position.set( -60, -60, 30 );
    camera.lookAt( 0, 0, 0 );

    listener = new THREE.AudioListener();
    camera.add( listener );

    audioLoader = new THREE.AudioLoader();

    renderer = new THREE.WebGLRenderer( { alpha: true,
                                          antialias: false } );
 	renderer.setPixelRatio( window.devicePixelRatio );

    renderer.setSize( window.innerWidth, window.innerHeight );
	renderer.sortObjects = false;

    controls = new THREE.OrbitControls( camera );
    var angleOffset = Math.PI / 32;
    controls.minDistance = 5;
    controls.maxDistance = 500;
    controls.minPolarAngle = 0 + angleOffset;
    controls.maxPolarAngle = Math.PI / 2 - angleOffset;
    controls.addEventListener( 'change', render );

    container = document.getElementById( 'canvas' );
    document.body.appendChild( container );
    container.appendChild( renderer.domElement );

    window.addEventListener( 'resize', onWindowResize, false );

    createBase( 70, 50, 2 );
    createEnvironment( 70, 50, 2 );
}

function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

    render();

}

function animate() {
    stats.begin();

    render();

    tick++;
    scene.update();
    controls.update();

    stats.end();

    requestAnimationFrame( animate );
}

function render() {
    renderer.render( scene, camera );
}

function initializeLights() {
    var sceneLight = new THREE.HemisphereLight( 0xc2c2dd, 0x40c2c2, .1 );
    scene.add( sceneLight );
    environment.hemiLight = sceneLight;

    var lamp = new THREE.DirectionalLight( 0xdddddd, 0.5 );
    lamp.position.set( 0, 10, 30 );
    lamp.castShadow = true;
    scene.add( lamp );
    environment.lamp = lamp;
}

function createBase( width, height, depth ) {

    scene = new THREE.Scene();

    environment.width = width;
    environment.height = height;
    environment.depth = depth;
    environment.radius = Math.sqrt( height * height / 4 + width * width / 4 );

    initializeLights();

    createWalls( width, height, 15 );

    var lanterns = [ { x : width / 2 - 2, y : -height / 2 + 2 },
                     { x : -width / 2 + 2, y : height / 2 - 2 } ];
    for ( var i = 0; i < lanterns.length; i++ ) {
        var dim = 3;
        var lantern = lanternFactory( dim, dim, 3 );
        var moth = mothFactory( lantern );

        lantern.addToObject( scene, lanterns[i].x, lanterns[i].y, depth * 2 );
    }
}

function createEnvironment( width, height, depth ) {
    if ( typeof environment.sand !== 'undefined' )
        scene.remove( environment.sand );
    if ( typeof environment.stars !== 'undefined' && !nightMode )
        scene.remove( environment.stars );
    createSand( width, height );
    //
    // generateSpireRock();
    // while ( Math.random() > 0.3 )
    //     generateSpireRock();

    if (nightMode) {
        scene.fog = new THREE.FogExp2( 0x001331, 0.0025 );
        renderer.setClearColor( 0x001331, 1 );
        environment.lamp = new THREE.DirectionalLight( 0x292929, 0.5 );
        if (typeof environment.stars === 'undefined') {
            stars = createStars();
            environment.stars = stars;
            scene.add(stars);
        }
        else {
            scene.add(environment.stars);
        }
    }
    else {
        scene.fog = new THREE.FogExp2( 0xaaccff, 0.005 );
        renderer.setClearColor( 0xaaccff, 1 );
        environment.lamp = new THREE.DirectionalLight( 0xdddddd, 0.5 );
    }

    var placer = new PlacementEngine(environment, scene);
    placer.runRandomTileEngine();

    // environment.sand.add(tree);
}
<commit_msg>Sound disconnect on object delete<commit_after>var camera, controls, scene, renderer, clock, stats, listener, audioLoader;

var environment = {};
var tick = 0;

var nightMode = false;

function nightModeSet(value) {
    nightMode = value;
}

init();
render();
animate();

function createUI() {
    stats = new Stats();
    stats.showPanel( 0 );
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.display = 'none';
    stats.domElement.style.margin = '10px 15px auto';
    document.body.appendChild( stats.domElement );

    var generate = new CRGButton( 'Regenerate', function ( btn ) {
        createEnvironment( 70, 50, 2 );
    });

    generate.addElement( new CRGDropdownButton( 'Night Mode', function( btn ) {
        if (nightMode == true) {
            nightModeSet(false);
            btn.setTextNode( 'Night Mode' );
        } else {
            nightModeSet(true);
            btn.setTextNode( 'Day Mode' );
        }
    }));
    UIaddElement( generate );

    var tools = new CRGDropdown( 'Tools' );
    tools.addElement( new CRGDropdownButton( 'Show FPS', function( btn ) {
        if (stats.domElement.style.display === 'none') {
            stats.domElement.style.display = 'block';
            btn.setTextNode( 'Hide FPS' );
        } else {
            stats.domElement.style.display = 'none';
            btn.setTextNode( 'Show FPS' );
        }
    }));

    tools.addElement( new CRGDropdownButton( 'Stop Audio', function( btn ) {
        if ( listener.getMasterVolume() > 0 ) {
            listener.setMasterVolume( 0 );
            btn.setTextNode( 'Play Audio' );
        } else {
            listener.setMasterVolume( 1 );
            btn.setTextNode( 'Stop Audio' );
        }
    }));

    UIaddElement( tools );

    UIgenerate();
}

function videoKilledTheRadioStar() {
    scene.traverse( function ( obj ) {
        var sound = obj.userData.sound;
        if ( typeof sound !== 'undefined' ) {
            sound.disconnect();
            delete sound;
        }
    } );
}

function init() {
    createUI();

    clock = new THREE.Clock();

    camera = new THREE.PerspectiveCamera( 45,
                                          window.innerWidth / window.innerHeight,
                                          1,
                                          1000 );

    camera.up = new THREE.Vector3( 0, 0, 1 );
    camera.position.set( -60, -60, 30 );
    camera.lookAt( 0, 0, 0 );

    listener = new THREE.AudioListener();
    camera.add( listener );

    audioLoader = new THREE.AudioLoader();

    renderer = new THREE.WebGLRenderer( { alpha: true,
                                          antialias: false } );
 	renderer.setPixelRatio( window.devicePixelRatio );

    renderer.setSize( window.innerWidth, window.innerHeight );
	renderer.sortObjects = false;

    controls = new THREE.OrbitControls( camera );
    var angleOffset = Math.PI / 32;
    controls.minDistance = 5;
    controls.maxDistance = 500;
    controls.minPolarAngle = 0 + angleOffset;
    controls.maxPolarAngle = Math.PI / 2 - angleOffset;
    controls.addEventListener( 'change', render );

    container = document.getElementById( 'canvas' );
    document.body.appendChild( container );
    container.appendChild( renderer.domElement );

    window.addEventListener( 'resize', onWindowResize, false );

    createBase( 70, 50, 2 );
    createEnvironment( 70, 50, 2 );
}

function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

    render();

}

function animate() {
    stats.begin();

    render();

    tick++;
    scene.update();
    controls.update();

    stats.end();

    requestAnimationFrame( animate );
}

function render() {
    renderer.render( scene, camera );
}

function initializeLights() {
    var sceneLight = new THREE.HemisphereLight( 0xc2c2dd, 0x40c2c2, .1 );
    scene.add( sceneLight );
    environment.hemiLight = sceneLight;

    var lamp = new THREE.DirectionalLight( 0xdddddd, 0.5 );
    lamp.position.set( 0, 10, 30 );
    lamp.castShadow = true;
    scene.add( lamp );
    environment.lamp = lamp;
}

function createBase( width, height, depth ) {

    scene = new THREE.Scene();

    environment.width = width;
    environment.height = height;
    environment.depth = depth;
    environment.radius = Math.sqrt( height * height / 4 + width * width / 4 );

    initializeLights();

    createWalls( width, height, 15 );

    var lanterns = [ { x : width / 2 - 2, y : -height / 2 + 2 },
                     { x : -width / 2 + 2, y : height / 2 - 2 } ];
    for ( var i = 0; i < lanterns.length; i++ ) {
        var dim = 3;
        var lantern = lanternFactory( dim, dim, 3 );
        var moth = mothFactory( lantern );

        lantern.addToObject( scene, lanterns[i].x, lanterns[i].y, depth * 2 );
    }
}

function createEnvironment( width, height, depth ) {
    if ( typeof environment.sand !== 'undefined' ) {
        videoKilledTheRadioStar();
        scene.remove( environment.sand );
    }
    if ( typeof environment.stars !== 'undefined' && !nightMode )
        scene.remove( environment.stars );
    createSand( width, height );
    //
    // generateSpireRock();
    // while ( Math.random() > 0.3 )
    //     generateSpireRock();

    if (nightMode) {
        scene.fog = new THREE.FogExp2( 0x001331, 0.0025 );
        renderer.setClearColor( 0x001331, 1 );
        environment.lamp = new THREE.DirectionalLight( 0x292929, 0.5 );
        if (typeof environment.stars === 'undefined') {
            stars = createStars();
            environment.stars = stars;
            scene.add(stars);
        }
        else {
            scene.add(environment.stars);
        }
    }
    else {
        scene.fog = new THREE.FogExp2( 0xaaccff, 0.005 );
        renderer.setClearColor( 0xaaccff, 1 );
        environment.lamp = new THREE.DirectionalLight( 0xdddddd, 0.5 );
    }

    var placer = new PlacementEngine(environment, scene);
    placer.runRandomTileEngine();

    // environment.sand.add(tree);
}
<|endoftext|>


<commit_before>// shape.js
// shapdar - Shape Radar...kinda
// nhmood @ [gooscode labs] - 2013
// HTML5 Canvas + JS

// did = div id
// cheight = canvas height
// cwidth = canvas width
// lstyle = line style
// lwidth = line width
// ccol = center color
// crad = center radius

function Shape(did, cheight, cwidth, lstyle, lwidth, ccol, crad, grid)  {
	// Grab canvas by ID, use "shape" as default
	this.dID = typeof(did) === "undefined" ? "" : did;
	// Use JQuery selector to get the .shape class within the specified div
	this.canvas = $(this.dID + ' .shape')[0];

	// Add event handlersr for mouse actions
	// Use .bind(this) to scope "this" to Shape not canvas
	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
	this.canvas.addEventListener("mousedown", this.mouseDown.bind(this));
	this.canvas.addEventListener("mousemove", this.mouseMove.bind(this));
	this.canvas.addEventListener("mouseup"  , this.mouseUp.bind(this));

	// Set size of canvas, use 400x400 as default
	this.canvas.width  = typeof(cwidth)  === "undefined" ? 400 : cwidth;
	this.canvas.height = typeof(cheight) === "undefined" ? 400 : cheight;

	// Grid size, default = 10 per dimension and grid flag
	this.gridSize = typeof(grid) === "undefined" ? 10 : grid;
	this.gridEnable = 0;

	// Get context of canvas for path drawing
	this.ctx = this.canvas.getContext("2d");

	// Line parameters default
	this.ctx.strokeStyle = typeof(lstyle) === "undefined" ? "#c95f5e" : lstyle;
	this.ctx.lineWidth   = typeof(lwidth) === "undefined" ?    3      : lwidth;

	// Create contour object to hold contour, gets populated from mouse events
	this.contour = new Contour();

	// ==================
	// Internal flags
	// ==================

	// drawEnable - Flag for when mouse movement registers drawing
	// drawComplete - Flag for when drawing is completed
	this.drawEnable = 0;
	this.drawComplete = 0;

	// Center point for shape that line is drawn from
	this.centerValid = 0;
	this.centerX = 0;
	this.centerY = 0;

	// Make center point red always (gets changed to black when color is red though)
	this.ccol = typeof(ccol) === "undefined" ? "#0099ff" : ccol;
	this.crad = typeof(crad) === "undefined" ?     5    : crad;

}

Shape.prototype.mouseDown = function(e){
	// If we haven't drawn our shape yet, draw our shape!
	if (!this.drawComplete){
		// Enable drawing for mousemove listener
		this.drawEnable = 1;

		// Add starting points to contour
		this.contour.addPoint(e.offsetX, e.offsetY);
		this.ctx.moveTo(e.offsetX, e.offsetY);
	}
	// If shape is drawn and mouse is clicked, register new center point
	else {
		// We now have a valid center point
		this.centerValid = 1;

		// Set center for this instance
		this.centerX = e.offsetX;
		this.centerY = e.offsetY;

		// Clear canvas, restore original shape, and place new center
		this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
		this.drawContour();

		// Draw center point
		this.ctx.fillStyle = this.ccol;
		this.ctx.fillRect(this.centerX - this.crad/2, this.centerY - this.crad/2, this.crad, this.crad);
	}
};

Shape.prototype.mouseMove = function(e){
	// If drawing is enabled, draw the line\
	if (this.drawEnable){
		// Store coords at mouse location
		var x = e.offsetX;
		var y = e.offsetY;

		// Add this point to our contour
		this.contour.addPoint(x, y);

		// Draw the point itself using a path
		// We need this to be done instantaneously for the user
		// So using a path is better than drawing each individual contour point
		// We will draw actual contour points as rectangles after full path is done
		this.ctx.lineTo(x, y);
		this.ctx.stroke();
	}
};

Shape.prototype.mouseUp = function(e){
	if (this.drawEnable){
		// Store coords at mouse location
		var x = e.offsetX;
		var y = e.offsetY;

		// Need a sufficiently sized shape
		// Also prevents accidental clicks
		if (this.contour.points.length > 10){
			// Add this current point to connect last to this
			// Then add initial point again to get contour for closePath
			this.contour.addPoint(x, y);
			this.contour.addPoint(this.contour.startX, this.contour.startY);

			// Finish line contour and save it
			this.ctx.lineTo(this.contour.startX, this.contour.startY);
			this.ctx.stroke();
			this.ctx.closePath();

			// Draw contour using actual rectangles then save context so we can
			// redraw this every frame next time
			this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
			this.drawContour();

			this.drawEnable = 0;
			this.drawComplete = 1;
		}
		// If not big enough, reset canvas, allow drawing, and reset params
		else {
			this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
			this.contour = new Contour();
			this.drawEnable = 0;
			this.drawComplete = 0;
		}
	}
};

Shape.prototype.drawContour = function(e){
	this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
	// Check if we have a contour to use
	// Short circuit with || will make sure second statement doesn't cause error
	if (typeof this.contour === 'undefined' || this.contour.points.length == 0){
		console.log("Uh oh, looks like there isn't a contour to draw");
		return;
	}

	// If we have valid contour, draw it
	for (var i = 0; i < this.contour.points.length; i++){
		this.ctx.fillStyle = this.ctx.strokeStyle;
		// Had to shift both dimensions by 2 pixels to line up with path line???
		this.ctx.fillRect(this.contour.points[i][0]-2, this.contour.points[i][1]-2, this.ctx.lineWidth, this.ctx.lineWidth+1);
	}
}

Shape.prototype.drawCenter = function(e){
	this.ctx.fillStyle = this.ccol;
	this.ctx.fillRect(this.centerX - this.crad/2, this.centerY - this.crad/2, this.crad, this.crad);
}

Shape.prototype.animate = function(index){
	var index = index % this.contour.points.length;

	// Clear canvas and redraw contour
	this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

	this.drawContour();
	this.drawGrid();

	// Draw a line from	center to next point
	this.ctx.beginPath();
	this.ctx.moveTo(this.centerX, this.centerY);
	this.ctx.lineTo(this.contour.points[index][0], this.contour.points[index][1]);
	this.ctx.stroke();
	this.ctx.closePath();
	this.drawCenter();
}

Shape.prototype.borderLine = function(index){
	var index = index % this.contour.points.length;
	// Draw line from contour to edge (to match GIF) if Y animation
	// Was using lineTo before but wasn't matching up right, using fillRect now
	// Fill rect from current x position to width of canvas @ y position
	for (var i = this.contour.points[index][0]; i < this.canvas.width; i++){
		this.ctx.fillStyle = this.ctx.strokeStyle;
		this.ctx.fillRect(i, this.contour.points[index][1], this.ctx.lineWidth, this.ctx.lineWidth);
	}

	// Fill in intersection point with dot
	this.ctx.fillStyle = this.ccol;
	this.ctx.fillRect(this.contour.points[index][0]-2.5, this.contour.points[index][1]-2.5, 5, 5);

}

Shape.prototype.drawGrid = function(e){
	if (this.gridEnable){
		this.ctx.beginPath();
		// Draw Y axis grids
		for (var i = 0; i < Math.round(this.canvas.width / this.gridSize); i++){
			this.ctx.moveTo(i*(Math.round(this.canvas.width / this.gridSize)), 0);
			this.ctx.lineTo(i*(Math.round(this.canvas.width / this.gridSize)), this.canvas.height);
		}

		// Draw X axis grids
		for (var i = 0; i < Math.round(this.canvas.height / this.gridSize); i++){
			this.ctx.moveTo(0, i*(Math.round(this.canvas.height / this.gridSize)));
			this.ctx.lineTo(this.canvas.height, i*(Math.round(this.canvas.height / this.gridSize)));
		}

		// Store previous line width and style so we don't mess up our actual shape
		var prevWidth = this.ctx.lineWidth;
		var prevStyle = this.ctx.strokeStyle;

		this.ctx.lineWidth = 1;
		this.ctx.strokeStyle = "#000000";
		this.ctx.stroke();

		// Reset our previous line style and width
		this.ctx.lineWidth = prevWidth;
		this.ctx.strokeStyle = prevStyle;
	}
}

// Reset shape to defaults and blank canvas
Shape.prototype.reset = function(lstyle, lwidth, ccol, crad){

	// Reset line style
	this.ctx.strokeStyle = typeof(lstyle) === "undefined" ? "#c95f5e" : lstyle;
	this.ctx.lineWidth   = typeof(lwidth) === "undefined" ?    3      : lwidth;

	// Reste contour
	this.contour = new Contour();

	// Reset drawing flags
	this.drawEnable = 0;
	this.drawComplete = 0;

	// Reset center points
	this.centerValid = 0;
	this.centerX = 0;
	this.centerY = 0;

	// Reset center colors (not really necessary)
	this.ccol = typeof(ccol) === "undefined" ? "#0099ff" : ccol;
	this.crad = typeof(crad) === "undefined" ?     5    : crad;

	// Clear canvas and remove any existing paths
	this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
	this.ctx.beginPath();
}<commit_msg>Small fix for grid lines<commit_after>// shape.js
// shapdar - Shape Radar...kinda
// nhmood @ [gooscode labs] - 2013
// HTML5 Canvas + JS

// did = div id
// cheight = canvas height
// cwidth = canvas width
// lstyle = line style
// lwidth = line width
// ccol = center color
// crad = center radius

function Shape(did, cheight, cwidth, lstyle, lwidth, ccol, crad, grid)  {
	// Grab canvas by ID, use "shape" as default
	this.dID = typeof(did) === "undefined" ? "" : did;
	// Use JQuery selector to get the .shape class within the specified div
	this.canvas = $(this.dID + ' .shape')[0];

	// Add event handlersr for mouse actions
	// Use .bind(this) to scope "this" to Shape not canvas
	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
	this.canvas.addEventListener("mousedown", this.mouseDown.bind(this));
	this.canvas.addEventListener("mousemove", this.mouseMove.bind(this));
	this.canvas.addEventListener("mouseup"  , this.mouseUp.bind(this));

	// Set size of canvas, use 400x400 as default
	this.canvas.width  = typeof(cwidth)  === "undefined" ? 400 : cwidth;
	this.canvas.height = typeof(cheight) === "undefined" ? 400 : cheight;

	// Grid size, default = 10 per dimension and grid flag
	this.gridSize = typeof(grid) === "undefined" ? 5 : grid;
	this.gridEnable = 0;

	// Get context of canvas for path drawing
	this.ctx = this.canvas.getContext("2d");

	// Line parameters default
	this.ctx.strokeStyle = typeof(lstyle) === "undefined" ? "#c95f5e" : lstyle;
	this.ctx.lineWidth   = typeof(lwidth) === "undefined" ?    3      : lwidth;

	// Create contour object to hold contour, gets populated from mouse events
	this.contour = new Contour();

	// ==================
	// Internal flags
	// ==================

	// drawEnable - Flag for when mouse movement registers drawing
	// drawComplete - Flag for when drawing is completed
	this.drawEnable = 0;
	this.drawComplete = 0;

	// Center point for shape that line is drawn from
	this.centerValid = 0;
	this.centerX = 0;
	this.centerY = 0;

	// Make center point red always (gets changed to black when color is red though)
	this.ccol = typeof(ccol) === "undefined" ? "#0099ff" : ccol;
	this.crad = typeof(crad) === "undefined" ?     5    : crad;

}

Shape.prototype.mouseDown = function(e){
	// If we haven't drawn our shape yet, draw our shape!
	if (!this.drawComplete){
		// Enable drawing for mousemove listener
		this.drawEnable = 1;

		// Add starting points to contour
		this.contour.addPoint(e.offsetX, e.offsetY);
		this.ctx.moveTo(e.offsetX, e.offsetY);
	}
	// If shape is drawn and mouse is clicked, register new center point
	else {
		// We now have a valid center point
		this.centerValid = 1;

		// Set center for this instance
		this.centerX = e.offsetX;
		this.centerY = e.offsetY;

		// Clear canvas, restore original shape, and place new center
		this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
		this.drawContour();

		// Draw center point
		this.ctx.fillStyle = this.ccol;
		this.ctx.fillRect(this.centerX - this.crad/2, this.centerY - this.crad/2, this.crad, this.crad);
	}
};

Shape.prototype.mouseMove = function(e){
	// If drawing is enabled, draw the line\
	if (this.drawEnable){
		// Store coords at mouse location
		var x = e.offsetX;
		var y = e.offsetY;

		// Add this point to our contour
		this.contour.addPoint(x, y);

		// Draw the point itself using a path
		// We need this to be done instantaneously for the user
		// So using a path is better than drawing each individual contour point
		// We will draw actual contour points as rectangles after full path is done
		this.ctx.lineTo(x, y);
		this.ctx.stroke();
	}
};

Shape.prototype.mouseUp = function(e){
	if (this.drawEnable){
		// Store coords at mouse location
		var x = e.offsetX;
		var y = e.offsetY;

		// Need a sufficiently sized shape
		// Also prevents accidental clicks
		if (this.contour.points.length > 10){
			// Add this current point to connect last to this
			// Then add initial point again to get contour for closePath
			this.contour.addPoint(x, y);
			this.contour.addPoint(this.contour.startX, this.contour.startY);

			// Finish line contour and save it
			this.ctx.lineTo(this.contour.startX, this.contour.startY);
			this.ctx.stroke();
			this.ctx.closePath();

			// Draw contour using actual rectangles then save context so we can
			// redraw this every frame next time
			this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
			this.drawContour();

			this.drawEnable = 0;
			this.drawComplete = 1;
		}
		// If not big enough, reset canvas, allow drawing, and reset params
		else {
			this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
			this.contour = new Contour();
			this.drawEnable = 0;
			this.drawComplete = 0;
		}
	}
};

Shape.prototype.drawContour = function(e){
	this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
	// Check if we have a contour to use
	// Short circuit with || will make sure second statement doesn't cause error
	if (typeof this.contour === 'undefined' || this.contour.points.length == 0){
		console.log("Uh oh, looks like there isn't a contour to draw");
		return;
	}

	// If we have valid contour, draw it
	for (var i = 0; i < this.contour.points.length; i++){
		this.ctx.fillStyle = this.ctx.strokeStyle;
		// Had to shift both dimensions by 2 pixels to line up with path line???
		this.ctx.fillRect(this.contour.points[i][0]-2, this.contour.points[i][1]-2, this.ctx.lineWidth, this.ctx.lineWidth+1);
	}
}

Shape.prototype.drawCenter = function(e){
	this.ctx.fillStyle = this.ccol;
	this.ctx.fillRect(this.centerX - this.crad/2, this.centerY - this.crad/2, this.crad, this.crad);
}

Shape.prototype.animate = function(index){
	var index = index % this.contour.points.length;

	// Clear canvas and redraw contour
	this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

	this.drawContour();
	this.drawGrid();

	// Draw a line from	center to next point
	this.ctx.beginPath();
	this.ctx.moveTo(this.centerX, this.centerY);
	this.ctx.lineTo(this.contour.points[index][0], this.contour.points[index][1]);
	this.ctx.stroke();
	this.ctx.closePath();
	this.drawCenter();
}

Shape.prototype.borderLine = function(index){
	var index = index % this.contour.points.length;
	// Draw line from contour to edge (to match GIF) if Y animation
	// Was using lineTo before but wasn't matching up right, using fillRect now
	// Fill rect from current x position to width of canvas @ y position
	for (var i = this.contour.points[index][0]; i < this.canvas.width; i++){
		this.ctx.fillStyle = this.ctx.strokeStyle;
		this.ctx.fillRect(i, this.contour.points[index][1], this.ctx.lineWidth, this.ctx.lineWidth);
	}

	// Fill in intersection point with dot
	this.ctx.fillStyle = this.ccol;
	this.ctx.fillRect(this.contour.points[index][0]-2.5, this.contour.points[index][1]-2.5, 5, 5);

}

Shape.prototype.drawGrid = function(e){
	if (this.gridEnable){
		this.ctx.beginPath();
		// Draw Y axis grids
		for (var i = 0; i < Math.round(this.canvas.width / this.gridSize); i++){
			this.ctx.moveTo(i*(Math.round(this.canvas.width / this.gridSize)), 0);
			this.ctx.lineTo(i*(Math.round(this.canvas.width / this.gridSize)), this.canvas.height);
		}

		// Draw X axis grids
		for (var i = 0; i < Math.round(this.canvas.height / this.gridSize); i++){
			this.ctx.moveTo(0, i*(Math.round(this.canvas.height / this.gridSize)));
			this.ctx.lineTo(this.canvas.height, i*(Math.round(this.canvas.height / this.gridSize)));
		}

		// Store previous line width and style so we don't mess up our actual shape
		var prevWidth = this.ctx.lineWidth;
		var prevStyle = this.ctx.strokeStyle;

		this.ctx.lineWidth = 1;
		this.ctx.strokeStyle = "#000000";
		this.ctx.stroke();

		// Reset our previous line style and width
		this.ctx.lineWidth = prevWidth;
		this.ctx.strokeStyle = prevStyle;
	}
}

// Reset shape to defaults and blank canvas
Shape.prototype.reset = function(lstyle, lwidth, ccol, crad){

	// Reset line style
	this.ctx.strokeStyle = typeof(lstyle) === "undefined" ? "#c95f5e" : lstyle;
	this.ctx.lineWidth   = typeof(lwidth) === "undefined" ?    3      : lwidth;

	// Reste contour
	this.contour = new Contour();

	// Reset drawing flags
	this.drawEnable = 0;
	this.drawComplete = 0;

	// Reset center points
	this.centerValid = 0;
	this.centerX = 0;
	this.centerY = 0;

	// Reset center colors (not really necessary)
	this.ccol = typeof(ccol) === "undefined" ? "#0099ff" : ccol;
	this.crad = typeof(crad) === "undefined" ?     5    : crad;

	// Clear canvas and remove any existing paths
	this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
	this.ctx.beginPath();
}<|endoftext|>


<commit_before>"use strict";
var screenH;
var screenW;
var stars = [];
var fps = 50;
var numStars = 200;

window.addEventListener("load", function() {

    // Calculate the screen size
    screenH = 600;
    screenW = 800;

    // Get the canvas
    //canvas = document.getElementById("#space");

    // Fill out the canvas

    // Create all the stars
    for (var i = 0; i < numStars; i++) {
        var x = Math.round(Math.random() * screenW);
        var y = Math.round(Math.random() * screenH);
        var length = 1 + Math.random() * 2;
        var opacity = Math.random();

        // Create a new star and draw
        var star = new Star(x, y, length, opacity);

        // Add the the stars array
        stars.push(star);
    }

}, false);

/**
 * Animate the canvas
 */

function animate(con, currentTime) {
    con.save();

    for(var i = 0; i < stars.length; i++) {
        stars[i].draw(con, currentTime);
    }

    con.restore();
}

/**
 * Star
 *
 * @param int x
 * @param int y
 * @param int length
 * @param opacity
 */
function Star(x, y, length, opacity) {
    /*
    this.x = parseInt(x);
    this.y = parseInt(y);
    this.length = parseInt(length);
    */
    this.x = x;
    this.y = y;
    this.length = length;
    this.opacity = opacity;
    this.factor = 1;
    this.period = Math.random() * 1.6 + 10;
    this.cycle = 0;
}

/**
 * Draw a star
 *
 * This function draws a start.
 * You need to give the contaxt as a parameter
 *
 * @param context
 */
Star.prototype.draw = function(con, currentTime) {

    var frameTime = (currentTime % this.period) / this.period;

    var passedCycles = Math.floor(currentTime / this.period);

    con.rotate((Math.PI * 1 / 10));

    // Save the context
    con.save();

    // move into the middle of the canvas, just to make room
    con.translate(this.x, this.y);

    if(this.cycle < passedCycles) {
        this.x = Math.round(Math.random() * screenW);
        this.y = Math.round(Math.random() * screenH);
        this.cycle = passedCycles;
    }
    this.opacity = 0.5 + 0.5 * Math.sin(2 * Math.PI * frameTime);

    con.beginPath()
    for (var i = 5; i > 0 ; i--) {
        con.lineTo(0, this.length);
        con.translate(0, this.length);
        con.rotate((Math.PI * 2 / 10));
        con.lineTo(0, -this.length);
        con.translate(0, -this.length);
        con.rotate(-(Math.PI * 6 / 10));
    }
    con.lineTo(0, this.length);
    con.closePath();
    con.fillStyle = "rgba(255, 255, 200, " + this.opacity + ")";
    con.shadowBlur = 5;
    con.shadowColor = '#ffff33';
    con.fill();

    con.restore();
}
<commit_msg>rewriting stars.js to be more concise<commit_after>"use strict";
let stars = [];
let numStars = 87;

window.addEventListener("load", function() {
  let canvas = document.getElementById('canvas');

  // Add stars to the stars array
  for (let i = 0; i < numStars; i++) {
    let star = new Star;
    stars.push(star);
  }

}, false);

let animate = (con) => {
    con.save();
    stars.map((star)=>star.draw(con))
    con.restore();
}

function Star() {
  this.length = 1 + Math.random() * 1.8;
  this.period = Math.random() * 1.6 + 10;
  this.pos = {x:Math.round(Math.random() * canvas.width),y:Math.round(Math.random() * canvas.height)};
}

Star.prototype.draw = function(con) {
    // Save the context
    con.save();

    // move into the middle of the canvas, just to make room
    con.translate(this.pos.x+this.pos.x/2, this.pos.y);

    this.opacity = 0.5 + 0.5 * Math.sin(3 * Math.PI);

    con.beginPath()
    for (let i = 5; i > 0 ; i--) {
        con.lineTo(0, this.length);
        con.translate(0, this.length);
        con.rotate((Math.PI * 2 / 10));
        con.lineTo(0, -this.length);
        con.translate(0, -this.length);
        con.rotate(-(Math.PI * 6 / 10));
    }
    con.lineTo(0, this.length);
    con.closePath();
    con.fillStyle = "rgba(255, 255, 200, " + this.opacity + ")";

    con.fill();

    con.restore();
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Spam Reporter
// @namespace    http://github.com/Tiny-Giant
// @version      1.0.0.0
// @description  Adds a link to the post menu for most posts.
// @author       @TinyGiant
// @include      /^https?:\/\/\w*.?(stackexchange.com|stackoverflow.com|serverfault.com|superuser.com|askubuntu.com|stackapps.com|mathoverflow.net)\/q(uestions)?\/\d+/
// @grant        GM_xmlhttpRequest
// ==/UserScript==
/* jshint -W097 */

(function(){
    'use strict';

    var notify = (function(){
        var count = 0, timeout;
        return function(m,t) {
            console.log(m,t);
            if($('#notify-' + count).length) {
                clearTimeout(timeout);
                StackExchange.notify.close(count);
            }
            StackExchange.notify.show(m,++count);
            if(t) timeout = setTimeout(StackExchange.notify.close.bind(null,count), t);
        };
    })();

    var engage = function(scope) {

        if (!scope) {
            return false;
        }

        var room = 41570; // use 68414 for testing

        var postLink = scope.querySelector('.short-link').href;

        var reportSent = function(response) {
            console.log(response);

            if (response.status !== 200) {
                notify('Error sending request: ' + resp.responseText);
                return false;
            }

            notify('Close vote request sent.',1000);
        };

        var sendReport = function(response) {
            console.log(response);

            if (response.status !== 200) {
                notify('Failed sending report, check the console for more information.');
                return false;
            }

            var fkey = response.responseText.match(/hidden" value="([\dabcdef]{32})/)[1];

            if (!fkey) {
                notify('Failed retrieving key, is the room URL valid?');
                return false;
            }

            var reportStr = '!!/report ' + postLink;

            var options = {
                method: 'POST',
                url: 'http://chat.stackoverflow.com/chats/' + room + '/messages/new',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                data: 'text=' + encodeURIComponent(reportStr) + '&fkey=' + fkey,
                onload: reportSent
            };

            GM_xmlhttpRequest(options);
        };

        var report = function() {
            if(!confirm('Do you really want to report this post?')) {
                return false;
            }

            var options = {
                method: 'GET',
                url: 'http://chat.stackoverflow.com/rooms/' + room,
                onload: sendReport
            };

            GM_xmlhttpRequest(options);
        };

        var sep = document.createElement('span');
        sep.className = 'lsep';
        sep.textContent = '|';
        scope.appendChild(sep);

        var link = document.createElement('a');
        link.href = '#';
        link.textContent = 'report';
        link.addEventListener('click', report, false);
        scope.appendChild(link);
    };

    var menus = document.querySelectorAll('.post-menu');

    for(var i in Object.keys(menus)) engage(menus[i]);

    $(document).ajaxComplete(function(){
        var url = arguments[2].url;
        if (/^\/posts\/ajax-load-realtime\//.test(url)) engage(/\d+/.exec(url)[0]);
    });
})();
<commit_msg>Prevent from going to top of page when clicking on Report<commit_after>// ==UserScript==
// @name         Spam Reporter
// @namespace    http://github.com/Tiny-Giant
// @version      1.0.0.0
// @description  Adds a link to the post menu for most posts.
// @author       @TinyGiant
// @include      /^https?:\/\/\w*.?(stackexchange.com|stackoverflow.com|serverfault.com|superuser.com|askubuntu.com|stackapps.com|mathoverflow.net)\/q(uestions)?\/\d+/
// @grant        GM_xmlhttpRequest
// ==/UserScript==
/* jshint -W097 */

(function(){
    'use strict';

    var notify = (function(){
        var count = 0, timeout;
        return function(m,t) {
            console.log(m,t);
            if($('#notify-' + count).length) {
                clearTimeout(timeout);
                StackExchange.notify.close(count);
            }
            StackExchange.notify.show(m,++count);
            if(t) timeout = setTimeout(StackExchange.notify.close.bind(null,count), t);
        };
    })();

    var engage = function(scope) {

        if (!scope) {
            return false;
        }

        var room = 41570; // use 68414 for testing

        var postLink = scope.querySelector('.short-link').href;

        var reportSent = function(response) {
            console.log(response);

            if (response.status !== 200) {
                notify('Error sending request: ' + resp.responseText);
                return false;
            }

            notify('Close vote request sent.',1000);
        };

        var sendReport = function(response) {
            console.log(response);

            if (response.status !== 200) {
                notify('Failed sending report, check the console for more information.');
                return false;
            }

            var fkey = response.responseText.match(/hidden" value="([\dabcdef]{32})/)[1];

            if (!fkey) {
                notify('Failed retrieving key, is the room URL valid?');
                return false;
            }

            var reportStr = '!!/report ' + postLink;

            var options = {
                method: 'POST',
                url: 'http://chat.stackoverflow.com/chats/' + room + '/messages/new',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                data: 'text=' + encodeURIComponent(reportStr) + '&fkey=' + fkey,
                onload: reportSent
            };

            GM_xmlhttpRequest(options);
        };

        var report = function(e) {
			e.preventDefault();

            if(!confirm('Do you really want to report this post?')) {
                return false;
            }

            var options = {
                method: 'GET',
                url: 'http://chat.stackoverflow.com/rooms/' + room,
                onload: sendReport
            };

            GM_xmlhttpRequest(options);
        };

        var sep = document.createElement('span');
        sep.className = 'lsep';
        sep.textContent = '|';
        scope.appendChild(sep);

        var link = document.createElement('a');
        link.href = '#';
        link.textContent = 'report';
        link.addEventListener('click', report, false);
        scope.appendChild(link);
    };

    var menus = document.querySelectorAll('.post-menu');

    for(var i in Object.keys(menus)) engage(menus[i]);

    $(document).ajaxComplete(function(){
        var url = arguments[2].url;
        if (/^\/posts\/ajax-load-realtime\//.test(url)) engage(/\d+/.exec(url)[0]);
    });
})();
<|endoftext|>


<commit_before>import { routing } from '../../../app/routes';

const mappedRoutes = {};
// eslint-disable-next-line array-callback-return
Object.keys(routing).map((key) => {
  mappedRoutes[routing[key].type] = () => [
    'trackPageView',
    routing[key].title,
    window.location.href,
    null
  ];
});

const routes = mappedRoutes;

export default routes;
<commit_msg>Simplified function to return object with routes/functions for piwik<commit_after>import { routing } from '../../../app/routes';

const routes = Object.entries(routing).reduce((acc, [, value]) => ({
  ...acc,
  [value.type]: () => [
    'trackPageView',
    value.title,
    window.location.href,
    null
  ]
}));

export default routes;
<|endoftext|>