<commit_before>'use strict';

var _ = require('lodash'),
  apiAccepts = require('../../fixtures/api-accepts'),
  endpointName = _.startCase(__dirname.split('/').pop()),
  filename = _.startCase(__filename.split('/').pop().split('.').shift()),
  sinon = require('sinon');

describe(endpointName, function () {
  describe(filename, function () {
    var sandbox,
      hostname = 'localhost.example.com',
      acceptsJson = apiAccepts.acceptsJson(_.camelCase(filename)),
      acceptsHtml = apiAccepts.acceptsHtml(_.camelCase(filename)),
      data = { name: 'Manny', species: 'cat' },
      componentList = [ 'byline-c5', 'byline-c3', 'byline-c4' ],
      message406 = '406 text/html not acceptable';

    beforeEach(function () {
      sandbox = sinon.sandbox.create();
      return apiAccepts.beforeEachComponentTest(sandbox,  hostname, data);
    });

    afterEach(function () {
      sandbox.restore();
    });

    describe('/components', function () {
      var path = this.title;
      acceptsJson(path, {}, 200, componentList);
      acceptsHtml(path, {}, 406, message406);
    });

    describe('/components/:name', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid'}, 404);
      acceptsJson(path, {name: 'valid'}, 200, data);
      acceptsJson(path, {name: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid'}, 406, message406);
      acceptsHtml(path, {name: 'missing'}, 406, message406);
    });

    describe('/components/:name/schema', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid'}, 404);
      acceptsJson(path, {name: 'valid'}, 200, {some:'schema', thatIs:'valid'});
      acceptsJson(path, {name: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid'}, 406, message406);
      acceptsHtml(path, {name: 'missing'}, 406, message406);
    });

    describe('/components/:name.html', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid'}, 404);
      acceptsJson(path, {name: 'valid'}, 406, '{"message":"application/json not acceptable","code":406,"accept":["text/html"]}');
      acceptsJson(path, {name: 'missing'}, 406, '{"message":"application/json not acceptable","code":406,"accept":["text/html"]}');

      acceptsHtml(path, {name: 'invalid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid'}, 200,
        '<valid>{' +
        '"refs":{"localhost.example.com/components/valid":{"name":"Manny","species":"cat","template":"valid","_self":"localhost.example.com/components/valid"}},' +
        '"components":["valid"],' +
        '"name":"Manny",' +
        '"species":"cat",' +
        '"template":"valid",' +
        '"_self":"localhost.example.com/components/valid"' +
        '}</valid>');
      acceptsHtml(path, {name: 'missing'}, 404, '404 Not Found');
    });

    describe('/components/:name@:version', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid', version: 'missing'}, 404);
      acceptsJson(path, {name: 'valid', version: 'missing'}, 404);
      acceptsJson(path, {name: 'missing', version: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid', version: 'missing'}, 404);
      acceptsHtml(path, {name: 'valid', version: 'missing'}, 406);
      acceptsHtml(path, {name: 'missing', version: 'missing'}, 406);
    });

    describe('/components/:name/instances', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid'}, 404);
      acceptsJson(path, {name: 'valid'}, 200, '["localhost.example.com/components/valid/instances/valid"]');
      acceptsJson(path, {name: 'missing'}, 200, '[]');

      acceptsHtml(path, {name: 'invalid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid'}, 406);
      acceptsHtml(path, {name: 'missing'}, 406);
    });

    describe('/components/:name/instances/:id', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid', id: 'valid'}, 404);
      acceptsJson(path, {name: 'valid', id: 'valid'}, 200, data);
      acceptsJson(path, {name: 'valid', id: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid', id: 'valid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid', id: 'valid'}, 406);
      acceptsHtml(path, {name: 'valid', id: 'missing'}, 406);
    });

    describe('/components/:name/instances/:id.html', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid', id: 'valid'}, 404);
      acceptsJson(path, {name: 'valid', id: 'valid'}, 406, '{"message":"application/json not acceptable","code":406,"accept":["text/html"]}');
      acceptsJson(path, {name: 'valid', id: 'missing'}, 406, '{"message":"application/json not acceptable","code":406,"accept":["text/html"]}');

      acceptsHtml(path, {name: 'invalid', id: 'valid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid', id: 'valid'}, 200, '<valid>{' +
        '"refs":{"localhost.example.com/components/valid/instances/valid":{"name":"Manny","species":"cat","template":"valid","_self":"localhost.example.com/components/valid/instances/valid"}},' +
        '"components":["valid"],' +
        '"name":"Manny",' +
        '"species":"cat",' +
        '"template":"valid",' +
        '"_self":"localhost.example.com/components/valid/instances/valid"' +
        '}</valid>');
      acceptsHtml(path, {name: 'valid', id: 'missing'}, 404, '404 Not Found');
    });

    describe('/components/:name/instances/:id@:version', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid', version: 'missing', id: 'valid'}, 404);
      acceptsJson(path, {name: 'valid', version: 'missing', id: 'valid'}, 404);
      acceptsJson(path, {name: 'valid', version: 'missing', id: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid', version: 'missing', id: 'valid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid', version: 'missing', id: 'valid'}, 406);
      acceptsHtml(path, {name: 'valid', version: 'missing', id: 'missing'}, 406);
    });
  });
});
<commit_msg>fixed test<commit_after>'use strict';

var _ = require('lodash'),
  apiAccepts = require('../../fixtures/api-accepts'),
  endpointName = _.startCase(__dirname.split('/').pop()),
  filename = _.startCase(__filename.split('/').pop().split('.').shift()),
  sinon = require('sinon');

describe(endpointName, function () {
  describe(filename, function () {
    var sandbox,
      hostname = 'localhost.example.com',
      acceptsJson = apiAccepts.acceptsJson(_.camelCase(filename)),
      acceptsHtml = apiAccepts.acceptsHtml(_.camelCase(filename)),
      data = { name: 'Manny', species: 'cat' },
      componentList = [ 'clay-c5', 'clay-c3', 'clay-c4' ],
      message406 = '406 text/html not acceptable';

    beforeEach(function () {
      sandbox = sinon.sandbox.create();
      return apiAccepts.beforeEachComponentTest(sandbox,  hostname, data);
    });

    afterEach(function () {
      sandbox.restore();
    });

    describe('/components', function () {
      var path = this.title;
      acceptsJson(path, {}, 200, componentList);
      acceptsHtml(path, {}, 406, message406);
    });

    describe('/components/:name', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid'}, 404);
      acceptsJson(path, {name: 'valid'}, 200, data);
      acceptsJson(path, {name: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid'}, 406, message406);
      acceptsHtml(path, {name: 'missing'}, 406, message406);
    });

    describe('/components/:name/schema', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid'}, 404);
      acceptsJson(path, {name: 'valid'}, 200, {some:'schema', thatIs:'valid'});
      acceptsJson(path, {name: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid'}, 406, message406);
      acceptsHtml(path, {name: 'missing'}, 406, message406);
    });

    describe('/components/:name.html', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid'}, 404);
      acceptsJson(path, {name: 'valid'}, 406, '{"message":"application/json not acceptable","code":406,"accept":["text/html"]}');
      acceptsJson(path, {name: 'missing'}, 406, '{"message":"application/json not acceptable","code":406,"accept":["text/html"]}');

      acceptsHtml(path, {name: 'invalid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid'}, 200,
        '<valid>{' +
        '"refs":{"localhost.example.com/components/valid":{"name":"Manny","species":"cat","template":"valid","_self":"localhost.example.com/components/valid"}},' +
        '"components":["valid"],' +
        '"name":"Manny",' +
        '"species":"cat",' +
        '"template":"valid",' +
        '"_self":"localhost.example.com/components/valid"' +
        '}</valid>');
      acceptsHtml(path, {name: 'missing'}, 404, '404 Not Found');
    });

    describe('/components/:name@:version', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid', version: 'missing'}, 404);
      acceptsJson(path, {name: 'valid', version: 'missing'}, 404);
      acceptsJson(path, {name: 'missing', version: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid', version: 'missing'}, 404);
      acceptsHtml(path, {name: 'valid', version: 'missing'}, 406);
      acceptsHtml(path, {name: 'missing', version: 'missing'}, 406);
    });

    describe('/components/:name/instances', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid'}, 404);
      acceptsJson(path, {name: 'valid'}, 200, '["localhost.example.com/components/valid/instances/valid"]');
      acceptsJson(path, {name: 'missing'}, 200, '[]');

      acceptsHtml(path, {name: 'invalid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid'}, 406);
      acceptsHtml(path, {name: 'missing'}, 406);
    });

    describe('/components/:name/instances/:id', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid', id: 'valid'}, 404);
      acceptsJson(path, {name: 'valid', id: 'valid'}, 200, data);
      acceptsJson(path, {name: 'valid', id: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid', id: 'valid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid', id: 'valid'}, 406);
      acceptsHtml(path, {name: 'valid', id: 'missing'}, 406);
    });

    describe('/components/:name/instances/:id.html', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid', id: 'valid'}, 404);
      acceptsJson(path, {name: 'valid', id: 'valid'}, 406, '{"message":"application/json not acceptable","code":406,"accept":["text/html"]}');
      acceptsJson(path, {name: 'valid', id: 'missing'}, 406, '{"message":"application/json not acceptable","code":406,"accept":["text/html"]}');

      acceptsHtml(path, {name: 'invalid', id: 'valid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid', id: 'valid'}, 200, '<valid>{' +
        '"refs":{"localhost.example.com/components/valid/instances/valid":{"name":"Manny","species":"cat","template":"valid","_self":"localhost.example.com/components/valid/instances/valid"}},' +
        '"components":["valid"],' +
        '"name":"Manny",' +
        '"species":"cat",' +
        '"template":"valid",' +
        '"_self":"localhost.example.com/components/valid/instances/valid"' +
        '}</valid>');
      acceptsHtml(path, {name: 'valid', id: 'missing'}, 404, '404 Not Found');
    });

    describe('/components/:name/instances/:id@:version', function () {
      var path = this.title;

      acceptsJson(path, {name: 'invalid', version: 'missing', id: 'valid'}, 404);
      acceptsJson(path, {name: 'valid', version: 'missing', id: 'valid'}, 404);
      acceptsJson(path, {name: 'valid', version: 'missing', id: 'missing'}, 404);

      acceptsHtml(path, {name: 'invalid', version: 'missing', id: 'valid'}, 404, '404 Not Found');
      acceptsHtml(path, {name: 'valid', version: 'missing', id: 'valid'}, 406);
      acceptsHtml(path, {name: 'valid', version: 'missing', id: 'missing'}, 406);
    });
  });
});
<|endoftext|>


<commit_before>/* Tester for App */

var clientenv = require('../helpers/helper.spec.js'),
    should = require('should'),
    sinon = require('sinon');

describe('userModel', function() {

  var User;

  beforeEach(function(done) {
    clientenv.setup(function() {
      UserModel = require(appDir + 'users/userModel.js');

      fbStub = sinon.stub(global, 'Firebase');
      loginStub = sinon.stub(global, 'FirebaseSimpleLogin');

      // Fake mixpanel object
      global.mixpanel = {
        identify: sinon.stub().returns('123'),
        people: {
          set: function(data) {
            return(data);
          }
        }
      };

      done();
    });
  });

  afterEach(function() {
    fbStub.restore();
    loginStub.restore();
  });

  describe('loads the model', function() {
    it('without errors', function() {
      should.exist(UserModel);

      userModel = new UserModel();
      should.exist(userModel);
    });
  });

  describe('connects to Firebase', function() {
    it('loads Firebase with a URL', function() {
      app.fbUrl = 'http://blah.com';

      fbStub.calledOnce.should.be.false;
      userModel = new UserModel();

      fbStub.calledOnce.should.be.true;
      fbStub.getCall(0).args[0].should.equal(app.fbUrl);  // Firebsae has been called w/ URL
    });

    it('loads Firebase-Simple-Login', function() {
      loginStub.calledOnce.should.be.false;
      userModel = new UserModel();
      loginStub.calledOnce.should.be.true;  // Auth has been called
    });

  });

  describe('User signed out', function() {
    it('User can login', function() {
    });
  });

  describe('User signed in', function() {
    it('Should remain logged in', function() {
      // Input
      var input = {
        displayName: 'User Name',
        profile_image_url_https: 'http://blah.com/img.jpg',
        lastLogin: new Date(),
        username: 'username',
        loggedIn: true
      };

      loginStub.yields(null, input);  // FirebaseSimpleLogin will generate a callback which contains these two parameters

      userModel = new UserModel();

      input.displayName.should.equal(userModel.get('displayName'));
      input.profile_image_url_https.should.equal(userModel.get('profileImage'));
      should.exist(userModel.get('lastLogin')); // Time is not always synced
      input.username.should.equal(userModel.get('username'));
      input.loggedIn.should.equal(userModel.get('loggedIn'));
    });

    it('User can log out', function() {
    });
  });
});

<commit_msg>Figured out how to stub prototypes<commit_after>/* Tester for App */

var clientenv = require('../helpers/helper.spec.js'),
    should = require('should'),
    sinon = require('sinon');

describe('userModel', function() {

  var User;

  beforeEach(function(done) {
    clientenv.setup(function() {
      UserModel = require(appDir + 'users/userModel.js');

      fbStub = sinon.stub(global, 'Firebase');
      loginStub = sinon.stub(global, 'FirebaseSimpleLogin');

      // Fake mixpanel object
      global.mixpanel = {
        identify: sinon.stub().returns('123'),
        people: {
          set: function(data) {
            return(data);
          }
        }
      };

      done();
    });
  });

  afterEach(function() {
    fbStub.restore();
    loginStub.restore();
  });

  describe('loads the model', function() {
    it('without errors', function() {
      should.exist(UserModel);

      userModel = new UserModel();
      should.exist(userModel);
    });
  });

  describe('connects to Firebase', function() {
    it('loads Firebase with a URL', function() {
      app.fbUrl = 'http://blah.com';

      fbStub.calledOnce.should.be.false;
      userModel = new UserModel();

      fbStub.calledOnce.should.be.true;
      fbStub.getCall(0).args[0].should.equal(app.fbUrl);  // Firebsae has been called w/ URL
    });

    it('loads Firebase-Simple-Login', function() {
      loginStub.calledOnce.should.be.false;
      userModel = new UserModel();
      loginStub.calledOnce.should.be.true;  // Auth has been called
    });

  });

  describe('User signed out', function() {
    it('User can login', function() {
    });
  });

  describe('User signed in', function() {
    it('Should remain logged in', function() {
      // Input
      var input = {
        displayName: 'User Name',
        profile_image_url_https: 'http://blah.com/img.jpg',
        lastLogin: new Date(),
        username: 'username',
        loggedIn: true
      };

      loginStub.yields(null, input);  // FirebaseSimpleLogin will generate a callback which contains these two parameters

      userModel = new UserModel();

      input.displayName.should.equal(userModel.get('displayName'));
      input.profile_image_url_https.should.equal(userModel.get('profileImage'));
      should.exist(userModel.get('lastLogin')); // Time is not always synced
      input.username.should.equal(userModel.get('username'));
      input.loggedIn.should.equal(userModel.get('loggedIn'));
    });

    it('User can log out', function() {

      // stub out app.auth.logout
      loginStub.prototype.logout = function() {
        // Fake out logout actions (wipe user)
        console.log('got here');
      };
      // logout should trigger FirebaseSimpleLogin constructor again
      // expect model to be empty
      userModel = new UserModel();
      userModel.logout();

    });
  });
});

<|endoftext|>


<commit_before>/**
 * Windsnet wireless network access web application
 * application javascript
 */
<!--//
//AJAX process function
/**
 * Execute AJAX call
 *
 * @author David J Eddy <me@davidjeddy.com>
 * @version 0.0.1
 * @since 0.0.2
 * @date 2014-01-15
 * @param string type [optional]
 * @param string data [optional]
 * @param string method [optional]
 * @param string url [optional]
 * @return boolean
 */
function ajaxCall (type, data, dataType, url) {
	console.log( 'ajax function called' );

	if ( typeof('type') == 'undefined' ) 	{ type 	= "POST"; }
	if ( typeof('data') == 'undefined' ) 	{ data 	= "NULL"; }
	if ( typeof('dataType') == 'undefined' ){ dataType= "JSON"; }
	if ( typeof('url') == 'undefined' ) 	{ url 	= "../controllers/base_class.php"; }

    var promise = $.ajax({ type: type, data: data, dataType: dataType, url: url });

    promise.success(function(data) {
		console.log(data);

        return true;
    });

    promise.error(function(data) {
		console.log(data);

        return false;
    });

    promise.complete(function(){

		return true;
    });
}

// Form submit logic
$(document).on("submit", "form", function(e) {
	console.log( 'form submited');

	// Prevent default
	e.preventDefault();

	//if the form is 'sign in', validate both fields are populated.
	if ( $(this).attr('id') == "sign_in") {

		console.log( 'user signing in.');
	}

	return true;
});

// Form button actions
$(document).on("click", "button.clear", function(e) {
	console.log( 'btn.clear clicked');

	// Reset Val
	var form = $(this).closest( 'form' );
	form[0].reset();

	// Clear valitation errors
	var form_val = form.validate();
	form_val.resetForm();

	//scroll to the top of the page if possible
	//$().scrollto( '0%', 250);

	return true;
});

$(document).on("click", "button.next", function(e) {
	console.log( 'button.next clicked' );

	// Get form elem
	var form = $(this).closest('form');

	// Is the form currently client valid?
	if ( form.valid() != true ) {
		console.log( 'form not valid.');
		return false;
	}

	// Serialize data
	var form_data = form.serialize();

	//write data to a cookie
	$.cookie(form.attr('name'), form_data, { expires: 7, path: '/' });

	// relocate to the forms 'action' property
	window.location = "./"+form.attr('action');

	return true;
});

$(document).on("click", "button.submit", function(e) {
	console.log( 'button.submit clicked');

	//Prevent default form action
	e.preventDefault;

	// Get form elem
	var form = $(this).closest('form');

	// Is the form currently client valid?
	if ( form.valid() != true ) {
		console.log( 'form not valid.');
		return false;
	}

	//Do the AJAX call with all the form data
	ajaxCall("post", form.serialize(), "JSON", form.attr('action'));

	return true;
});

// BootBox listeners and callbacks
$(document).on("click", ".alert", function(e) {

    bootbox.alert("Hello world!", function() {
        console.log("Alert Callback");
    });
});
--><commit_msg>Removed JS $("click", "button.next"...), no longer needed.<commit_after>/**
 * Windsnet wireless network access web application
 * application javascript
 */
<!--//
//AJAX process function
/**
 * Execute AJAX call
 *
 * @author David J Eddy <me@davidjeddy.com>
 * @version 0.0.1
 * @since 0.0.2
 * @date 2014-01-15
 * @param string type [optional]
 * @param string data [optional]
 * @param string method [optional]
 * @param string url [optional]
 * @return boolean
 */
function ajaxCall (type, data, dataType, url) {
	console.log( 'ajax function called' );

	if ( typeof('type') == 'undefined' ) 	{ type 	= "POST"; }
	if ( typeof('data') == 'undefined' ) 	{ data 	= "NULL"; }
	if ( typeof('dataType') == 'undefined' ){ dataType= "JSON"; }
	if ( typeof('url') == 'undefined' ) 	{ url 	= "../controllers/base_class.php"; }

    var promise = $.ajax({ type: type, data: data, dataType: dataType, url: url });

    promise.success(function(data) {
		console.log(data);

        return true;
    });

    promise.error(function(data) {
		console.log(data);

        return false;
    });

    promise.complete(function(){

		return true;
    });
}

// Form submit logic
$(document).on("submit", "form", function(e) {
	console.log( 'form submited');

	// Prevent default
	e.preventDefault();

	//if the form is 'sign in', validate both fields are populated.
	if ( $(this).attr('id') == "sign_in") {

		console.log( 'user signing in.');
	}

	return true;
});

// Form button actions
$(document).on("click", "button.clear", function(e) {
	console.log( 'btn.clear clicked');

	// Reset Val
	var form = $(this).closest( 'form' );
	form[0].reset();

	// Clear valitation errors
	var form_val = form.validate();
	form_val.resetForm();

	//scroll to the top of the page if possible
	//$().scrollto( '0%', 250);

	return true;
});

$(document).on("click", "button.submit", function(e) {
	console.log( 'button.submit clicked');

	//Prevent default form action
	e.preventDefault;

	// Get form elem
	var form = $(this).closest('form');

	// Is the form currently client valid?
	if ( form.valid() != true ) {
		console.log( 'form not valid.');
		return false;
	}

	//Do the AJAX call with all the form data
	ajaxCall("post", form.serialize(), "JSON", form.attr('action'));

	return true;
});

// BootBox listeners and callbacks
$(document).on("click", ".alert", function(e) {

    bootbox.alert("Hello world!", function() {
        console.log("Alert Callback");
    });
});
--><|endoftext|>


<commit_before>var helper = require("./helper");
var should = require("should");

function getBasicTest(opt) {

    var options = opt || {};
    var Manager = options.manager;
    var Model = options.model;
    var dataUtil = options.util;
    var validate = options.validator;
    var createDuplicate = options.createDuplicate;
    var keys = options.keys;

    var manager;
    before("#00. connect db", function (done) {
        helper.getDb()
            .then((db) => {
                manager = new Manager(db, {
                    username: "unit-test"
                });
                done();
            })
            .catch(e => {
                done(e);
            });
    });

    it("#01. should error when create with empty data", function (done) {
        manager.create({})
            .then((id) => {
                done("Should not be able to create with empty data");
            })
            .catch((e) => {
                try {
                    e.name.should.equal("ValidationError");
                    e.should.have.property("errors");
                    e.errors.should.instanceof(Object);
                    done();
                }
                catch (ex) {
                    done(e);
                }
            });
    });

    var createdId;
    it("#02. should success when create new data", function (done) {
        dataUtil.getNewData()
            .then((data) => {
                manager.create(data)
                    .then((id) => {
                        id.should.be.Object();
                        createdId = id;
                        done();
                    })
                    .catch((e) => {
                        done(e);
                    });
            })
            .catch((e) => {
                done(e);
            });
    });

    var createdData;
    it(`#03. should success when get created data with id`, function (done) {
        manager.getSingleById(createdId)
            .then((data) => {
                data.should.instanceof(Object);
                validate(data);
                createdData = data;
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#04. should error when create new data with same key(s)", function (done) {
        if (!createDuplicate || keys.length <= 0)
            this.skip();
        else {
            var data = Object.assign({}, createdData);
            delete data._id;

            manager.create(data)
                .then((id) => {
                    done("Should not be able to create data with same key(s)");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        for (var key of keys) {
                            e.errors.should.have.property(key);
                        }
                        done();
                    }
                    catch (ex) {
                        done(e);
                    }
                });

        }
    });

    it(`#05. should success when update created data`, function (done) {
        manager.update(createdData)
            .then((id) => {
                createdId.toString().should.equal(id.toString());
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it(`#06. should success when get updated data with id`, function (done) {
        manager.getSingleById(createdId)
            .then((data) => {
                validate(data);
                data._stamp.should.not.equal(createdData._stamp);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#07. should error when update new data with same key(s)", function (done) {
        if (keys.length <= 0)
            this.skip();
        else {
            var newDataId;
            dataUtil.getNewData()
                .then((data) => manager.create(data))
                .then((newId) => manager.getSingleById(newId))
                .then((newData) => {
                    newDataId = newData._id;
                    for (var key of keys) {
                        newData[key] = createdData[key];
                    }
                    return manager.update(newData);
                })
                .then((id) => {
                    done("Should not be able to update data with key(s)");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        for (var key of keys) {
                            e.errors.should.have.property(key);
                        }
                        manager.destroy(newDataId)
                            .then(() => done());
                    }
                    catch (ex) {
                        done(e);
                    }
                });
        }
    });

    it("#08. should success when read data", function (done) {
        manager.read({
            filter: {
                _id: createdId
            }
        })
            .then((documents) => {
                //process documents
                documents.should.have.property("data");
                documents.data.should.be.instanceof(Array);
                documents.data.length.should.not.equal(0);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it(`#09. should success when delete data`, function (done) {
        manager.delete(createdData)
            .then((id) => {
                id.toString().should.equal(createdId.toString());
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it(`#10. should _deleted=true`, function (done) {
        manager.getSingleByQuery({
            _id: createdId
        })
            .then((data) => {
                validate(data);
                data._deleted.should.be.Boolean();
                data._deleted.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#11. should success when destroy data with id", function (done) {
        manager.destroy(createdId)
            .then((result) => {
                result.should.be.Boolean();
                result.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it(`#12. should null when get destroyed data`, function (done) {
        manager.getSingleByIdOrDefault(createdId)
            .then((data) => {
                should.equal(data, null);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });
}
module.exports = getBasicTest;<commit_msg>debug console<commit_after>var helper = require("./helper");
var should = require("should");

function getBasicTest(opt) {

    var options = opt || {};
    var Manager = options.manager;
    var Model = options.model;
    var dataUtil = options.util;
    var validate = options.validator;
    var createDuplicate = options.createDuplicate;
    var keys = options.keys;

    var manager;
    before("#00. connect db", function (done) {
        helper.getDb()
            .then((db) => {
                manager = new Manager(db, {
                    username: "unit-test"
                });
                done();
            })
            .catch(e => {
                done(e);
            });
    });

    it("#01. should error when create with empty data", function (done) {
        manager.create({})
            .then((id) => {
                done("Should not be able to create with empty data");
            })
            .catch((e) => {
                try {
                    e.name.should.equal("ValidationError");
                    e.should.have.property("errors");
                    e.errors.should.instanceof(Object);
                    done();
                }
                catch (ex) {
                    done(e);
                }
            });
    });

    var createdId;
    it("#02. should success when create new data", function (done) {
        dataUtil.getNewData()
            .then((data) => {
                manager.create(data)
                    .then((id) => {
                        id.should.be.Object();
                        createdId = id;
                        done();
                    })
                    .catch((e) => {
                        done(e);
                    });
            })
            .catch((e) => {
                done(e);
            });
    });

    var createdData;
    it(`#03. should success when get created data with id`, function (done) {
        manager.getSingleById(createdId)
            .then((data) => {
                data.should.instanceof(Object);
                validate(data);
                createdData = data;
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#04. should error when create new data with same key(s)", function (done) {
        if (!createDuplicate || keys.length <= 0)
            this.skip();
        else {
            var data = Object.assign({}, createdData);
            delete data._id;

            manager.create(data)
                .then((id) => {
                    done("Should not be able to create data with same key(s)");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        for (var key of keys) {
                            e.errors.should.have.property(key);
                        }
                        done();
                    }
                    catch (ex) {
                        done(e);
                    }
                });

        }
    });

    it(`#05. should success when update created data`, function (done) {
        manager.update(createdData)
            .then((id) => {
                createdId.toString().should.equal(id.toString());
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it(`#06. should success when get updated data with id`, function (done) {
        manager.getSingleById(createdId)
            .then((data) => {
                validate(data);
                data._stamp.should.not.equal(createdData._stamp);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#07. should error when update new data with same key(s)", function (done) {
        if (keys.length <= 0)
            this.skip();
        else {
            var newDataId;
            dataUtil.getNewData()
                .then((data) => manager.create(data))
                .then((newId) => manager.getSingleById(newId))
                .then((newData) => {
                    newDataId = newData._id;
                    for (var key of keys) {
                        newData[key] = createdData[key];
                    }
                    return manager.update(newData);
                })
                .then((id) => {
                    done("Should not be able to update data with key(s)");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        for (var key of keys) {
                            e.errors.should.have.property(key);
                        }
                        manager.destroy(newDataId)
                            .then(() => done());
                    }
                    catch (ex) {
                        done(e);
                    }
                });
        }
    });

    it("#08. should success when read data", function (done) {
        manager.read({
            filter: {
                _id: createdId
            }
        })
            .then((documents) => {
                //process documents
                documents.should.have.property("data");
                documents.data.should.be.instanceof(Array);
                console.log(documents.data.length);
                documents.data.length.should.not.equal(0);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it(`#09. should success when delete data`, function (done) {
        manager.delete(createdData)
            .then((id) => {
                id.toString().should.equal(createdId.toString());
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it(`#10. should _deleted=true`, function (done) {
        manager.getSingleByQuery({
            _id: createdId
        })
            .then((data) => {
                validate(data);
                data._deleted.should.be.Boolean();
                data._deleted.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#11. should success when destroy data with id", function (done) {
        manager.destroy(createdId)
            .then((result) => {
                result.should.be.Boolean();
                result.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it(`#12. should null when get destroyed data`, function (done) {
        manager.getSingleByIdOrDefault(createdId)
            .then((data) => {
                should.equal(data, null);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });
}
module.exports = getBasicTest;<|endoftext|>


<commit_before>"use strict";

var socket = io();

var username;
$(window).load(function() {
    username = prompt("Please enter your name");
    socket.emit('log on', username);
});

$(window).on('beforeunload', function() {
  socket.emit('log off', username);
});

function userActivity(name, joinedOrLeft) {
  alert(name + " " + joinedOrLeft + " the game");
}
socket.on('log on', function(name) {
  userActivity(name, "joined");
});
socket.on('log off', function(name) {
  userActivity(name, "left");
});
<commit_msg>Emit card click event with card ID<commit_after>"use strict";

var socket = io();

var username;
$(window).load(function() {
    username = prompt("Please enter your name");
    socket.emit('log on', username);
});

$(window).on('beforeunload', function() {
  socket.emit('log off', username);
});

function userActivity(name, joinedOrLeft) {
  alert(name + " " + joinedOrLeft + " the game");
}
socket.on('log on', function(name) {
  userActivity(name, "joined");
});
socket.on('log off', function(name) {
  userActivity(name, "left");
});

function getCardID(targetNode) {
  console.log(targetNode);
  if (targetNode.className === 'card') {
    return targetNode.id;
  }
  else {
    return getCardID(targetNode.parentNode);
  }
}

$('.card').click(function(event) {
  var cardID = getCardID(event.target);

  console.log(username, "clicked card", cardID);
  socket.emit('card click', username, cardID);
});
<|endoftext|>


<commit_before>google.charts.load('current', {'packages':['line']});

function buttonClickDraw(strX,strY,formTime) {
   drawChart(strX, strY, formTime);
}

function drawChart(x, y, formTime) {
 var data = new google.visualization.DataTable();
 var limit = false;
 switch (x) {
  case "Time":
  data.addColumn('date', 'Day');
  break;
  case "Temperature":
  data.addColumn('number', 'Temperature');
  break;
  case "Light":
  data.addColumn('number', 'Light');
  break;
  case "pH":
  data.addColumn('number', 'pH');
  break;
  case "Colour":
  data.addColumn('number', 'Colour');
  limit = true;
  break;
  case "Height":
  data.addColumn('number', 'Height');
  limit = true;
  break;
}
switch (y) {
  case "Time":
  data.addColumn('date', 'Day');
  break;
  case "Temperature":
  data.addColumn('number', 'Temperature');
  break;
  case "Light":
  data.addColumn('number', 'Light');
  break;
  case "pH":
  data.addColumn('number', 'pH');
  break;
  case "Colour":
  data.addColumn('number', 'Colour');
  limit = true;
  break;
  case "Height":
  data.addColumn('number', 'Height');
  limit = true;
  break;
}
data.addRows(dataTest(x, y, limit, formTime));

var options = {
 chart: {
   title: x + ' plotted against ' + y
 },
 width: 900,
 height: 500
};

var chart = new google.charts.Line(document.getElementById('chart_div'));

chart.draw(data, options);
}

function createArray(length) {
  var arr = new Array(length || 0),
  i = length;

  if (arguments.length > 1) {
    var args = Array.prototype.slice.call(arguments, 1);
    while(i--) arr[length-1 - i] = createArray.apply(this, args);
  }

  return arr;
}

function filterData(dataArr, endTime, startTime, xCol, yCol, limit) {
  var count = 0;
  for(i = 0; i < dataArr.length; i++){
    var newDate = new Date(dataArr[i].date);
    if(newDate.getTime() >= startTime && newDate.getTime() <= endTime) {
      if(!limit || (dataArr[i].height != -1)) {
        count++;
      }
    }
  }
  var dataArray = createArray(count, 2);
  var index = 0;
  for (i = 0; i < dataArr.length; i++) {
    var newDate = new Date(dataArr[i].date);
    if(newDate.getTime() >= startTime && newDate.getTime() <= endTime) {
      if(!limit || (dataArr[i].height != -1)) {
        switch(xCol) {
          case "Time":
          dataArray[index][0] = newDate;
          break;
          case "Temperature":
          dataArray[index][0] = dataArr[i].temp;
          console.log(dataArr[i].temp);
          break;
          case "Light":
          dataArray[index][0] = dataArr[i].light;
          break;
          case "pH":
          dataArray[index][0] = dataArr[i].pH;
          break;
          case "colour":
          dataArray[index][0] = dataArr[i].colour;
          break;
          case "height":
          dataArray[index][0] = dataArr[i].height;
          break;
        }
        switch(yCol) {
          case "Time":
          dataArray[index][1] = newDate;
          break;
          case "Temperature":
          dataArray[index][1] = dataArr[i].temp;
          break;
          case "Light":
          dataArray[index][1] = dataArr[i].light;
          break;
          case "pH":
          dataArray[index][1] = dataArr[i].pH;
          break;
          case "colour":
          dataArray[index][1] = dataArr[i].colour;
          break;
          case "height":
          dataArray[index][1] = dataArr[i].height;
          break;
        }
        index++;
      }
    }
  }
  return dataArray;
}

  function drawData() {
    console.log("test");
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "http://localhost:8080/data", false);
    xhttp.send();
    var response = JSON.parse(xhttp.responseText);
  }

  function dataTest(xCol, yCol, limit, formTime){

    var durationInMinutes = 0;
    switch(formTime) {
      case "1":
      durationInMinutes = 6*60;
      break;
      case "2":
      durationInMinutes = 24*60;
      break;
      case "3":
      durationInMinutes = 24*3*60;
      break;
      case "4":
      durationInMinutes = 24*7*60;
      break;
      case "5":
      durationInMinutes = 24*7*2*60;
      break;
      case "6":
      durationInMinutes = 24*30*60;
      break;
      case "7":
      durationInMinutes = 24*30*2*60;
      break;
    }
    var MS_PER_MINUTE = 60000;
    var date = new Date();
    var myStartDate = (date - durationInMinutes * MS_PER_MINUTE);
    var url = "http://localhost:8080/data";
    var dataTry = httpGet(url);
    console.log(JSON.parse(dataTry));
    var startDate = new Date(myStartDate);
    var dataArr = filterData(JSON.parse(dataTry), date, startDate, xCol, yCol, limit);
    console.log(dataArr);
    return dataArr;
  };

  function httpGet(theUrl)
  {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
  }
<commit_msg>making right for heroku<commit_after>google.charts.load('current', {'packages':['line']});

function buttonClickDraw(strX,strY,formTime) {
   drawChart(strX, strY, formTime);
}

function drawChart(x, y, formTime) {
 var data = new google.visualization.DataTable();
 var limit = false;
 switch (x) {
  case "Time":
  data.addColumn('date', 'Day');
  break;
  case "Temperature":
  data.addColumn('number', 'Temperature');
  break;
  case "Light":
  data.addColumn('number', 'Light');
  break;
  case "pH":
  data.addColumn('number', 'pH');
  break;
  case "Colour":
  data.addColumn('number', 'Colour');
  limit = true;
  break;
  case "Height":
  data.addColumn('number', 'Height');
  limit = true;
  break;
}
switch (y) {
  case "Time":
  data.addColumn('date', 'Day');
  break;
  case "Temperature":
  data.addColumn('number', 'Temperature');
  break;
  case "Light":
  data.addColumn('number', 'Light');
  break;
  case "pH":
  data.addColumn('number', 'pH');
  break;
  case "Colour":
  data.addColumn('number', 'Colour');
  limit = true;
  break;
  case "Height":
  data.addColumn('number', 'Height');
  limit = true;
  break;
}
data.addRows(dataTest(x, y, limit, formTime));

var options = {
 chart: {
   title: x + ' plotted against ' + y
 },
 width: 900,
 height: 500
};

var chart = new google.charts.Line(document.getElementById('chart_div'));

chart.draw(data, options);
}

function createArray(length) {
  var arr = new Array(length || 0),
  i = length;

  if (arguments.length > 1) {
    var args = Array.prototype.slice.call(arguments, 1);
    while(i--) arr[length-1 - i] = createArray.apply(this, args);
  }

  return arr;
}

function filterData(dataArr, endTime, startTime, xCol, yCol, limit) {
  var count = 0;
  for(i = 0; i < dataArr.length; i++){
    var newDate = new Date(dataArr[i].date);
    if(newDate.getTime() >= startTime && newDate.getTime() <= endTime) {
      if(!limit || (dataArr[i].height != -1)) {
        count++;
      }
    }
  }
  var dataArray = createArray(count, 2);
  var index = 0;
  for (i = 0; i < dataArr.length; i++) {
    var newDate = new Date(dataArr[i].date);
    if(newDate.getTime() >= startTime && newDate.getTime() <= endTime) {
      if(!limit || (dataArr[i].height != -1)) {
        switch(xCol) {
          case "Time":
          dataArray[index][0] = newDate;
          break;
          case "Temperature":
          dataArray[index][0] = dataArr[i].temp;
          console.log(dataArr[i].temp);
          break;
          case "Light":
          dataArray[index][0] = dataArr[i].light;
          break;
          case "pH":
          dataArray[index][0] = dataArr[i].pH;
          break;
          case "colour":
          dataArray[index][0] = dataArr[i].colour;
          break;
          case "height":
          dataArray[index][0] = dataArr[i].height;
          break;
        }
        switch(yCol) {
          case "Time":
          dataArray[index][1] = newDate;
          break;
          case "Temperature":
          dataArray[index][1] = dataArr[i].temp;
          break;
          case "Light":
          dataArray[index][1] = dataArr[i].light;
          break;
          case "pH":
          dataArray[index][1] = dataArr[i].pH;
          break;
          case "colour":
          dataArray[index][1] = dataArr[i].colour;
          break;
          case "height":
          dataArray[index][1] = dataArr[i].height;
          break;
        }
        index++;
      }
    }
  }
  return dataArray;
}

  function drawData() {
    console.log("test");
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "https://plantsense.herokuapp.com/data", false);
    xhttp.send();
    var response = JSON.parse(xhttp.responseText);
  }

  function dataTest(xCol, yCol, limit, formTime){

    var durationInMinutes = 0;
    switch(formTime) {
      case "1":
      durationInMinutes = 6*60;
      break;
      case "2":
      durationInMinutes = 24*60;
      break;
      case "3":
      durationInMinutes = 24*3*60;
      break;
      case "4":
      durationInMinutes = 24*7*60;
      break;
      case "5":
      durationInMinutes = 24*7*2*60;
      break;
      case "6":
      durationInMinutes = 24*30*60;
      break;
      case "7":
      durationInMinutes = 24*30*2*60;
      break;
    }
    var MS_PER_MINUTE = 60000;
    var date = new Date();
    var myStartDate = (date - durationInMinutes * MS_PER_MINUTE);
    var url = "https://plantsense.herokuapp.com/data";
    var dataTry = httpGet(url);
    console.log(JSON.parse(dataTry));
    var startDate = new Date(myStartDate);
    var dataArr = filterData(JSON.parse(dataTry), date, startDate, xCol, yCol, limit);
    console.log(dataArr);
    return dataArr;
  };

  function httpGet(theUrl)
  {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
  }
<|endoftext|>


<commit_before>'use strict';

// Scene array to be filled on index.js
var scene = [];
var activeScene = 0;
var showCoordinates = true;

var glowFilter = new PIXI.filters.GlowFilter(renderer.width, renderer.height, 20, 2, 1, 0xFFFFFF, 0.5);
var zoomSize = 120;
var zoomTriangle = CreateTriangle(zoomSize);

// Item creation, to be used on index.js
function createItem(directory, posX, posY, imgScale, imgRotation, zoom = null, offsetX = 0, offsetY = 0) {
  var item = {
    image: directory,
    position: {
      x: posX,
      y: posY
    },
    scale: imgScale,
    zoomImage: zoom,
    zoomOffsetX: offsetX,
    zoomOffsetY: offsetY,
    rotation: (Math.PI / 180) * imgRotation,
    sceneChange: null
  };
  return item;
}

// Scene change, to be used on index.js
function changeScene(gameItem, scene) {
  gameItem.sceneChange = scene;
}

// Start the application
function start() {
  // Load image textures
  loader
    .add(createImagesArray())
    .load(loadSpritesFromTextures);
}

// Create an array with all images, without repetition
function createImagesArray() {
  var image = [];
  for (var i = 0; i < scene.length; i++) {
    image = addImageToArray(image, scene[i].backgroundImage);
    for (var j = 0; j < scene[i].item.length; j++) {
      image = addImageToArray(image, scene[i].item[j].image);
      if (scene[i].item[j].zoomImage)
        image = addImageToArray(image, scene[i].item[j].zoomImage);
    }
  }
  return image;
}

function addImageToArray(array, directory) {
  // Check if already exist
  for (var i = 0; i < array.length; i++) {
    if (array[i] === directory) // Already exist
      return array;
  }
  array.push(directory);
  return array;
}

function loadSpritesFromTextures() {
  for (var i = 0; i < scene.length; i++) {

    scene[i].backgroundImage = new PIXI.Sprite(resources[scene[i].backgroundImage].texture);
    scene[i].backgroundImage.interactive = true;
    scene[i].backgroundImage.click = function(evt) {
      HideZoom();
      if (showCoordinates) {
        var mousePosition = evt.data.getLocalPosition(stage);
        console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
      }
    };

    for (var j = 0; j < scene[i].item.length; j++) {
      scene[i].item[j].image = new PIXI.Sprite(resources[scene[i].item[j].image].texture);
      scene[i].item[j].image.x = scene[i].item[j].position.x;
      scene[i].item[j].image.y = scene[i].item[j].position.y;
      scene[i].item[j].image.anchor.set(0.5, 0.5);
      scene[i].item[j].image.scale.set(scene[i].item[j].scale, scene[i].item[j].scale);
      scene[i].item[j].image.rotation = scene[i].item[j].rotation;
      if (scene[i].item[j].sceneChange != null) {
        AddClickChangeSceneEvent(scene[i].item[j]);
      }
      if (scene[i].item[j].zoomImage) {
        scene[i].item[j].zoomImage = new PIXI.Sprite(resources[scene[i].item[j].zoomImage].texture);
        scene[i].item[j].zoomImage.anchor.set(0.5, 0.5);
        scene[i].item[j].zoomImage.height = 2*zoomSize;
        scene[i].item[j].zoomImage.width = 2*zoomSize;
        scene[i].item[j].zoomImage.visible = false;
        AddClickShowZoomEvent(scene[i].item[j]);
      }
    }
  }

  UpdateScreen();
}

function HideZoom() {
  zoomTriangle.visible = false;
  for (var i = 0; i < scene.length; i++)
    for (var j = 0; j < scene[i].item.length; j++)
      if (scene[i].item[j].zoomImage)
        scene[i].item[j].zoomImage.visible = false;
  UpdateScreen();
}

function CreateTriangle(size) {
  var triangle = new Graphics();
  triangle.beginFill(0x000000);
  triangle.drawPolygon([
      -size, 4*size,
      size, 4*size,
      0, 0
  ]);
  triangle.endFill();
  triangle.visible = false;
  return triangle;
}

function AddEvent(item) {
  item.image.interactive = true;
  // Setting glow area to be 25 pixels bigger than the image bounds
  item.image.filterArea = new Rectangle(item.image.x - item.image.width/2 - 25, item.image.y - item.image.height/2 - 25, item.image.width + 50, item.image.height + 50);
  item.image.mouseover = function(interaction) {
    // viewWidth, viewHeight, outerStrength, innerStrength, color, quality
    item.image.filters = [new PIXI.filters.GlowFilter(renderer.width, renderer.height, 18, 2, 1, 0xFFFFFF, 0.3)];
    UpdateScreen();
  };
  item.image.mouseout = function(interaction) {
    item.image.filters = null;
    UpdateScreen();
  };
}

function AddClickChangeSceneEvent(item) {
  AddEvent(item);
  item.image.click = function(interaction) {
    /*var audio = new Audio("audio/explosion.wav");
    audio.play();*/
    HideZoom();
    activeScene = item.sceneChange;
    UpdateScreen();
  };
}

function AddClickShowZoomEvent(item) {
  AddEvent(item);
  item.image.click = function(evt) {
    // Hide any other zoom being display
    HideZoom();

    // Show zoom of the item clicked
    zoomTriangle.x = item.zoomOffsetX + evt.target.position.x;
    zoomTriangle.y = item.zoomOffsetY + evt.target.position.y;
    if (zoomTriangle.x < renderer.width/2) { // Left side
      // Rotate triangle's base to right
      zoomTriangle.rotation = 1.5 * Math.PI;
      // Show the zoom image
      item.zoomImage.x = item.zoomOffsetX + item.position.x + 4 * zoomSize;
      item.zoomImage.y = item.zoomOffsetY + item.position.y;
      item.zoomImage.visible = true;
    }
    else { // Right side
      // Rotate triangle's base to left
      zoomTriangle.rotation = 0.5 * Math.PI;
      // Show the zoom image
      item.zoomImage.x = item.zoomOffsetX + item.position.x - 4 * zoomSize;
      item.zoomImage.y = item.zoomOffsetY + item.position.y;
      item.zoomImage.visible = true;
    }
    zoomTriangle.visible = true;
    UpdateScreen();
  };
}

function UpdateScreen() {
  // Draw Background
  stage.addChild(scene[activeScene].backgroundImage);

  // Draw Items
  for (var i = 0; i < scene[activeScene].item.length; i++) {
    stage.addChild(scene[activeScene].item[i].image);
  }

  // Draw zoom's Triangle
  stage.addChild(zoomTriangle);

  // Draw zoom's Image
  for (var i = 0; i < scene[activeScene].item.length; i++) {
    if (scene[activeScene].item[i].zoomImage)
      stage.addChild(scene[activeScene].item[i].zoomImage);
  }

  // Render 'em all
  renderer.render(stage);
}

/*var i = 0;
function play() {
  //message.text = i;
  stage.addChild(scene[activeScene].backgroundImage);
  for (var i = 0; i < scene[activeScene].item.length; i++)
    stage.addChild(scene[activeScene].item[i].image);
}

function gameLoop() {
  requestAnimationFrame(gameLoop);
  state();
  renderer.render(stage);
  meter.tick();
}*/

/*
  var message = new Text(
    "Hello Pixi!",
    {font: "32px sans-serif", fill: "white"}
  );
  message.position.set(54, 96);
}*/
<commit_msg>small changes on createItem function<commit_after>'use strict';

// Scene array to be filled on index.js
var scene = [];
var activeScene = 0;
var showCoordinates = true;

var glowFilter = new PIXI.filters.GlowFilter(renderer.width, renderer.height, 20, 2, 1, 0xFFFFFF, 0.5);
var zoomSize = 120;
var zoomTriangle = CreateTriangle(zoomSize);

// Item creation, to be used on index.js
function createItem(directory, posX, posY, imgScale, imgRotation, zoom = null, offsetX = 0, offsetY = 0) {
  var item = {
    image: directory,
    position: {
      x: posX,
      y: posY
    },
    scale: imgScale,
    rotation: (Math.PI / 180) * imgRotation,
    zoomImage: zoom,
    zoomOffsetX: offsetX,
    zoomOffsetY: offsetY,
    sceneChange: null
  };
  return item;
}

// Scene change, to be used on index.js
function changeScene(gameItem, scene) {
  gameItem.sceneChange = scene;
}

// Start the application
function start() {
  // Load image textures
  loader
    .add(createImagesArray())
    .load(loadSpritesFromTextures);
}

// Create an array with all images, without repetition
function createImagesArray() {
  var image = [];
  for (var i = 0; i < scene.length; i++) {
    image = addImageToArray(image, scene[i].backgroundImage);
    for (var j = 0; j < scene[i].item.length; j++) {
      image = addImageToArray(image, scene[i].item[j].image);
      if (scene[i].item[j].zoomImage)
        image = addImageToArray(image, scene[i].item[j].zoomImage);
    }
  }
  return image;
}

function addImageToArray(array, directory) {
  // Check if already exist
  for (var i = 0; i < array.length; i++) {
    if (array[i] === directory) // Already exist
      return array;
  }
  array.push(directory);
  return array;
}

function loadSpritesFromTextures() {
  for (var i = 0; i < scene.length; i++) {

    scene[i].backgroundImage = new PIXI.Sprite(resources[scene[i].backgroundImage].texture);
    scene[i].backgroundImage.interactive = true;
    scene[i].backgroundImage.click = function(evt) {
      HideZoom();
      if (showCoordinates) {
        var mousePosition = evt.data.getLocalPosition(stage);
        console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
      }
    };

    for (var j = 0; j < scene[i].item.length; j++) {
      scene[i].item[j].image = new PIXI.Sprite(resources[scene[i].item[j].image].texture);
      scene[i].item[j].image.x = scene[i].item[j].position.x;
      scene[i].item[j].image.y = scene[i].item[j].position.y;
      scene[i].item[j].image.anchor.set(0.5, 0.5);
      scene[i].item[j].image.scale.set(scene[i].item[j].scale, scene[i].item[j].scale);
      scene[i].item[j].image.rotation = scene[i].item[j].rotation;
      if (scene[i].item[j].sceneChange != null) {
        AddClickChangeSceneEvent(scene[i].item[j]);
      }
      if (scene[i].item[j].zoomImage) {
        scene[i].item[j].zoomImage = new PIXI.Sprite(resources[scene[i].item[j].zoomImage].texture);
        scene[i].item[j].zoomImage.anchor.set(0.5, 0.5);
        scene[i].item[j].zoomImage.height = 2*zoomSize;
        scene[i].item[j].zoomImage.width = 2*zoomSize;
        scene[i].item[j].zoomImage.visible = false;
        AddClickShowZoomEvent(scene[i].item[j]);
      }
    }
  }

  UpdateScreen();
}

function HideZoom() {
  zoomTriangle.visible = false;
  for (var i = 0; i < scene.length; i++)
    for (var j = 0; j < scene[i].item.length; j++)
      if (scene[i].item[j].zoomImage)
        scene[i].item[j].zoomImage.visible = false;
  UpdateScreen();
}

function CreateTriangle(size) {
  var triangle = new Graphics();
  triangle.beginFill(0x000000);
  triangle.drawPolygon([
      -size, 4*size,
      size, 4*size,
      0, 0
  ]);
  triangle.endFill();
  triangle.visible = false;
  return triangle;
}

function AddEvent(item) {
  item.image.interactive = true;
  // Setting glow area to be 25 pixels bigger than the image bounds
  item.image.filterArea = new Rectangle(item.image.x - item.image.width/2 - 25, item.image.y - item.image.height/2 - 25, item.image.width + 50, item.image.height + 50);
  item.image.mouseover = function(interaction) {
    // viewWidth, viewHeight, outerStrength, innerStrength, color, quality
    item.image.filters = [new PIXI.filters.GlowFilter(renderer.width, renderer.height, 18, 2, 1, 0xFFFFFF, 0.3)];
    UpdateScreen();
  };
  item.image.mouseout = function(interaction) {
    item.image.filters = null;
    UpdateScreen();
  };
}

function AddClickChangeSceneEvent(item) {
  AddEvent(item);
  item.image.click = function(interaction) {
    /*var audio = new Audio("audio/explosion.wav");
    audio.play();*/
    HideZoom();
    activeScene = item.sceneChange;
    UpdateScreen();
  };
}

function AddClickShowZoomEvent(item) {
  AddEvent(item);
  item.image.click = function(evt) {
    // Hide any other zoom being display
    HideZoom();

    // Show zoom of the item clicked
    zoomTriangle.x = item.zoomOffsetX + evt.target.position.x;
    zoomTriangle.y = item.zoomOffsetY + evt.target.position.y;
    if (zoomTriangle.x < renderer.width/2) { // Left side
      // Rotate triangle's base to right
      zoomTriangle.rotation = 1.5 * Math.PI;
      // Show the zoom image
      item.zoomImage.x = item.zoomOffsetX + item.position.x + 4 * zoomSize;
      item.zoomImage.y = item.zoomOffsetY + item.position.y;
      item.zoomImage.visible = true;
    }
    else { // Right side
      // Rotate triangle's base to left
      zoomTriangle.rotation = 0.5 * Math.PI;
      // Show the zoom image
      item.zoomImage.x = item.zoomOffsetX + item.position.x - 4 * zoomSize;
      item.zoomImage.y = item.zoomOffsetY + item.position.y;
      item.zoomImage.visible = true;
    }
    zoomTriangle.visible = true;
    UpdateScreen();
  };
}

function UpdateScreen() {
  // Draw Background
  stage.addChild(scene[activeScene].backgroundImage);

  // Draw Items
  for (var i = 0; i < scene[activeScene].item.length; i++) {
    stage.addChild(scene[activeScene].item[i].image);
  }

  // Draw zoom's Triangle
  stage.addChild(zoomTriangle);

  // Draw zoom's Image
  for (var i = 0; i < scene[activeScene].item.length; i++) {
    if (scene[activeScene].item[i].zoomImage)
      stage.addChild(scene[activeScene].item[i].zoomImage);
  }

  // Render 'em all
  renderer.render(stage);
}

/*var i = 0;
function play() {
  //message.text = i;
  stage.addChild(scene[activeScene].backgroundImage);
  for (var i = 0; i < scene[activeScene].item.length; i++)
    stage.addChild(scene[activeScene].item[i].image);
}

function gameLoop() {
  requestAnimationFrame(gameLoop);
  state();
  renderer.render(stage);
  meter.tick();
}*/

/*
  var message = new Text(
    "Hello Pixi!",
    {font: "32px sans-serif", fill: "white"}
  );
  message.position.set(54, 96);
}*/
<|endoftext|>


<commit_before>"use strict";
var requests = require('./requests');

var Hackerspace = function() {
  this.debug = 0;

  this.web = 'https://hackerspace-ntnu.no/';
  this.api = 'https://hackerspace-ntnu.no/api/door';

  this.msgDisconnected = 'Frakoblet fra Hackerspace';
  this.msgError = 'Malformatert data fra Hackerspace';
  this.responseData = {};
};

Hackerspace.prototype.get = function(callback) {
  var self = this;
  requests.json(self.api, {
    success: function(door) {
      if (self.debug) console.log('Raw door:\n\n', door);

      if (typeof door === 'object') {
        self.responseData.open = door.isOpen.door;
      }
      else {
        // Empty string returned from API
        self.responseData.error = self.msgError;
      }
      callback(self.responseData);
    },
    error: function(jqXHR, text, err) {
      if (self.debug) console.log('ERROR: Failed to get hackerspace info.');
      data.error = self.msgDisconnected;
      callback(self.responseData);
    }
  });
};

module.exports = Hackerspace;
<commit_msg>Update hackerspace api with new endpoint<commit_after>"use strict";
var requests = require('./requests');

var Hackerspace = function() {
  this.debug = 0;

  this.web = 'https://hackerspace-ntnu.no/';
  this.api = 'https://hackerspace-ntnu.no/door/get_status/';

  this.msgDisconnected = 'Frakoblet fra Hackerspace';
  this.msgError = 'Malformatert data fra Hackerspace';
  this.responseData = {};
};

Hackerspace.prototype.get = function(callback) {
  var self = this;
  requests.json(self.api, {
    success: function(door) {
      if (self.debug) console.log('Raw door:\n\n', door);

      if (typeof door === 'string') {
        self.responseData.open = door === 'True';
      }
      else {
        // Empty string returned from API
        self.responseData.error = self.msgError;
      }
      callback(self.responseData);
    },
    error: function(jqXHR, text, err) {
      if (self.debug) console.log('ERROR: Failed to get hackerspace info.');
      self.responseData.error = self.msgDisconnected;
      callback(self.responseData);
    }
  });
};

module.exports = Hackerspace;
<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var enemyStride = 7;
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var textures = new Object();

  function init() {
  	document.documentElement.style.overflow = 'hidden';  // firefox, chrome
    document.body.scroll = "no"; // ie only

    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
        for (i = 0; i < 4; i++) {
          userData[i] = Number(userData[i]);
        }
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
        enemyStride = Number(message.data.split(":")[0].replace("dat", ""));
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    $("body").empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
      onblur: clearInput,
    }).focus();
    window.onblur = clearInput;

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    context.globalCompositeOperation = "normal";
    gameLoop();

    $(window).resize(function() {
      windowWidth = $(window).innerWidth();
      windowHeight = $(window).innerHeight();

      canvasElement.attr({
        width: windowWidth,
        height: windowHeight
      });
    });
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);
    context.fillStyle = "#FFFFFF"
    context.fillRect(0, 0, windowWidth, windowHeight);
    //draw BG
    context.drawImage(getImage("BG"), gPIVX(0) % 1000, gPIVY(0) % 1000, 1000, 1000);
    //draw enemies
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.drawImage(getImageMasked("player", enemies[i+4]),gPIVX(enemies[i]), gPIVY(enemies[i+1]), enemies[i+2], enemies[i+3]);
    }

    //draw enemy names
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.fillText(enemies[i+5],(gPIVX(enemies[i]) - (context.measureText(enemies[i+5]).width / 2)) + 15,gPIVY(enemies[i+1]) - 5);
    }

    //draw player name
    //context.fillStyle = userData[4];
    //context.font = "15px Arial";
    //context.fillText(userData[5],(gPIVX(userData[0]) - (context.measureText(userData[5]).width / 2)) + 15,gPIVY(userData[1]) - 5);

    setTimeout(gameLoop, frameLength);
  }

  function gPIVX(x){
    //getPositionInViewportX
    var ret = new Object();
    return ((x - (userData[0] + (userData[2] / 2))) + (windowWidth / 2.0));
  }
  function gPIVY(y){
    //getPositionInViewportY
    return ((y - (userData[1] + (userData[3] / 2))) + (windowHeight / 2.0));
  }

  function clearInput(){
    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  function getImageData(image){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.drawImage(image, 0, 0, image.width, image.height);
    return tempCTX.getImageData(0, 0, image.width, image.height);
  }

  function getImage(name){
  	if ((name) in textures){
  		return textures[name];
  	} else {
  		textures[name] = new Image;
  		textures[name].src = 'http://monolc.com/FellJS/res/' + name + '.png';
  		return textures[name];
  	}
  }
  function getImageMasked(name, color){
  	if ((name + "-mask" + color) in textures){
  		return textures[name + "-mask" + color];
  	}
    var image = getImage(name);
    var mask = getImage(name + "-mask");
    if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0){
      return new Image();
    }
    var maskData = getImageData(mask);
    var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    var colorRGBS = regex.exec(color);
    console.log(color + "|" + colorRGBS[0] + "|" + colorRGBS[1] + "|" + colorRGBS[2] + "|" + colorRGBS[3]);
    var colorRGB = [];
    for (i = 0; i < 3; i++){
      colorRGB[i] = parseInt(colorRGBS[i+1], 16);
    }
    for (i = 0; i < maskData.data.length; i+=4){
      maskData.data[i] =  colorRGB[0];
      maskData.data[i+1] =  colorRGB[1];
      maskData.data[i+2] =  colorRGB[2];
    }
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX=tempCanv.getContext("2d");
    tempCTX.drawImage(image,0,0,image.width, image.height);
    tempCTX.putImageData(maskData, 0, 0)
    var ret = new Image();
    ret.src = tempCanv.toDataURL("image/png");
    textures[name + "-mask" + color] = ret;
    return ret;
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<commit_msg>bg scrolling<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var enemyStride = 7;
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var textures = new Object();

  function init() {
  	document.documentElement.style.overflow = 'hidden';  // firefox, chrome
    document.body.scroll = "no"; // ie only

    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
        for (i = 0; i < 4; i++) {
          userData[i] = Number(userData[i]);
        }
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
        enemyStride = Number(message.data.split(":")[0].replace("dat", ""));
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    $("body").empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
      onblur: clearInput,
    }).focus();
    window.onblur = clearInput;

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    context.globalCompositeOperation = "normal";
    gameLoop();

    $(window).resize(function() {
      windowWidth = $(window).innerWidth();
      windowHeight = $(window).innerHeight();

      canvasElement.attr({
        width: windowWidth,
        height: windowHeight
      });
    });
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);
    context.fillStyle = "#FFFFFF"
    context.fillRect(0, 0, windowWidth, windowHeight);
    //draw BG
    for (a = -2; a < 3; a++){
    	for (b = -2; b < 3; b++){
    		context.drawImage(getImage("BG"), (gPIVX(0) % 1000) + (1000 * a), (gPIVY(0) % 1000) + (1000 * b), 1000, 1000);
    	}
    }
    //draw enemies
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.drawImage(getImageMasked("player", enemies[i+4]),gPIVX(enemies[i]), gPIVY(enemies[i+1]), enemies[i+2], enemies[i+3]);
    }

    //draw enemy names
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.fillText(enemies[i+5],(gPIVX(enemies[i]) - (context.measureText(enemies[i+5]).width / 2)) + 15,gPIVY(enemies[i+1]) - 5);
    }

    //draw player name
    //context.fillStyle = userData[4];
    //context.font = "15px Arial";
    //context.fillText(userData[5],(gPIVX(userData[0]) - (context.measureText(userData[5]).width / 2)) + 15,gPIVY(userData[1]) - 5);

    setTimeout(gameLoop, frameLength);
  }

  function gPIVX(x){
    //getPositionInViewportX
    var ret = new Object();
    return ((x - (userData[0] + (userData[2] / 2))) + (windowWidth / 2.0));
  }
  function gPIVY(y){
    //getPositionInViewportY
    return ((y - (userData[1] + (userData[3] / 2))) + (windowHeight / 2.0));
  }

  function clearInput(){
    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  function getImageData(image){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.drawImage(image, 0, 0, image.width, image.height);
    return tempCTX.getImageData(0, 0, image.width, image.height);
  }

  function getImage(name){
  	if ((name) in textures){
  		return textures[name];
  	} else {
  		textures[name] = new Image;
  		textures[name].src = 'http://monolc.com/FellJS/res/' + name + '.png';
  		return textures[name];
  	}
  }
  function getImageMasked(name, color){
  	if ((name + "-mask" + color) in textures){
  		return textures[name + "-mask" + color];
  	}
    var image = getImage(name);
    var mask = getImage(name + "-mask");
    if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0){
      return new Image();
    }
    var maskData = getImageData(mask);
    var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    var colorRGBS = regex.exec(color);
    console.log(color + "|" + colorRGBS[0] + "|" + colorRGBS[1] + "|" + colorRGBS[2] + "|" + colorRGBS[3]);
    var colorRGB = [];
    for (i = 0; i < 3; i++){
      colorRGB[i] = parseInt(colorRGBS[i+1], 16);
    }
    for (i = 0; i < maskData.data.length; i+=4){
      maskData.data[i] =  colorRGB[0];
      maskData.data[i+1] =  colorRGB[1];
      maskData.data[i+2] =  colorRGB[2];
    }
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX=tempCanv.getContext("2d");
    tempCTX.drawImage(image,0,0,image.width, image.height);
    tempCTX.putImageData(maskData, 0, 0)
    var ret = new Image();
    ret.src = tempCanv.toDataURL("image/png");
    textures[name + "-mask" + color] = ret;
    return ret;
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<|endoftext|>


<commit_before>var moment = require("moment");
var querystring = require("querystring");

var options = { baseUrl : "http://news-at.zhihu.com/api/4/" };
var dailyRequest = require("request").defaults(options);
var imgRequest = require("request");

const PREFIX = "/api/4/imgs/";

var today = null;

/**
 * 获取最新热门日报。
 */
function getTopStories(p_res)
{
    dailyRequest.get({ url: "/news/latest", json: true }, function (error, response, body)
    {
        if (!error && response.statusCode == 200)
        {
            var stories = body.top_stories.map(function (item)
            {
                return {
                    id: item.id,
                    title: item.title,
                    image: PREFIX + querystring.escape(item.image)
                };
            });

            today = body.date;
            p_res.set(response.headers);
            p_res.json({
                date: body.date,
                stories: stories
            });
        }
        else
        {
            p_res.status(404).render("error_404");
        }
    });
}

/**
 * 获取指定日期的日报。
 * @param String p_date 指定的日期。如果小于 20130519，返回值为 {}；如果未指定，则返回最新日报。
 */
function getStories(p_date, p_res)
{
    var m = moment(p_date || today, "YYYYMMDD", true);
    if (m.isValid())
    {
        // 因知乎日报 API 返回的是指定日期的前一天的日报，所以要加一天才能获取指定日期的日报。
        var date = m.add(1, "day").format("YYYYMMDD");
        dailyRequest.get({ url: "/news/before/" + date, json: true }, function (error, response, body)
        {
            if (!error && response.statusCode == 200)
            {
                // 因知乎日报的 API 返回的图片太小，这里直接丢弃，后面再通过其他途径获取图片。
                var stories = body.stories.map(function (item)
                {
                    return {
                        id: item.id,
                        title: item.title,
                    };
                });

                p_res.set(response.headers);
                p_res.json({
                    date: body.date,
                    stories: stories
                });
            }
            else
            {
                p_res.status(404).render("error_404");
            }
        });
    }
    else
    {
        p_res.status(404).render("error_404");
    }
}

/**
 * 获取指定图片。
 * @param p_url 图片地址。
 */
function getImage(p_url, p_res)
{
    imgRequest.get(p_url)
    .on("error", function ()
    {
        p_res.status(404).render("error_404");
    }).pipe(p_res);
}

exports.today = today;
exports.getTopStories = getTopStories;
exports.getStories = getStories;
exports.getImage = getImage;
<commit_msg>add getLatestStories()<commit_after>var moment = require("moment");
var querystring = require("querystring");

var options = { baseUrl : "http://news-at.zhihu.com/api/4/" };
var dailyRequest = require("request").defaults(options);
var imgRequest = require("request");

const PREFIX = "/api/4/imgs/";

/**
 * 获取最新日报（即今天截止目前为止的日报）。
 */
function getLatestStories(p_res)
{
    dailyRequest.get({ url: "/news/latest", json: true }, function (error, response, body)
    {
        if (!error && response.statusCode == 200)
        {
            // 因知乎日报的 API 返回的图片太小，这里直接丢弃，后面再通过其他途径获取图片。
            var stories = body.stories.map(function (item)
            {
                return {
                    id: item.id,
                    title: item.title,
                };
            });

            p_res.set(response.headers);
            p_res.json({
                date: body.date,
                stories: stories
            });
        }
        else
        {
            p_res.status(404).render("error_404");
        }
    });
}

/**
 * 获取最新热门日报。
 */
function getTopStories(p_res)
{
    dailyRequest.get({ url: "/news/latest", json: true }, function (error, response, body)
    {
        if (!error && response.statusCode == 200)
        {
            var stories = body.top_stories.map(function (item)
            {
                return {
                    id: item.id,
                    title: item.title,
                    image: PREFIX + querystring.escape(item.image)
                };
            });

            p_res.set(response.headers);
            p_res.json({
                date: body.date,
                stories: stories
            });
        }
        else
        {
            p_res.status(404).render("error_404");
        }
    });
}

/**
 * 获取指定日期的日报。
 * @param String p_date 指定的日期。如果小于 20130519，返回值为 {}；如果未指定，则返回最新日报。
 */
function getStories(p_date, p_res)
{
    var m = moment(p_date, "YYYYMMDD", true);
    if (m.isValid())
    {
        // 因知乎日报 API 返回的是指定日期的前一天的日报，所以要加一天才能获取指定日期的日报。
        var date = m.add(1, "day").format("YYYYMMDD");
        dailyRequest.get({ url: "/news/before/" + date, json: true }, function (error, response, body)
        {
            if (!error && response.statusCode == 200)
            {
                // 因知乎日报的 API 返回的图片太小，这里直接丢弃，后面再通过其他途径获取图片。
                var stories = body.stories.map(function (item)
                {
                    return {
                        id: item.id,
                        title: item.title,
                    };
                });

                p_res.set(response.headers);
                p_res.json({
                    date: body.date,
                    stories: stories
                });
            }
            else
            {
                p_res.status(404).render("error_404");
            }
        });
    }
    else
    {
        p_res.status(404).render("error_404");
    }
}

/**
 * 获取指定图片。
 * @param p_url 图片地址。
 */
function getImage(p_url, p_res)
{
    imgRequest.get(p_url)
    .on("error", function ()
    {
        p_res.status(404).render("error_404");
    }).pipe(p_res);
}

exports.getTopStories = getTopStories;
exports.getStories = getStories;
exports.getImage = getImage;
<|endoftext|>