<commit_before>// TODO create method to parse the excel (https://www.npmjs.org/package/excel-parser) and save each row in collection 'registration' in MongoDB
var cfg = require('../../app-config.json');
var excelParser = require('excel-parser');

// DB Connection
var mongoFactory = require('mongo-factory');
var db;
mongoFactory.getConnection(cfg.mongodb.url).then(function(dbConnection) {
    db = dbConnection;
});

var processExcelDocument = function(document) {
    excelParser.worksheets({inFile: document}, function(err, worksheets){
	if(err) console.error(err);
	console.log(worksheets);
    });

    excelParser.parse({inFile: document,
		       worksheet: 1},
		      function(err, records){
			  firstRow = records[0];
			  if(err) console.error(err);
			  db.collection("registration").remove();
			  for(var row in records) {
			      //console.log(records[row]);
			      var jsonObj = {}
			      if ( row == 0 ) continue;
			      for(var column in records[row]) {
				  fieldname = records[0][column];
				  console.log(fieldname);

				  if (str.indexOf("|") >= 0){
				      var result = records[row][column]. split('|');
				      jsonObj[fieldname] = result;
				  } else {
				      jsonObj[fieldname] = records[row][column]
				  }
			      }
			      var json_version = JSON.parse( JSON.string(jsonObj));
			      //console.log(json_version);
			      db.collection("registration").insert(json_version, function (err) {console.log(err);});
			  }
		      });
}

exports.processExcelDocument = processExcelDocument;

<commit_msg>Parsing take 2 -- Deleting previous database<commit_after>// TODO create method to parse the excel (https://www.npmjs.org/package/excel-parser) and save each row in collection 'registration' in MongoDB
var cfg = require('../../app-config.json');
var excelParser = require('excel-parser');

// DB Connection
var mongoFactory = require('mongo-factory');
var db;
mongoFactory.getConnection(cfg.mongodb.url).then(function(dbConnection) {
    db = dbConnection;
});

var processExcelDocument = function(document) {
    excelParser.worksheets({inFile: document}, function(err, worksheets){
	if(err) console.error(err);
	console.log(worksheets);
    });

    excelParser.parse({inFile: document,
		       worksheet: 1},
		      function(err, records){
			  firstRow = records[0];
			  if(err) console.error(err);
			  //db.collection('registration').remove();
			  db.collection('registration',function(err, collection){
			      collection.remove({},function(err, removed){
				  if(err) console.error(err);
			      });
			  });

			  db.createCollection('registration');
			  console.error("Completed flushing the database.");
			  for(var row in records) {
			      //console.log(records[row]);
			      var jsonObj = {}
			      if ( row == 0 ) continue;
			      for(var column in records[row]) {
				  fieldname = records[0][column];
				  console.log(fieldname);

				  if (records[row][column].indexOf("|") >= 0){
				      var result = records[row][column]. split('|');
				      jsonObj[fieldname] = result;
				  } else {
				      jsonObj[fieldname] = records[row][column]
				  }
			      }
			      var json_version = JSON.parse( JSON.string(jsonObj));
			      //console.log(json_version);
			      db.collection("registration").insert(json_version, function (err) {console.log(err);});
			  }
		      });
}

exports.processExcelDocument = processExcelDocument;

<|endoftext|>


<commit_before>'use strict';

angular.module('myApp', [
  'ngRoute',
  'selectize',
  'ng-token-auth'
])

  .config(function ($authProvider) {
    $authProvider.configure({
      apiUrl: '',
      emailRegistrationPath: '/signup',
      emailSignInPath: '/signin',
      signOutUrl: ' '
    });
  });<commit_msg>Change configure<commit_after>'use strict';

angular.module('myApp', [
  'ngRoute',
  'selectize',
  'ng-token-auth'
])

  .config(function ($authProvider) {
    $authProvider.configure({
      apiUrl: 'http://localhost:8080',
      emailRegistrationPath: '/signup',
      emailSignInPath: '/signin',
      signOutUrl: ' '
    });
  });<|endoftext|>


<commit_before>define([
	'goo/entities/systems/System',
	'goo/entities/SystemBus'
],
/** @lends */
function (
	System,
	SystemBus
) {
	"use strict";

	/**
	 * @class Processes all entities with a light component making sure that lights are placed according to its transforms
	 */
	function LightingSystem() {
		System.call(this, 'LightingSystem', ['LightComponent', 'TransformComponent']);

		this.overrideLights = null;
		this._needsUpdate = true;
	}

	LightingSystem.prototype = Object.create(System.prototype);

	// does this really need exist? can't inserted and deleted be used instead?
	/*
	LightingSystem.prototype.addedComponent = function (entity, component) {
		if (component.type !== 'LightComponent') {
			return;
		}

		if (this.lights.indexOf(component.light) === -1) {
			entity.transformComponent.setUpdated();
			this.lights.push(component.light);
			if (!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};

	LightingSystem.prototype.removedComponent = function (entity, component) {
		if (component.type !== 'LightComponent') {
			return;
		}

		var index = this.lights.indexOf(component.light);
		if (index !== -1) {
			this.lights.splice(index, 1);
			if (!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};
	//*/

	//
	/*
	LightingSystem.prototype.inserted = function() {
		if (this.lights.indexOf(component.light) === -1) {
			entity.transformComponent.setUpdated();
			this.lights.push(component.light);
			if (!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};

	LightingSystem.prototype.deleted = function() {
		var index = this.lights.indexOf(component.light);
		if (index !== -1) {
			this.lights.splice(index, 1);
			if(!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};
	*/

	/**
	 * Replaces the lights tracked by the system with custom ones.
	 * @param overrideLights
	 */
	LightingSystem.prototype.setOverrideLights = function (overrideLights) {
		this.overrideLights = overrideLights;
		SystemBus.emit('goo.setLights', this.overrideLights);
		this._needsUpdate = true;
	};

	/**
	 * Disables overriding of lights tracked by the system
	 */
	LightingSystem.prototype.clearOverrideLights = function () {
		this.overrideLights = undefined;
		//SystemBus.emit('goo.setLights', this.lights);
		this._needsUpdate = true;
	};

	LightingSystem.prototype.process = function (entities) {
		if (!this.overrideLights) {
			var lights = [];

			for (var i = 0; i < entities.length; i++) {
				var entity = entities[i];
				var transformComponent = entity.transformComponent;
				var lightComponent = entity.lightComponent;

				if (transformComponent._updated || this._needsUpdate) {
					lightComponent.updateLight(transformComponent.worldTransform);
				}

				if (!lightComponent.hidden) {
					lights.push(lightComponent.light);
				}
			}
			this._needsUpdate = false;

			SystemBus.emit('goo.setLights', lights);
		}
	};

	return LightingSystem;
});<commit_msg>Review on #779<commit_after>define([
	'goo/entities/systems/System',
	'goo/entities/SystemBus'
],
/** @lends */
function (
	System,
	SystemBus
) {
	"use strict";

	/**
	 * @class Processes all entities with a light component making sure that lights are placed according to its transforms
	 */
	function LightingSystem() {
		System.call(this, 'LightingSystem', ['LightComponent', 'TransformComponent']);

		this.overrideLights = null;
		this._needsUpdate = true;
	}

	LightingSystem.prototype = Object.create(System.prototype);

	// does this really need exist? can't inserted and deleted be used instead?
	/*
	LightingSystem.prototype.addedComponent = function (entity, component) {
		if (component.type !== 'LightComponent') {
			return;
		}

		if (this.lights.indexOf(component.light) === -1) {
			entity.transformComponent.setUpdated();
			this.lights.push(component.light);
			if (!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};

	LightingSystem.prototype.removedComponent = function (entity, component) {
		if (component.type !== 'LightComponent') {
			return;
		}

		var index = this.lights.indexOf(component.light);
		if (index !== -1) {
			this.lights.splice(index, 1);
			if (!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};
	//*/

	//
	/*
	LightingSystem.prototype.inserted = function() {
		if (this.lights.indexOf(component.light) === -1) {
			entity.transformComponent.setUpdated();
			this.lights.push(component.light);
			if (!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};

	LightingSystem.prototype.deleted = function() {
		var index = this.lights.indexOf(component.light);
		if (index !== -1) {
			this.lights.splice(index, 1);
			if(!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};
	*/

	/**
	 * Replaces the lights tracked by the system with custom ones.
	 * @param overrideLights
	 */
	LightingSystem.prototype.setOverrideLights = function (overrideLights) {
		this.overrideLights = overrideLights;
		SystemBus.emit('goo.setLights', this.overrideLights);
		this._needsUpdate = true;
	};

	/**
	 * Disables overriding of lights tracked by the system
	 */
	LightingSystem.prototype.clearOverrideLights = function () {
		this.overrideLights = undefined;
		//SystemBus.emit('goo.setLights', this.lights);
		this._needsUpdate = true;
	};

	/* REVIEW: Fair enough, since simplepartitioner does it every frame
	 * The systembus thing might be a bit slow though
	 * How about uncomment setLights in clearOverride, then loop in a more performant way
	 * like in partitioner. Reuse this.lights.
	 var index = 0;
	 this.lights[index++] = light;
	 ...
	 this.lights.length = index;
	 */
	LightingSystem.prototype.process = function (entities) {
		if (!this.overrideLights) {
			var lights = [];

			for (var i = 0; i < entities.length; i++) {
				var entity = entities[i];
				var transformComponent = entity.transformComponent;
				var lightComponent = entity.lightComponent;

				if (transformComponent._updated || this._needsUpdate) {
					lightComponent.updateLight(transformComponent.worldTransform);
				}

				if (!lightComponent.hidden) {
					lights.push(lightComponent.light);
				}
			}
			this._needsUpdate = false;

			SystemBus.emit('goo.setLights', lights);
		}
	};

	return LightingSystem;
});<|endoftext|>


<commit_before>var _ = require('lodash');
var Benchmark = require('benchmark.js');

var flyd = require('../flyd');
var oldFlyd = require('../flyd-old');

var stream = flyd.stream;

global.stream = flyd.stream;
global.flyd = flyd;
global.oldFlyd = oldFlyd;
global.oldStream = oldFlyd.stream;

// ************************************************
// Util functions

var suites = [];

function getHz(bench) { // hz adjusted for margin of error
  var result = 1 / (bench.stats.mean + bench.stats.moe);
  return isFinite(result) ? result : 0;
}

function printFastest(suite) {
  var formatNumber = Benchmark.formatNumber,
      fastest = suite.filter('fastest'),
      fastestHz = getHz(fastest[0]),
      slowest = suite.filter('slowest'),
      slowestHz = getHz(slowest[0]),
      aHz = getHz(suite[0]),
      bHz = getHz(suite[1]);
  if (fastest.length > 1) {
    console.log('It\'s too close to call.');
    aHz = bHz = slowestHz;
  } else {
    var percent = ((fastestHz / slowestHz) - 1) * 100;
    console.log('  ' + fastest[0].name + ' is ' +
        formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) +
        '% faster.');
  }
}

Benchmark.Suite.options.onStart = function() {
  console.log('\n' + this.name + ':');
};

Benchmark.Suite.options.onCycle = function(event) {
  console.log('  ' + event.target);
};

Benchmark.Suite.options.onComplete = function() {
  printFastest(this);
  suites.shift();
  if (suites.length) {
    suites[0].run({async: true});
  }
};

// ************************************************
// Benchmarks!

suites.push(Benchmark.Suite('dynamic dependencies').add('New', {
  setup: function() {
    var s = stream();
    stream(function() {
      return s();
    });
  },
  fn: function() {
    s(12);
  },
}).add('Old', {
  setup: function() {
    var s = oldStream();
    oldStream(function() {
      return s();
    });
  },
  fn: function() {
    s(12);
  },
}));

suites.push(Benchmark.Suite('static dependencies').add('New', {
  setup: function() {
    var s = stream();
    stream([s], function() {
      return s();
    });
  },
  fn: function() {
    s(12);
  },
}).add('Old', {
  setup: function() {
    var s = oldStream();
    oldStream([s], function() {
      return s();
    });
  },
  fn: function() {
    s(12);
  },
}));

suites.push(Benchmark.Suite('map').add('First', {
  setup: function() {
    var flyd = global.flyd;
    var stream = global.flyd.stream;
    function f(x) { return x; }
    var s1 = stream();
    var s2 = s1.map(f);
    var s3 = s2.map(f);
    var s4 = s3.map(f);
    var s5 = s4.map(f);
  },
  fn: function() {
    s1(12);
  },
}).add('Second', {
  setup: function() {
    var flyd = global.flyd;
    var stream = global.flyd.stream;
    function f(x) { return x; }
    var s1 = stream();
    var s2 = s1.map(f);
    var s3 = s2.map(f);
    var s4 = s3.map(f);
    var s5 = s4.map(f);
  },
  fn: function() {
    s1(12);
  },
}));

suites.push(Benchmark.Suite('dynamic dependency graph').add('New', {
  setup: function() {
    var s1 = stream();
    var s2 = stream(function() {
      s1(); s1();
    });
    var s3 = stream(function() {
      s1(); s2(); s1();
    });
    var s4 = stream(function() {
      s1(); s2(); s3(); s1(); s3();
    });
    stream(function() {
      s3(); s2(); s1(); s3(); s4();
    });
  },
  fn: function() {
    s1(12);
  },
}).add('Old', {
  setup: function() {
    var s1 = oldStream();
    var s2 = oldStream(function() {
      s1(); s1();
    });
    var s3 = oldStream(function() {
      s1(); s2(); s1();
    });
    var s4 = oldStream(function() {
      s1(); s2(); s3(); s1(); s3();
    });
    oldStream(function() {
      s3(); s2(); s1(); s3(); s4();
    });
  },
  fn: function() {
    s1(12);
  },
}));

suites[0].run({ 'async': true });
<commit_msg>Fix requiring benchmark.js<commit_after>var _ = require('lodash');
var Benchmark = require('benchmark');

var flyd = require('../flyd');
var oldFlyd = require('../flyd-old');

var stream = flyd.stream;

global.stream = flyd.stream;
global.flyd = flyd;
global.oldFlyd = oldFlyd;
global.oldStream = oldFlyd.stream;

// ************************************************
// Util functions

var suites = [];

function getHz(bench) { // hz adjusted for margin of error
  var result = 1 / (bench.stats.mean + bench.stats.moe);
  return isFinite(result) ? result : 0;
}

function printFastest(suite) {
  var formatNumber = Benchmark.formatNumber,
      fastest = suite.filter('fastest'),
      fastestHz = getHz(fastest[0]),
      slowest = suite.filter('slowest'),
      slowestHz = getHz(slowest[0]),
      aHz = getHz(suite[0]),
      bHz = getHz(suite[1]);
  if (fastest.length > 1) {
    console.log('It\'s too close to call.');
    aHz = bHz = slowestHz;
  } else {
    var percent = ((fastestHz / slowestHz) - 1) * 100;
    console.log('  ' + fastest[0].name + ' is ' +
        formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) +
        '% faster.');
  }
}

Benchmark.Suite.options.onStart = function() {
  console.log('\n' + this.name + ':');
};

Benchmark.Suite.options.onCycle = function(event) {
  console.log('  ' + event.target);
};

Benchmark.Suite.options.onComplete = function() {
  printFastest(this);
  suites.shift();
  if (suites.length) {
    suites[0].run({async: true});
  }
};

// ************************************************
// Benchmarks!

suites.push(Benchmark.Suite('dynamic dependencies').add('New', {
  setup: function() {
    var s = stream();
    stream(function() {
      return s();
    });
  },
  fn: function() {
    s(12);
  },
}).add('Old', {
  setup: function() {
    var s = oldStream();
    oldStream(function() {
      return s();
    });
  },
  fn: function() {
    s(12);
  },
}));

suites.push(Benchmark.Suite('static dependencies').add('New', {
  setup: function() {
    var s = stream();
    stream([s], function() {
      return s();
    });
  },
  fn: function() {
    s(12);
  },
}).add('Old', {
  setup: function() {
    var s = oldStream();
    oldStream([s], function() {
      return s();
    });
  },
  fn: function() {
    s(12);
  },
}));

suites.push(Benchmark.Suite('map').add('First', {
  setup: function() {
    var flyd = global.flyd;
    var stream = global.flyd.stream;
    function f(x) { return x; }
    var s1 = stream();
    var s2 = s1.map(f);
    var s3 = s2.map(f);
    var s4 = s3.map(f);
    var s5 = s4.map(f);
  },
  fn: function() {
    s1(12);
  },
}).add('Second', {
  setup: function() {
    var flyd = global.flyd;
    var stream = global.flyd.stream;
    function f(x) { return x; }
    var s1 = stream();
    var s2 = s1.map(f);
    var s3 = s2.map(f);
    var s4 = s3.map(f);
    var s5 = s4.map(f);
  },
  fn: function() {
    s1(12);
  },
}));

suites.push(Benchmark.Suite('dynamic dependency graph').add('New', {
  setup: function() {
    var s1 = stream();
    var s2 = stream(function() {
      s1(); s1();
    });
    var s3 = stream(function() {
      s1(); s2(); s1();
    });
    var s4 = stream(function() {
      s1(); s2(); s3(); s1(); s3();
    });
    stream(function() {
      s3(); s2(); s1(); s3(); s4();
    });
  },
  fn: function() {
    s1(12);
  },
}).add('Old', {
  setup: function() {
    var s1 = oldStream();
    var s2 = oldStream(function() {
      s1(); s1();
    });
    var s3 = oldStream(function() {
      s1(); s2(); s1();
    });
    var s4 = oldStream(function() {
      s1(); s2(); s3(); s1(); s3();
    });
    oldStream(function() {
      s3(); s2(); s1(); s3(); s4();
    });
  },
  fn: function() {
    s1(12);
  },
}));

suites[0].run({ 'async': true });
<|endoftext|>


<commit_before>var should = require('should');
var request = require('superagent').agent();

var init = require('../main/init');
var config = require('../main/config').options({ test: true });
var mongo = require('../main/mongo').options({ dropDatabase: true });
var es = require('../main/es').options({ dropIndex: true });
var express = require('../main/express');
var rcs = require('../main/rcs');
var test = require('../main/test').options({ request: request });

require('../main/session-api');
require('../main/post-api');

before(function (next) {
	init.run(next);
});

before(function () {
	express.listen();
});

describe('get /api/threads/0/0', function () {
	it('given user session', function (next) {
		test.loginUser(next);
	});
	var t1, p11, p12;
	it('given t1, p11', function (next) {
		var form = { categoryId: 101, writer: 'snowman', title: 'title 1', text: 'post 11' };
		request.post(test.url + '/api/threads').send(form).end(function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			t1 = res.body.threadId;
			p11 = res.body.postId;
			next();
		});
	});
	it('given p12', function (next) {
		var form = { writer: 'snowman', text: 'post 12' };
		request.post(test.url + '/api/threads/' + t1).send(form).end(function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			p12 = res.body.postId;
			next();
		});
	});
	it('given admin session', function (next) {
		test.loginAdmin(next);
	});
	var t2, p21, p22;
	it('given t2, p21 in recycle bin', function (next) {
		var form = { categoryId: 40, writer: 'snowman', title: 'title 2', text: 'post 21' };
		request.post(test.url + '/api/threads').send(form).end(function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			t2 = res.body.threadId;
			p21 = res.body.postId;
			next();
		});
	});
	it('given p22 in recycle bin', function (next) {
		var form = { writer: 'snowman', text: 'post 22' };
		request.post(test.url + '/api/threads/' + t2).send(form).end(function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			p22 = res.body.postId;
			next();
		});
	});
	it('given no session', function (next) {
		test.logout(next);
	});
	it("should fail", function (next) {
		request.get(test.url + '/api/threads/' + t1 + '/' + p11, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.NOT_AUTHENTICATED);
			next();
		});
	});
	it('given user session', function (next) {
		test.loginUser(next);
	});
	it('should success for p11', function (next) {
		request.get(test.url + '/api/threads/' + t1 + '/' + p11, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			res.body.thread.title.should.equal('title 1');
			res.body.category.id.should.equal(101);
			res.body.post.writer.should.equal('snowman');
			res.body.post.text.should.equal('post 11');
			res.body.post.head.should.true;
			res.body.post.visible.should.true;
			next();
		});
	});
	it('should success for p12', function (next) {
		request.get(test.url + '/api/threads/' + t1 + '/' + p12, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			res.body.post.writer.should.equal('snowman');
			res.body.post.text.should.equal('post 12');
			res.body.post.head.should.false;
			next();
		});
	});
	it('should fail for p21 in recycle bin', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p21, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.INVALID_CATEGORY);
			next();
		});
	});
	it('should fail for p22 in recycle bin', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p22, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.INVALID_CATEGORY);
			next();
		});
	});
	it('given admin session', function (next) {
		test.loginAdmin(next);
	});
	it('should success for p21 in recycle bin', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p21, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			next();
		});
	});
	it('should success for p22 in recycle bin', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p22, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			next();
		});
	});
});

<commit_msg>post-read-test, added some test.<commit_after>var should = require('should');
var request = require('superagent').agent();

var init = require('../main/init');
var config = require('../main/config').options({ test: true });
var mongo = require('../main/mongo').options({ dropDatabase: true });
var es = require('../main/es').options({ dropIndex: true });
var express = require('../main/express');
var rcs = require('../main/rcs');
var test = require('../main/test').options({ request: request });

require('../main/session-api');
require('../main/post-api');

before(function (next) {
	init.run(next);
});

before(function () {
	express.listen();
});

describe('get /api/threads/0/0', function () {
	it('given user session', function (next) {
		test.loginUser(next);
	});
	var t1, p11, p12;
	it('given t1, p11', function (next) {
		var form = { categoryId: 101, writer: 'snowman', title: 'title 1', text: 'post 11' };
		request.post(test.url + '/api/threads').send(form).end(function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			t1 = res.body.threadId;
			p11 = res.body.postId;
			next();
		});
	});
	it('given p12', function (next) {
		var form = { writer: 'snowman', text: 'post 12' };
		request.post(test.url + '/api/threads/' + t1).send(form).end(function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			p12 = res.body.postId;
			next();
		});
	});
	it('given admin session', function (next) {
		test.loginAdmin(next);
	});
	var t2, p21, p22;
	it('given t2, p21 in recycle bin', function (next) {
		var form = { categoryId: 40, writer: 'snowman', title: 'title 2', text: 'post 21' };
		request.post(test.url + '/api/threads').send(form).end(function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			t2 = res.body.threadId;
			p21 = res.body.postId;
			next();
		});
	});
	it('given p22 in recycle bin', function (next) {
		var form = { writer: 'snowman', text: 'post 22' };
		request.post(test.url + '/api/threads/' + t2).send(form).end(function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			p22 = res.body.postId;
			next();
		});
	});
	it('given no session', function (next) {
		test.logout(next);
	});
	it("should fail", function (next) {
		request.get(test.url + '/api/threads/' + t1 + '/' + p11, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.NOT_AUTHENTICATED);
			next();
		});
	});
	it('given user session', function (next) {
		test.loginUser(next);
	});
	it('should fail with invalid threadId', function (next) {
		request.get(test.url + '/api/threads/' + 99999 + '/' + p11, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.INVALID_THREAD);
			next();
		});
	});
	it('should fail with mismatching threadId', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p11, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.INVALID_POST);
			next();
		});
	});
	it('should fail with invalid postId', function (next) {
		request.get(test.url + '/api/threads/' + t1 + '/' + 99999, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.INVALID_POST);
			next();
		});
	});
	it('should success for p11', function (next) {
		request.get(test.url + '/api/threads/' + t1 + '/' + p11, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			res.body.thread.title.should.equal('title 1');
			res.body.category.id.should.equal(101);
			res.body.post.writer.should.equal('snowman');
			res.body.post.text.should.equal('post 11');
			res.body.post.head.should.true;
			res.body.post.visible.should.true;
			next();
		});
	});
	it('should success for p12', function (next) {
		request.get(test.url + '/api/threads/' + t1 + '/' + p12, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			res.body.post.writer.should.equal('snowman');
			res.body.post.text.should.equal('post 12');
			res.body.post.head.should.false;
			next();
		});
	});
	it('given user session', function (next) {
		test.loginUser(next);
	});
	it('should fail for p21 in recycle bin', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p21, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.INVALID_CATEGORY);
			next();
		});
	});
	it('should fail for p22 in recycle bin', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p22, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.INVALID_CATEGORY);
			next();
		});
	});
	it('given admin session', function (next) {
		test.loginAdmin(next);
	});
	it('should success for p21 in recycle bin', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p21, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			next();
		});
	});
	it('should success for p22 in recycle bin', function (next) {
		request.get(test.url + '/api/threads/' + t2 + '/' + p22, function (err, res) {
			res.status.should.equal(200);
			res.body.rc.should.equal(rcs.SUCCESS);
			next();
		});
	});
});

<|endoftext|>


<commit_before>/*
   This file is part of Rogue Vision.

   Copyright (C) 2016 Daniel Reischl, Rene Rathmann, Peter Tan,
       Tobias Dorsch, Shefali Shukla, Vignesh Govindarajulu,
       Aleksander Penew, Abinav Puri

   Rogue Vision is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Rogue Vision is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with Rogue Vision.  If not, see <http://www.gnu.org/licenses/>.
*/

/* This file contains all AngularJS Services*/

angular.module('app')

.service('percentageService', function(sessionService) {
    /*
    Provides percentage data of carriers
    */
    var percentageData = [];
    function getFromDB(percentageDataType) {
        /*
        Fetches data from backend
        So far this is called each time when getAll is called, but this is probably not necessary
        */
        Papa.parse('django/dataInterface/'+percentageDataType+'?session=' +sessionService.getCurrentSession(), {
            download: true,
            dynamicTyping: true,
            complete: function(results) {
                percentageData = results.data[1];
            }
        });
    }

    this.getAll = function(percentageDataType) {
        getFromDB(percentageDataType);
        return percentageData;
    }

    this.getColorOfCarrier = function(carrier) {
        var percentageOfEnergy = percentageData[carrier - 1];
        var color = {'background-color': 'rgb(255,255,0)'};

        if(percentageOfEnergy > 1.05) {
            color = {'background-color' : 'rgb(229, 28, 52)'};
        }

        if(percentageOfEnergy <= 1.025 ) {
            color = {'background-color' : 'rgb(178,255,89)'};
        }
        return color;
    }

    return {
        getAll: this.getAll,
        getColorOfCarrier: this.getColorOfCarrier
    };
});

/* The carrierService, proved carrier data to all controllers
For now it is used to saves the carriers for comparison, chosen by the user and proved them to all controller
who need the data.
*/

angular.module('app')

.service('carrierService', function(sessionService) {
    var carriersForComparison = [];

    this.containsCarrier = function(carrierID){
        for(var i = 0; i < carriersForComparison.length; i++) {
            if (carriersForComparison[i].carrierNumber == carrierID) {
                return true;
            }
        }
        return false;
    }

    this.hasCarrier = function(carrierId) {
	    return carriersForComparison.some(function(carrier){return carrier.carrierNumber == carrierId;});
    }

    // function adds a carrier with a given ID
    this.addCarrier = function(newCarrier) {
        for(var i = 0; i < carriersForComparison.length; i++) {
            if (carriersForComparison[i].carrierNumber == newCarrier) {
                return false;
            }
        }
        carriersForComparison.push({carrierNumber: newCarrier});
        return true;
    };

    // returns the array with CarrierIDs to be compared
    this.getCarrier = function(){
        return carriersForComparison;
    }

    // deletes a carrier with a given ID
    this.deleteCarrier = function(removeCarrier) {
        for(var i = 0; i < carriersForComparison.length; i++) {
            if (carriersForComparison[i].carrierNumber == removeCarrier) {
                carriersForComparison.splice(i,1);
                return true;
            }
        }
        return false;
    }

    // this function empties the array, so that no carrier item is left inside anymore.
    this.emptyCarrierArray = function() {
        carriersForComparison.splice(0,carriersForComparison.length);
    }

    // this service returns 5 functions to the caller, which he can use.
    return {
        hasCarrier: this.hasCarrier,
        addCarrier: this.addCarrier,
        getCarrier: this.getCarrier,
        deleteCarrier: this.deleteCarrier,
        emptyCarrierArray: this.emptyCarrierArray,
    };
});

angular.module('app')

.service('sessionService', function() {
	var numberOfSessions = 0;
	var currentSession = 1;

	function update () {
	    var xmlHttp = new XMLHttpRequest();
	    // so far session, carrier and iteration have to be set - they are disregarded however
	    xmlHttp.open( "GET", 'django/dataInterface/values.request?session=1&carrier=1&iteration=1&value=currentSession', false );
	    xmlHttp.send(null);
	    //parses Http-ResponseText to a decimal int
	    numberOfSessions = parseInt(xmlHttp.responseText,10);
	}

	this.getNumberOfSessions = function() {
	    update();
	    return numberOfSessions;
	}

	this.getCurrentSession = function() {
	    update();
	    return currentSession;
	}

	this.setCurrentSession = function(newSession) {
		currentSession = newSession;
	}

	return {
        getNumberOfSessions: this.getNumberOfSessions,
        getCurrentSession: this.getCurrentSession,
        setCurrentSession: this.setCurrentSession,
	};

});
<commit_msg>Registered contains carrier function in the carrierService<commit_after>/*
   This file is part of Rogue Vision.

   Copyright (C) 2016 Daniel Reischl, Rene Rathmann, Peter Tan,
       Tobias Dorsch, Shefali Shukla, Vignesh Govindarajulu,
       Aleksander Penew, Abinav Puri

   Rogue Vision is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Rogue Vision is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with Rogue Vision.  If not, see <http://www.gnu.org/licenses/>.
*/

/* This file contains all AngularJS Services*/

angular.module('app')

.service('percentageService', function(sessionService) {
    /*
    Provides percentage data of carriers
    */
    var percentageData = [];
    function getFromDB(percentageDataType) {
        /*
        Fetches data from backend
        So far this is called each time when getAll is called, but this is probably not necessary
        */
        Papa.parse('django/dataInterface/'+percentageDataType+'?session=' +sessionService.getCurrentSession(), {
            download: true,
            dynamicTyping: true,
            complete: function(results) {
                percentageData = results.data[1];
            }
        });
    }

    this.getAll = function(percentageDataType) {
        getFromDB(percentageDataType);
        return percentageData;
    }

    this.getColorOfCarrier = function(carrier) {
        var percentageOfEnergy = percentageData[carrier - 1];
        var color = {'background-color': 'rgb(255,255,0)'};

        if(percentageOfEnergy > 1.05) {
            color = {'background-color' : 'rgb(229, 28, 52)'};
        }

        if(percentageOfEnergy <= 1.025 ) {
            color = {'background-color' : 'rgb(178,255,89)'};
        }
        return color;
    }

    return {
        getAll: this.getAll,
        getColorOfCarrier: this.getColorOfCarrier
    };
});

/* The carrierService, proved carrier data to all controllers
For now it is used to saves the carriers for comparison, chosen by the user and proved them to all controller
who need the data.
*/

angular.module('app')

.service('carrierService', function(sessionService) {
    var carriersForComparison = [];

    this.containsCarrier = function(carrierID){
        for(var i = 0; i < carriersForComparison.length; i++) {
            if (carriersForComparison[i].carrierNumber == carrierID) {
                return true;
            }
        }
        return false;
    }

    this.hasCarrier = function(carrierId) {
	    return carriersForComparison.some(function(carrier){return carrier.carrierNumber == carrierId;});
    }

    // function adds a carrier with a given ID
    this.addCarrier = function(newCarrier) {
        for(var i = 0; i < carriersForComparison.length; i++) {
            if (carriersForComparison[i].carrierNumber == newCarrier) {
                return false;
            }
        }
        carriersForComparison.push({carrierNumber: newCarrier});
        return true;
    };

    // returns the array with CarrierIDs to be compared
    this.getCarrier = function(){
        return carriersForComparison;
    }

    // deletes a carrier with a given ID
    this.deleteCarrier = function(removeCarrier) {
        for(var i = 0; i < carriersForComparison.length; i++) {
            if (carriersForComparison[i].carrierNumber == removeCarrier) {
                carriersForComparison.splice(i,1);
                return true;
            }
        }
        return false;
    }

    // this function empties the array, so that no carrier item is left inside anymore.
    this.emptyCarrierArray = function() {
        carriersForComparison.splice(0,carriersForComparison.length);
    }

    // this service returns these functions to the caller for use
    return {
        containsCarrier: this.containsCarrier,
        hasCarrier: this.hasCarrier,
        addCarrier: this.addCarrier,
        getCarrier: this.getCarrier,
        deleteCarrier: this.deleteCarrier,
        emptyCarrierArray: this.emptyCarrierArray
    };
});

angular.module('app')

.service('sessionService', function() {
	var numberOfSessions = 0;
	var currentSession = 1;

	function update () {
	    var xmlHttp = new XMLHttpRequest();
	    // so far session, carrier and iteration have to be set - they are disregarded however
	    xmlHttp.open( "GET", 'django/dataInterface/values.request?session=1&carrier=1&iteration=1&value=currentSession', false );
	    xmlHttp.send(null);
	    //parses Http-ResponseText to a decimal int
	    numberOfSessions = parseInt(xmlHttp.responseText,10);
	}

	this.getNumberOfSessions = function() {
	    update();
	    return numberOfSessions;
	}

	this.getCurrentSession = function() {
	    update();
	    return currentSession;
	}

	this.setCurrentSession = function(newSession) {
		currentSession = newSession;
	}

	return {
        getNumberOfSessions: this.getNumberOfSessions,
        getCurrentSession: this.getCurrentSession,
        setCurrentSession: this.setCurrentSession,
	};

});
<|endoftext|>


<commit_before>define([
	'goo/entities/systems/System',
	'goo/entities/SystemBus'
],
/** @lends */
function (
	System,
	SystemBus
) {
	"use strict";

	/**
	 * @class Processes all entities with a light component making sure that lights are placed according to its transforms
	 */
	function LightingSystem() {
		System.call(this, 'LightingSystem', ['LightComponent', 'TransformComponent']);

		this.lights = [];
		this.overrideLights = null;
		this._needsUpdate = true;
	}

	LightingSystem.prototype = Object.create(System.prototype);

	LightingSystem.prototype.addedComponent = function (entity, component) {
		if (component.type !== 'LightComponent') {
			return;
		}

		if (this.lights.indexOf(component.light) === -1) {
			entity.transformComponent.setUpdated();
			this.lights.push(component.light);
			if (!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};

	LightingSystem.prototype.removedComponent = function (entity, component) {
		if (component.type !== 'LightComponent') {
			return;
		}

		var index = this.lights.indexOf(component.light);
		if (index !== -1) {
			this.lights.splice(index, 1);
			if(!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};

	/**
	 * Replaces the lights tracked by the system with custom ones.
	 * @param overrideLights
	 */
	LightingSystem.prototype.setOverrideLights = function (overrideLights) {
		this.overrideLights = overrideLights;
		SystemBus.emit('goo.setLights', this.overrideLights);
		this._needsUpdate = true;
	};

	/**
	 * Disables overriding of lights tracked by the system
	 */
	LightingSystem.prototype.clearOverrideLights = function () {
		SystemBus.emit('goo.setLights', this.lights);
		this._needsUpdate = true;
	};

	LightingSystem.prototype.process = function (entities) {
		if (!this.overrideLights) {
			for (var i = 0; i < entities.length; i++) {
				var entity = entities[i];
				var transformComponent = entity.transformComponent;
				var lightComponent = entity.lightComponent;

				if (transformComponent._updated || this._needsUpdate) {
					lightComponent.updateLight(transformComponent.worldTransform);
				}
			}
			this._needsUpdate = false;
		}
	};

	return LightingSystem;
});<commit_msg>Fix default/scene lights not updating<commit_after>define([
	'goo/entities/systems/System',
	'goo/entities/SystemBus'
],
/** @lends */
function (
	System,
	SystemBus
) {
	"use strict";

	/**
	 * @class Processes all entities with a light component making sure that lights are placed according to its transforms
	 */
	function LightingSystem() {
		System.call(this, 'LightingSystem', ['LightComponent', 'TransformComponent']);

		this.lights = [];
		this.overrideLights = null;
		this._needsUpdate = true;
	}

	LightingSystem.prototype = Object.create(System.prototype);

	LightingSystem.prototype.addedComponent = function (entity, component) {
		if (component.type !== 'LightComponent') {
			return;
		}

		if (this.lights.indexOf(component.light) === -1) {
			entity.transformComponent.setUpdated();
			this.lights.push(component.light);
			if (!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};

	LightingSystem.prototype.removedComponent = function (entity, component) {
		if (component.type !== 'LightComponent') {
			return;
		}

		var index = this.lights.indexOf(component.light);
		if (index !== -1) {
			this.lights.splice(index, 1);
			if(!this.overrideLights) {
				SystemBus.emit('goo.setLights', this.lights);
			}
		}
	};

	/**
	 * Replaces the lights tracked by the system with custom ones.
	 * @param overrideLights
	 */
	LightingSystem.prototype.setOverrideLights = function (overrideLights) {
		this.overrideLights = overrideLights;
		SystemBus.emit('goo.setLights', this.overrideLights);
		this._needsUpdate = true;
	};

	/**
	 * Disables overriding of lights tracked by the system
	 */
	LightingSystem.prototype.clearOverrideLights = function () {
		this.overrideLights = undefined;
		SystemBus.emit('goo.setLights', this.lights);
		this._needsUpdate = true;
	};

	LightingSystem.prototype.process = function (entities) {
		if (!this.overrideLights) {
			for (var i = 0; i < entities.length; i++) {
				var entity = entities[i];
				var transformComponent = entity.transformComponent;
				var lightComponent = entity.lightComponent;

				if (transformComponent._updated || this._needsUpdate) {
					lightComponent.updateLight(transformComponent.worldTransform);
				}
			}
			this._needsUpdate = false;
		}
	};

	return LightingSystem;
});<|endoftext|>


<commit_before>(function(window) {

  /** Use a single load function */
  var load = typeof require == 'function' ? require : window.load;

  /** Load Benchmark.js */
  var Benchmark =
    window.Benchmark || (
      Benchmark = load('../vendor/benchmark.js/benchmark.js') || window.Benchmark,
      Benchmark.Benchmark || Benchmark
    );

  /** Load Lo-Dash */
  var lodash =
    window.lodash || (
      lodash = load('../lodash.min.js') || window._,
      lodash = lodash._ || lodash,
      lodash.noConflict()
    );

  /** Load Underscore */
  var _ =
    window._ || (
      _ = load('../vendor/underscore/underscore-min.js') || window._,
      _._ || _
    );

  /** Used to score Lo-Dash and Underscore performance */
  var score = { 'lodash': 0, 'underscore': 0 };

  /** Used to queue benchmark suites */
  var suites = [];

  /** Add `console.log()` support for Narwhal and RingoJS */
  window.console || (window.console = { 'log': window.print });

  /** Expose functions to the global object */
  window._ = _;
  window.Benchmark = Benchmark;
  window.lodash = lodash;

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

  lodash.extend(Benchmark.options, {
    'async': true,
    'setup': function() {
      var window = Function('return this || global')(),
          _ = window._,
          lodash = window.lodash,
          numbers = [],
          object = {},
          words = [
            'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
            'seventeen', 'eighteen', 'nineteen', 'twenty'
          ];

      for (var index = 0; index < 20; index++) {
        numbers[index] = index;
        object['key' + index] = index;
      }

      var objects = lodash.map(numbers, function(n) {
        return { 'num': n };
      });
    }
  });

  lodash.extend(Benchmark.Suite.options, {
    'onStart': function() {
      console.log('\n' + this.name + ':');
    },
    'onCycle': function(event) {
      console.log(event.target + '');
    },
    'onComplete': function() {
      var fastest = this.filter('fastest').pluck('name'),
          lodashHz = 1 / (this[0].stats.mean + this[0].stats.moe),
          underscoreHz = 1 / (this[1].stats.mean + this[1].stats.moe);

      if (fastest.length > 1) {
        console.log('It\'s too close to call.');
        lodashHz = underscoreHz = Math.min(lodashHz, underscoreHz);
      } else {
        console.log(fastest + ' is the fastest.');
      }
      // add score adjusted for margin of error
      score.lodash += lodashHz;
      score.underscore += underscoreHz;

      // remove current suite from queue
      suites.shift();

      if (suites.length) {
        // run next suite
        suites[0].run();
      }
      else {
        // report results
        if (score.lodash >= score.underscore) {
          console.log('\nLo-Dash is ' + (score.lodash / score.underscore).toFixed(2) + 'x faster than Underscore.');
        } else {
          console.log('\nUnderscore is ' + (score.underscore / score.lodash).toFixed(2) + 'x faster than Lo-Dash.');
        }
      }
    }
  });

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

  suites.push(
    Benchmark.Suite('each array')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

  suites.push(
    Benchmark.Suite('each object')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

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

  suites.push(
    Benchmark.Suite('flatten deep')
      .add('Lo-Dash', function() {
        lodash.flatten([1, [2], [3, [[4]]]]);
      })
      .add('Underscore', function() {
        _.flatten([1, [2], [3, [[4]]]]);
      })
  );

  suites.push(
    Benchmark.Suite('flatten shallow')
      .add('Lo-Dash', function() {
        lodash.flatten([1, [2], [3, [[4]]]], true);
      })
      .add('Underscore', function() {
        _.flatten([1, [2], [3, [[4]]]], true);
      })
  );

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

  suites.push(
    Benchmark.Suite('groupBy with callback')
      .add('Lo-Dash', function() {
        lodash.groupBy(numbers, function(num) { return Math.floor(num); });
      })
      .add('Underscore', function() {
        _.groupBy(numbers, function(num) { return Math.floor(num); });
      })
  );

  suites.push(
    Benchmark.Suite('groupBy with property name')
      .add('Lo-Dash', function() {
        lodash.groupBy(words, 'length');
      })
      .add('Underscore', function() {
        _.groupBy(words, 'length');
      })
  );

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

  suites.push(
    Benchmark.Suite('keys')
      .add('Lo-Dash', function() {
        lodash.keys(object);
      })
      .add('Underscore', function() {
        _.keys(object);
      })
  );

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

  suites.push(
    Benchmark.Suite('map')
      .add('Lo-Dash', function() {
        lodash.map(objects, function(obj) {
          return obj.num;
        });
      })
      .add('Underscore', function() {
        _.map(objects, function(obj) {
          return obj.num;
        });
      })
  );

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

  suites.push(
    Benchmark.Suite('pluck')
      .add('Lo-Dash', function() {
        lodash.pluck(objects, 'num');
      })
      .add('Underscore', function() {
        _.pluck(objects, 'num');
      })
  );

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

  suites.push(
    Benchmark.Suite('values')
      .add('Lo-Dash', function() {
        lodash.values(objects);
      })
      .add('Underscore', function() {
        _.values(objects);
      })
  );

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

  if (Benchmark.platform + '') {
    console.log(Benchmark.platform + '');
  }
  // start suites
  suites[0].run();

}(typeof global == 'object' && global || this));
<commit_msg>Add _.difference, _.pick, and _.union benchmarks.<commit_after>(function(window) {

  /** Use a single load function */
  var load = typeof require == 'function' ? require : window.load;

  /** Load Benchmark.js */
  var Benchmark =
    window.Benchmark || (
      Benchmark = load('../vendor/benchmark.js/benchmark.js') || window.Benchmark,
      Benchmark.Benchmark || Benchmark
    );

  /** Load Lo-Dash */
  var lodash =
    window.lodash || (
      lodash = load('../lodash.min.js') || window._,
      lodash = lodash._ || lodash,
      lodash.noConflict()
    );

  /** Load Underscore */
  var _ =
    window._ || (
      _ = load('../vendor/underscore/underscore-min.js') || window._,
      _._ || _
    );

  /** Used to score Lo-Dash and Underscore performance */
  var score = { 'lodash': 0, 'underscore': 0 };

  /** Used to queue benchmark suites */
  var suites = [];

  /** Add `console.log()` support for Narwhal and RingoJS */
  window.console || (window.console = { 'log': window.print });

  /** Expose functions to the global object */
  window._ = _;
  window.Benchmark = Benchmark;
  window.lodash = lodash;

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

  lodash.extend(Benchmark.options, {
    'async': true,
    'setup': function() {
      var window = Function('return this || global')(),
          _ = window._,
          lodash = window.lodash,
          numbers = [],
          object = {},
          words = [
            'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
            'seventeen', 'eighteen', 'nineteen', 'twenty'
          ];

      for (var index = 0; index < 20; index++) {
        numbers[index] = index;
        object['key' + index] = index;
      }

      var objects = lodash.map(numbers, function(n) {
        return { 'num': n };
      });
    }
  });

  lodash.extend(Benchmark.Suite.options, {
    'onStart': function() {
      console.log('\n' + this.name + ':');
    },
    'onCycle': function(event) {
      console.log(event.target + '');
    },
    'onComplete': function() {
      var fastest = this.filter('fastest').pluck('name'),
          lodashHz = 1 / (this[0].stats.mean + this[0].stats.moe),
          underscoreHz = 1 / (this[1].stats.mean + this[1].stats.moe);

      if (fastest.length > 1) {
        console.log('It\'s too close to call.');
        lodashHz = underscoreHz = Math.min(lodashHz, underscoreHz);
      } else {
        console.log(fastest + ' is the fastest.');
      }
      // add score adjusted for margin of error
      score.lodash += lodashHz;
      score.underscore += underscoreHz;

      // remove current suite from queue
      suites.shift();

      if (suites.length) {
        // run next suite
        suites[0].run();
      }
      else {
        // report results
        if (score.lodash >= score.underscore) {
          console.log('\nLo-Dash is ' + (score.lodash / score.underscore).toFixed(2) + 'x faster than Underscore.');
        } else {
          console.log('\nUnderscore is ' + (score.underscore / score.lodash).toFixed(2) + 'x faster than Lo-Dash.');
        }
      }
    }
  });

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

  suites.push(
    Benchmark.Suite('each array')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

  suites.push(
    Benchmark.Suite('each object')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

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

  suites.push(
    Benchmark.Suite('flatten deep')
      .add('Lo-Dash', function() {
        lodash.flatten([1, [2], [3, [[4]]]]);
      })
      .add('Underscore', function() {
        _.flatten([1, [2], [3, [[4]]]]);
      })
  );

  suites.push(
    Benchmark.Suite('flatten shallow')
      .add('Lo-Dash', function() {
        lodash.flatten([1, [2], [3, [[4]]]], true);
      })
      .add('Underscore', function() {
        _.flatten([1, [2], [3, [[4]]]], true);
      })
  );

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

  suites.push(
    Benchmark.Suite('difference')
      .add('Lo-Dash', function() {
        lodash.difference(numbers, [5, 25, 10, 30]);
      })
      .add('Underscore', function() {
        _.difference(numbers, [5, 25, 10, 30]);
      })
  );

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

  suites.push(
    Benchmark.Suite('groupBy callback')
      .add('Lo-Dash', function() {
        lodash.groupBy(numbers, function(num) { return Math.floor(num); });
      })
      .add('Underscore', function() {
        _.groupBy(numbers, function(num) { return Math.floor(num); });
      })
  );

  suites.push(
    Benchmark.Suite('groupBy property name')
      .add('Lo-Dash', function() {
        lodash.groupBy(words, 'length');
      })
      .add('Underscore', function() {
        _.groupBy(words, 'length');
      })
  );

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

  suites.push(
    Benchmark.Suite('keys')
      .add('Lo-Dash', function() {
        lodash.keys(object);
      })
      .add('Underscore', function() {
        _.keys(object);
      })
  );

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

  suites.push(
    Benchmark.Suite('map')
      .add('Lo-Dash', function() {
        lodash.map(objects, function(obj) {
          return obj.num;
        });
      })
      .add('Underscore', function() {
        _.map(objects, function(obj) {
          return obj.num;
        });
      })
  );
  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pick')
      .add('Lo-Dash', function() {
        lodash.pick(object, 'key6', 'key13');
      })
      .add('Underscore', function() {
        _.pick(object, 'key6', 'key13');
      })
  );

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

  suites.push(
    Benchmark.Suite('pluck')
      .add('Lo-Dash', function() {
        lodash.pluck(objects, 'num');
      })
      .add('Underscore', function() {
        _.pluck(objects, 'num');
      })
  );

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

  suites.push(
    Benchmark.Suite('union')
      .add('Lo-Dash', function() {
        lodash.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
      })
      .add('Underscore', function() {
        _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
      })
  );

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

  suites.push(
    Benchmark.Suite('values')
      .add('Lo-Dash', function() {
        lodash.values(objects);
      })
      .add('Underscore', function() {
        _.values(objects);
      })
  );

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

  if (Benchmark.platform + '') {
    console.log(Benchmark.platform + '');
  }
  // start suites
  suites[0].run();

}(typeof global == 'object' && global || this));
<|endoftext|>


<commit_before>// @flow
import * as React from "react";
import { Hero } from "@components/hero";
import { Type } from "@components/typography";
import { ContentSection, ContentSections } from "@components/content-section";
import { Button, Buttons } from "@components/button";
import { Video } from "@components/video";
import { detectPlatform, getDownloadUrl } from "@lib";
import DemoVideo from "@components/demo-video";

import type { Context } from "next";

class SDK extends React.Component<OSProps> {
  render() {
    return (
      <>
        <Hero color="#232323">
          <Hero.Pane padding="0 20px 0 0">
            <Hero.Title>
              Bringing the power of notebooks to every application
            </Hero.Title>

            <Type.p>
              The nteract core SDK is a set of React components and JavaScript
              packages that allow you to build your own interactive notebook
              applications. The nteract team uses the core SDK to build
              nteract's suite of applications. The same SDK is available for you
              to build your own interactive notebook apps.
            </Type.p>
          </Hero.Pane>

          <Hero.Pane visual padding="40px 0 0 0">
            <DemoVideo />
          </Hero.Pane>
        </Hero>
        <ContentSections>
          <ContentSection>
            <ContentSection.Pane>
              <ContentSection.Title>
                Get started with the core SDK
              </ContentSection.Title>
              <Type.p>
                To get started building nteract-based apps with our SDK, please
                visit{" "}

                  our documentation

                .
              </Type.p>
            </ContentSection.Pane>
            <ContentSection.Pane visual>
              <Video mp4="https://github.com/nteract/logos/raw/master/nteract_logo_cube_book/exports/animations/nteract_logo_wide_idle_animation.mp4" />
            </ContentSection.Pane>
          </ContentSection>
          <ContentSection>
            <ContentSection.Pane>
              <ContentSection.Title>
                Composable and intuitive
              </ContentSection.Title>
              <Type.p>
                The nteract core SDK provides a set of components and packages
                that you can use to build your own notebook UI. These components
                and packages are composable, so you can swap them out with your
                implementations when needed or wrap them with your own
                functionality. Enjoy the freedom and think outside the box!
              </Type.p>
            </ContentSection.Pane>
            <ContentSection.Pane>
              <ContentSection.Title>
                Built on dependable technologies
              </ContentSection.Title>
              <Type.p>
                The nteract core SDK is built on top of popular and dependable
                technologies like React, Redux, and RxJS. In addition to the
                functionality provided by the nteract core SDK, you can leverage
                the resources and extensions of these technologies in your
                nteract-based applications.
              </Type.p>
            </ContentSection.Pane>
          </ContentSection>
          <ContentSection>
            <ContentSection.Pane>
              <ContentSection.Title>
                Data Explorer
              </ContentSection.Title>
              <Type.p>
                A GUI-driven way to visualize your dataframes (and dataframe-like data) using a variety of charting methods that can also be deployed as a stand-alone module. See the {" "}

                  documentation here

                .
              </Type.p>
            </ContentSection.Pane>
            <ContentSection.Pane visual>
                          </ContentSection.Pane>
          </ContentSection>
          <ContentSection>
            <ContentSection.Pane>
              <ContentSection.Title>
                Semiotic
              </ContentSection.Title>
              <Type.p>
                A React-based data visualization library with rich annotations, network visualization, summary charts, interactivity and more.

                  Check out the interactive documentation.
                 (It also has bar charts and lines charts)
              </Type.p>
            </ContentSection.Pane>
            <ContentSection.Pane visual>

            </ContentSection.Pane>
          </ContentSection>

        </ContentSections>
      </>
    );
  }
}

export default SDK;
<commit_msg>40px Hero?<commit_after>// @flow
import * as React from "react";
import { Hero } from "@components/hero";
import { Type } from "@components/typography";
import { ContentSection, ContentSections } from "@components/content-section";
import { Header } from "@components/header";
import { Video } from "@components/video";
import { detectPlatform, getDownloadUrl } from "@lib";
import DemoVideo from "@components/demo-video";
import styled, { css } from "styled-components";

import type { Context } from "next";

const FortyPXHero = styled.div`
  height: 40px;
  overflow: hidden;
  width: 100%;
`;

class SDK extends React.Component<OSProps> {
  render() {
    return (
      <>
        <Hero color="#232323">
          <Hero.Pane padding="0 20px 0 0">
            <Hero.Title>
              Bringing the power of notebooks to every application
            </Hero.Title>

            <Type.p>
              The nteract core SDK is a set of React components and JavaScript
              packages that allow you to build your own interactive notebook
              applications. The nteract team uses the core SDK to build
              nteract's suite of applications. The same SDK is available for you
              to build your own interactive notebook apps.
            </Type.p>
          </Hero.Pane>

          <Hero.Pane visual padding="40px 0 0 0">
            <DemoVideo />
          </Hero.Pane>
        </Hero>
        <ContentSections>
          <ContentSection>
            <ContentSection.Pane>
              <ContentSection.Title>
                Get started with the core SDK
              </ContentSection.Title>
              <Type.p>
                To get started building nteract-based apps with our SDK, please
                visit{" "}

                  our documentation

                .
              </Type.p>
            </ContentSection.Pane>
            <ContentSection.Pane visual>
              <Video mp4="https://github.com/nteract/logos/raw/master/nteract_logo_cube_book/exports/animations/nteract_logo_wide_idle_animation.mp4" />
            </ContentSection.Pane>
          </ContentSection>
          <ContentSection>
            <ContentSection.Pane>
              <ContentSection.Title>
                Composable and intuitive
              </ContentSection.Title>
              <Type.p>
                The nteract core SDK provides a set of components and packages
                that you can use to build your own notebook UI. These components
                and packages are composable, so you can swap them out with your
                implementations when needed or wrap them with your own
                functionality. Enjoy the freedom and think outside the box!
              </Type.p>
            </ContentSection.Pane>
            <ContentSection.Pane>
              <ContentSection.Title>
                Built on dependable technologies
              </ContentSection.Title>
              <Type.p>
                The nteract core SDK is built on top of popular and dependable
                technologies like React, Redux, and RxJS. In addition to the
                functionality provided by the nteract core SDK, you can leverage
                the resources and extensions of these technologies in your
                nteract-based applications.
              </Type.p>
            </ContentSection.Pane>
          </ContentSection>
          <FortyPXHero>
            <Hero color="#232323" />
          </FortyPXHero>
          <ContentSection>
            <ContentSection.Pane>
              <ContentSection.Title>
                Data Explorer
              </ContentSection.Title>
              <Type.p>
                A GUI-driven way to visualize your dataframes (and dataframe-like data) using a variety of charting methods that can also be deployed as a stand-alone module. See the {" "}

                  documentation here

                .
              </Type.p>
            </ContentSection.Pane>
            <ContentSection.Pane visual>
                          </ContentSection.Pane>
          </ContentSection>
          <ContentSection>
            <ContentSection.Pane>
              <ContentSection.Title>
                Semiotic
              </ContentSection.Title>
              <Type.p>
                A React-based data visualization library with rich annotations, network visualization, summary charts, interactivity and more.

                  Check out the interactive documentation.
                 (It also has bar charts and lines charts)
              </Type.p>
            </ContentSection.Pane>
            <ContentSection.Pane visual>

            </ContentSection.Pane>
          </ContentSection>

        </ContentSections>
      </>
    );
  }
}

export default SDK;
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs');
var path = require('path')
var db = require('../DatabaseManager.js');
var dbr = require('../DBRow.js');
var log = require('../log.js');
var lit = require('../Literals.js');

var possibleTypes = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'config/SQLDatatypes.json'), 'utf8'))
var defaults = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'config/defaultTables.json'), 'utf8'))
var demodata = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'config/mockData.json'), 'utf8'))

var dbm = new db.DatabaseManager();
var numCreated = 0;

exports.setupDatabase = function() {
	log.info("~~~~~~~~~~~~~~Starting Database Setup~~~~~~~~~~~~~~~")

	var totalLength = Object.keys(defaults).length;
	numCreated = 0;

	for (var prop in defaults) {
		createTable(defaults[prop][lit.TABLE_NAME], defaults[prop][lit.FIELDS], totalLength, numCreated);
	}
}

exports.loadDemoData = function() {
	log.info("~~~~~~~~~~~~~~Loading Demo Data~~~~~~~~~~~~~~~")
	var totalLength = Object.keys(demodata).length;
	numCreated = 0;
	for (var element in demodata) {
		loadRow(demodata[element][lit.TABLE], demodata[element], totalLength, numCreated);
	}
}

function loadRow(table, fields, numElementsToCreate, numberCreated) {
	var newRow = new dbr.DBRow(table);
	newRow.setId = false;
	for (var field in fields) {
		if (field == lit.TABLE)
			continue

		newRow.addQuery(field, fields[field]);
	}

	var id = newRow.getValue(lit.FIELD_ID);

	newRow.insert().then(function() {
		log.info("Example row no. " + numCreated + " created!");
		numCreated++;
		if (numElementsToCreate == numCreated)
			log.info("~~~~~~~~~~~~~~~End of Demo Data Load~~~~~~~~~~~~~~~~\n\n");
	}, function(err){
		log.warn("Row no. " + numCreated + " not inserted, likely due to a previously logged error");
		log.warn("The id of the failing row was '" + id + "'");
		numCreated++;
		if (numElementsToCreate == numCreated)
			log.info("~~~~~~~~~~~~~~~End of Demo Data Load~~~~~~~~~~~~~~~~\n")

	});
}

function createTable(tableName, fields, numberTablesToCreate, numberCreated) { //TODO: make this more intelligent to match changes to defaultTables.json
	var keyCount = 0;
	var queryString = 'CREATE TABLE ' + tableName + ' (';

	for (var field in fields) {
		if(keyCount < Object.keys(fields).length-1) {
			queryString += field + ' ' + possibleTypes[fields[field][lit.TYPE]];
			if (fields[field][lit.DEFAULT]) {
				if (fields[field][lit.DEFAULT] == 'CURRENT_TIMESTAMP' || fields[field][lit.DEFAULT] == 'GETDATE()') {
					queryString += " DEFAULT " + fields[field][lit.DEFAULT];
				}
				else {
					queryString += " DEFAULT '" + fields[field][lit.DEFAULT] + "'";
				}
			}

			if (fields[field]["PRIMARY_KEY"])
				queryString += " PRIMARY KEY"

			if (fields[field]["constraint"])
				queryString += " " + fields[field]["constraint"];

			queryString += ', ';
			keyCount++;
		}
		else {
			queryString += field + ' ' + possibleTypes[fields[field]["TYPE"]];
			if (fields[field][lit.DEFAULT]){ //make this better
				if (fields[field][lit.DEFAULT] == 'CURRENT_TIMESTAMP' || fields[field][lit.DEFAULT] == 'GETDATE()') {
					queryString += " DEFAULT " + fields[field][lit.DEFAULT];
				}
				else {
					queryString += " DEFAULT '" + fields[field][lit.DEFAULT] + "'";
				}
			}

			if (fields[field][lit.PRIMARY_KEY])
				queryString += " PRIMARY KEY"

			queryString += ')';
		}
	}

	dbm.query(queryString).then(function(){
		numCreated++;
		log.info("Table '" + tableName + "' created!");
		if (numberTablesToCreate == numCreated)
			log.info("~~~~~~~~~~~~~~~End of Database Setup~~~~~~~~~~~~~~~~\n\n")
	}, function(err){
		numCreated++;
		log.warn("Table '" + tableName + "' not created! Likely due to a previously logged error")
		if (numberTablesToCreate == numCreated)
			log.info("~~~~~~~~~~~~~~~End of Database Setup~~~~~~~~~~~~~~~~\n")

	});
}<commit_msg>FIX: unintended variable change from refactoring<commit_after>"use strict";

var fs = require('fs');
var path = require('path')
var db = require('../DatabaseManager.js');
var dbr = require('../DBRow.js');
var log = require('../log.js');
var lit = require('../Literals.js');

var possibleTypes = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'config/SQLDatatypes.json'), 'utf8'))
var defaults = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'config/defaultTables.json'), 'utf8'))
var demodata = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'config/mockData.json'), 'utf8'))

var dbm = new db.DatabaseManager();
var numCreated = 0;

exports.setupDatabase = function() {
	log.info("~~~~~~~~~~~~~~Starting Database Setup~~~~~~~~~~~~~~~")

	var totalLength = Object.keys(defaults).length;
	numCreated = 0;

	for (var prop in defaults) {
		createTable(defaults[prop][lit.TABLE_NAME], defaults[prop][lit.FIELDS], totalLength, numCreated);
	}
}

exports.loadDemoData = function() {
	log.info("~~~~~~~~~~~~~~Loading Demo Data~~~~~~~~~~~~~~~")
	var totalLength = Object.keys(demodata).length;
	numCreated = 0;
	for (var element in demodata) {
		loadRow(demodata[element][lit.TABLE], demodata[element], totalLength, numCreated);
	}
}

function loadRow(table, fields, numElementsToCreate, numberCreated) {
	var newRow = new dbr.DBRow(table);
	newRow.setId = false;
	for (var field in fields) {
		if (field == lit.TABLE)
			continue

		newRow.addQuery(field, fields[field]);
	}

	var id = newRow.getValue(lit.FIELD_ID);

	newRow.insert().then(function() {
		log.info("Example row no. " + numCreated + " created!");
		numCreated++;
		if (numElementsToCreate == numCreated)
			log.info("~~~~~~~~~~~~~~~End of Demo Data Load~~~~~~~~~~~~~~~~\n\n");
	}, function(err){
		log.warn("Row no. " + numCreated + " not inserted, likely due to a previously logged error");
		log.warn("The id of the failing row was '" + id + "'");
		numCreated++;
		if (numElementsToCreate == numCreated)
			log.info("~~~~~~~~~~~~~~~End of Demo Data Load~~~~~~~~~~~~~~~~\n")

	});
}

function createTable(tableName, fields, numberTablesToCreate, numberCreated) { //TODO: make this more intelligent to match changes to defaultTables.json
	var keyCount = 0;
	var queryString = 'CREATE TABLE ' + tableName + ' (';

	for (var field in fields) {
		if(keyCount < Object.keys(fields).length-1) {
			queryString += field + ' ' + possibleTypes[fields[field][lit.TYPE]];
			if (fields[field][lit.DEFAULT]) {
				if (fields[field][lit.DEFAULT] == 'CURRENT_TIMESTAMP' || fields[field][lit.DEFAULT] == 'GETDATE()') {
					queryString += " DEFAULT " + fields[field][lit.DEFAULT];
				}
				else {
					queryString += " DEFAULT '" + fields[field][lit.DEFAULT] + "'";
				}
			}

			if (fields[field][lit.PRIMARY_KEY])
				queryString += " PRIMARY KEY"

			if (fields[field]["constraint"])
				queryString += " " + fields[field]["constraint"];

			queryString += ', ';
			keyCount++;
		}
		else {
			queryString += field + ' ' + possibleTypes[fields[field][lit.TYPE]];
			if (fields[field][lit.DEFAULT]){ //make this better
				if (fields[field][lit.DEFAULT] == 'CURRENT_TIMESTAMP' || fields[field][lit.DEFAULT] == 'GETDATE()') {
					queryString += " DEFAULT " + fields[field][lit.DEFAULT];
				}
				else {
					queryString += " DEFAULT '" + fields[field][lit.DEFAULT] + "'";
				}
			}

			if (fields[field][lit.PRIMARY_KEY])
				queryString += " PRIMARY KEY"

			queryString += ')';
		}
	}

	dbm.query(queryString).then(function(){
		numCreated++;
		log.info("Table '" + tableName + "' created!");
		if (numberTablesToCreate == numCreated)
			log.info("~~~~~~~~~~~~~~~End of Database Setup~~~~~~~~~~~~~~~~\n\n")
	}, function(err){
		numCreated++;
		log.warn("Table '" + tableName + "' not created! Likely due to a previously logged error")
		if (numberTablesToCreate == numCreated)
			log.info("~~~~~~~~~~~~~~~End of Database Setup~~~~~~~~~~~~~~~~\n")

	});
}<|endoftext|>


<commit_before>var DOG_MAX = 4;
var DOG_MOV_SPEED = 64;

var DOG_STATE_IDLE = 0;
var DOG_STATE_ATTACKING = 1;
var DOG_STATE_RUNNING = 2;

var dogs = [];

function dog_init()
{
    for(var i = 0; i < DOG_MAX; ++i)
    {
        // MC: TODO Looks like this is too soon to Call. Gamepad connects later.
        //if (GamePad.isConnected(index))
        {
            var dog = {
                position: new Vector2(Random.randCircle(MAP_CENTER, TILE_SIZE * 3)),
                dir: "s", // we start facing south.
                state: DOG_STATE_IDLE,
                pushBackVel: new Vector2(0, 0)
            }

            // MC: TODO Figure out why this is doing a segfault.
            //dog.spriteAnim = playSpriteAnim("anims/dog.spriteanim", "idle_s"),

            dogs.push(dog);
        }

    }
}

function dog_update(dt)
{
    for (var i = 0; i < dogs.length; ++i)
    {
        var dog = dogs[i];

        var previousPosition = dog.position;
        var newPosition = dog.position.add(dog.pushBackVel.mul(dt));

        var dir = GamePad.getLeftThumb(i);

        if (GamePad.isDown(i, Button.DPAD_RIGHT)) dir.x += 1;
        if (GamePad.isDown(i, Button.DPAD_LEFT))  dir.x -= 1;
        if (GamePad.isDown(i, Button.DPAD_UP))    dir.y -= 1;
        if (GamePad.isDown(i, Button.DPAD_DOWN))  dir.y += 1;

        if (dir.lengthSquared() == 0)
        {
            //dog.spriteAnim.play("idle_" + dog.dir);
            dog.state = DOG_STATE_IDLE;
        }
        else
        {
            dir = dir.normalize();
            if (dir.y > .7) dog.dir = 's';
            else if (dir.x > .7) dog.dir = 'e';
            else if (dir.x < .7) dog.dir = 'w';
            else dog.dir = 'n';
            //dog.spriteAnim.play("run_" + dog.dir);
            dog.state = DOG_STATE_RUNNING;

            newPosition = newPosition.add(dir.mul(DOG_MOV_SPEED * dt));
        }

        dog.position = newPosition;
    }
}

function dog_render()
{
    for (var i = 0; i < dogs.length; ++i)
    {
        var dog = dogs[i];
        SpriteBatch.drawSpriteAnim(dog.spriteAnim, dog.position);
    }
}<commit_msg>Dog Attack + Bark WIP<commit_after>var DOG_MAX = 4;
var DOG_MOV_SPEED = 64;

var DOG_STATE_IDLE = 0;
var DOG_STATE_ATTACKING = 1;
var DOG_STATE_RUNNING = 2;
var DOG_STATE_BARKING = 3;

var dogs = [];

function dog_init()
{
    for(var i = 0; i < DOG_MAX; ++i)
    {
        // MC: TODO Looks like this is too soon to Call. Gamepad connects later.
        //if (GamePad.isConnected(index))
        {
            var dog = {
                position: new Vector2(Random.randCircle(MAP_CENTER, TILE_SIZE * 3)),
                dir: "s", // we start facing south.
                state: DOG_STATE_IDLE,
                pushBackVel: new Vector2(0, 0)
            }

            // MC: TODO Figure out why this is doing a segfault.
            //dog.spriteAnim = playSpriteAnim("anims/dog.spriteanim", "idle_s"),

            dogs.push(dog);
        }
    }
}

function dog_update(dt)
{
    for (var i = 0; i < dogs.length; ++i)
    {
        var dog = dogs[i];

        var previousPosition = dog.position;
        var newPosition = dog.position.add(dog.pushBackVel.mul(dt));

        var dir = GamePad.getLeftThumb(i);

        if (GamePad.isDown(i, Button.DPAD_RIGHT)) dir.x += 1;
        if (GamePad.isDown(i, Button.DPAD_LEFT))  dir.x -= 1;
        if (GamePad.isDown(i, Button.DPAD_UP))    dir.y -= 1;
        if (GamePad.isDown(i, Button.DPAD_DOWN))  dir.y += 1;

        if (dir.lengthSquared() == 0)
        {
            dog.state = DOG_STATE_IDLE;
        }
        else
        {
            dir = dir.normalize();
            if (dir.y > .7) dog.dir = 's';
            else if (dir.x > .7) dog.dir = 'e';
            else if (dir.x < .7) dog.dir = 'w';
            else dog.dir = 'n';
            //dog.spriteAnim.play("run_" + dog.dir);
            dog.state = DOG_STATE_RUNNING;

            newPosition = newPosition.add(dir.mul(DOG_MOV_SPEED * dt));
        }

        //MC TODO. Still not sure what sound file we're going to have, but
        // it might be a good idea to have a few samples of 4 different dogs
        // We don't want all the bark sounds to sound all the same. for example
        // if player 1 presses "X", it would play dog_bark_0_[0-3].wav while
        // player 2 would play  dog_bark_1_[0-3].wav

        if(GamePad.isJustDown(i, Button.A))
        {
            //playSound("dog_growl_" + i + "_" + Random.randInt(3) + ".wav", .5);
            dog.state = DOG_STATE_ATTACKING;
        }

        if(GamePad.isJustDown(i, Button.X))
        {
            //playSound("dog_bark_" + i + "_" + Random.randInt(3) + ".wav", .5);
            print("Dog " + i + ": Woof!");
            dog.state = DOG_STATE_RUNNING;
        }

        switch(dog.state)
        {
            case DOG_STATE_IDLE:
                //dog.spriteAnim.play("idle_" + dog.dir);
                break;

        }

        dog.position = newPosition;
    }
}

function dog_render()
{
    for (var i = 0; i < dogs.length; ++i)
    {
        var dog = dogs[i];
        SpriteBatch.drawSpriteAnim(dog.spriteAnim, dog.position);
    }
}<|endoftext|>


<commit_before>var app = require('express')();
module.exports = app;
<commit_msg>removed it'<commit_after><|endoftext|>