<commit_before>/**
 * Copyright RIKSOF (Private) Limited 2016.
 *
 * JS Style Checker.
 */

/**
 * Constructor
 *
 * @class [Checker ESLintChecker]
 */
checker = function ESLintChecker() {

  /**
   * Array of file paths.
   */
  this.checkedFiles = [];
};

/**
 * Instance methods.
 */
checker.prototype = {

  SEVERITY_HIGH: 1,
  SEVERITY_MEDIUM: 2,
  SEVERITY_LOW: 3,

  /**
   * Function is used to reset the checker for next pull review.
   *
   * @return {undefined}
   */
  reset: function ESLintReset() {
    this.checkedFiles = [];
  },

  /**
   * Indicates to the caller if this checker is interested in given
   * file.
   *
   * @param {string} file   Relative path of file.
   * @returns {boolean}     If this checker validates given file.
   */
  doesValidate: function ESLintDoesValidate( file ) {
    var validates = false;
    var included = ['.js'];

    included.forEach( function eachInclude( e ) {
      if ( file.substr( -e.length) === e ) {
        validates = true;
      }
    });

    return validates;
  },

  /**
   * Process a new file both its current and proposed version.
   *
   * @param {string} from         Path of the base file.
   * @param {string} baseSource   Content of the base source file.
   * @param {string} to           Path of the head file.
   * @param {function} callback   Callback method to let everyone know
   *                              we are done.
   */
  start: function ESLintStart( from, baseSource, to, headSource, callback ) {
    var errors = {};

    var linter = require('eslint').linter;
    var rules = {
      'no-cond-assign': this.SEVERITY_HIGH,
      'no-console': this.SEVERITY_HIGH,
      'no-constant-condition': this.SEVERITY_HIGH,
      'no-dupe-args': this.SEVERITY_HIGH,
      'no-dupe-keys': this.SEVERITY_HIGH,
      'no-duplicate-case': this.SEVERITY_HIGH,
      'no-ex-assign': this.SEVERITY_HIGH,
      'no-extra-parens': this.SEVERITY_MEDIUM,
      'no-extra-semi': this.SEVERITY_MEDIUM,
      'no-func-assign': this.SEVERITY_HIGH,
      'no-irregular-whitespace': this.SEVERITY_HIGH,
      'no-sparse-arrays': this.SEVERITY_HIGH,
      'no-unexpected-multiline': this.SEVERITY_HIGH,
      'no-unreachable': this.SEVERITY_HIGH,
      'valid-jsdoc': this.SEVERITY_HIGH,
      'valid-typeof': this.SEVERITY_HIGH,
      'accessor-pairs': this.SEVERITY_HIGH,
      'array-callback-return': this.SEVERITY_HIGH,
      'block-scoped-var': this.SEVERITY_HIGH,
      'complexity': [this.SEVERITY_HIGH, { 'max': 4 }],
      'consistent-return': this.SEVERITY_HIGH,
      'curly': this.SEVERITY_HIGH,
      'dot-notation': this.SEVERITY_HIGH,
      'eqeqeq': this.SEVERITY_HIGH,
      'no-eval': this.SEVERITY_MEDIUM,
      'no-lone-blocks': this.SEVERITY_HIGH,
      'no-loop-func': this.SEVERITY_HIGH,
      'no-magic-numbers': [this.SEVERITY_HIGH, {'ignore': [0, 1, -1]}],
      'no-multi-spaces': this.SEVERITY_HIGH,
      'no-native-reassign': this.SEVERITY_HIGH,
      'no-new': this.SEVERITY_HIGH,
      'no-new-func': this.SEVERITY_HIGH,
      'no-proto': this.SEVERITY_HIGH,
      'no-redeclare': this.SEVERITY_HIGH,
      'no-return-assign': this.SEVERITY_HIGH,
      'no-self-assign': this.SEVERITY_HIGH,
      'no-self-compare': this.SEVERITY_HIGH,
      'no-unmodified-loop-condition': this.SEVERITY_HIGH,
      'no-unused-expressions': this.SEVERITY_HIGH,
      'no-useless-call': this.SEVERITY_HIGH,
      'no-useless-concat': this.SEVERITY_HIGH,
      'no-useless-escape': this.SEVERITY_HIGH,
      'no-shadow': this.SEVERITY_LOW,
      'no-shadow-restricted-names': this.SEVERITY_LOW,
      'array-bracket-spacing': [this.SEVERITY_LOW, 'never'],
      'block-spacing': this.SEVERITY_LOW,
      'brace-style': this.SEVERITY_LOW,
      'camelcase': this.SEVERITY_LOW,
      'comma-spacing': this.SEVERITY_LOW,
      'consistent-this': [this.SEVERITY_LOW, 'me'],
      'func-names': this.SEVERITY_LOW,
      'indent': [this.SEVERITY_LOW, 2],
      'key-spacing': this.SEVERITY_LOW,
      'keyword-spacing': this.SEVERITY_LOW,
      'quotes': [this.SEVERITY_LOW, 'single'],
      'semi': this.SEVERITY_LOW,
      'semi-spacing': this.SEVERITY_LOW
    }

    // Lint the base source.
    errors.base = linter.verify( baseSource, {
      rules: rules
    });

    // Lint the head source.
    errors.head = linter.verify( headSource, {
      rules: rules
    });

    // Remember this report.
    var report = {
      file: to,
      errors: errors
    };

    this.checkedFiles.push( report );

    callback();
  },

  /**
   * Processes a step in the diff file.
   *
   * @param {Object} change       Line being read
   * @param {string} path         File path
   * @param {number} position     Position in file
   * @param {function} callback   Once processing is done.
   *
   * @return {undefined}
   */
  step: function ESLintStep( change, path, position, callback ) {
    var comment = '';

    // On the line, only report on changes that were made.
    if ( change.add ) {
      for ( j = 0; j < this.checkedFiles.length; j++ ) {
        var f = this.checkedFiles[j];
        if ( f.file === path ) {
          for ( i = 0; i < f.errors.head.length; i++ ) {
            if ( f.errors.head[i] !== null && f.errors.head[i].line === change.ln ) {
              comment += f.errors.head[i].message + '\n```javascript\n' + f.errors.head[i].source + '\n```\n';
              f.errors.head[i].reported = true;
            }
          }
        }
      }
    }

    callback( comment );
  },

  /**
   * This event indicates the current pull request diff is completed.
   * It gives checker the opportunity to make a comment to the full
   * diff.
   *
   * @param {function} callback    Once processing is done.
   *
   * @return {undefined}
   */
  done: function ESLintDone( callback ) {
    var comment = '';
    var maxErrorsPerFile = 5;

    // Look through all changed files and ensure that we
    // have not added more errors in this pull.
    for ( i = 0; i < this.checkedFiles.length; i++ ) {
      f = this.checkedFiles[i];

      // We are only interested if the head branch still has
      // lint issues.
      if ( f.errors.head.length > 0 ) {
        baseIndex = 0;
        headIndex = 0;

        // We want to limit to no more than 5 comments per file
        errorsCount = 0;

        // Keep searching till we get to the end of the issues
        // on head branch.
        while ( f.errors.head !== null && headIndex < f.errors.head.length && errorsCount < maxErrorsPerFile ) {
          // Make sure the current head error is not a null
          if ( f.errors.head[ headIndex] === null ) {
            headIndex++;
            continue;
          }

          // If we still have issues to look at on the base branch.
          if ( f.errors.base !== null && baseIndex < f.errors.base.length ) {

            // Make sure the current base error is not a null
            if ( f.errors.base[ baseIndex] === null ) {
              baseIndex++;
              continue;
            }

            // If this error is in both branches.
            if ( f.errors.base[ baseIndex ].line === f.errors.head[ headIndex ].line ) {

              // Ignore this line.
              baseIndex++;
              headIndex++;
            } else if ( f.errors.base[ baseIndex ].line < f.errors.head[ headIndex ].line ) {
              // Go to the next error as this error has
              // been removed from the head branch.
              baseIndex++;
            } else {
              // All these comments are not in the base branch, so they
              // are additional comments. Need to make sure we did not
              // report them in the line by line review.
              if ( !f.errors.head[headIndex].reported && f.errors.head[headIndex].severity >= this.SEVERITY_HIGH ) {
                comment += '\n**' + f.file + '(' + f.errors.head[ headIndex ].line + '):** *' + f.errors.head[ headIndex ].message + '*';
                comment += '\n```javascript\n' + f.errors.head[headIndex].source + '\n```\n';
                errorsCount++;
              }

              headIndex++;
            }
          } else {
            // All these comments are not in the base branch, so they
            // are additional comments. Need to make sure we did not
            // report them in the line by line review.
            if ( !f.errors.head[headIndex].reported && f.errors.head[headIndex].severity >= this.SEVERITY_HIGH ) {
              comment += '\n**' + f.file + '(' + f.errors.head[ headIndex ].line + '):** *' + f.errors.head[ headIndex ].message + '*';
              comment += '\n```javascript\n' + f.errors.head[headIndex].source + '\n```\n';
              errorsCount++;
            }

            headIndex++;
          }
        }
      }
    }

    callback( comment );
  }
};

// Make the module available to all
module.exports = checker;<commit_msg>Fixed lint issues<commit_after>/**
 * Copyright RIKSOF (Private) Limited 2016.
 *
 * JS Style Checker.
 */

/**
 * Constructor
 *
 * @class [Checker ESLintChecker]
 */
checker = function ESLintChecker() {

  /**
   * Array of file paths.
   */
  this.checkedFiles = [];
};

/**
 * Instance methods.
 */
checker.prototype = {

  SEVERITY_HIGH: 1,
  SEVERITY_MEDIUM: 2,
  SEVERITY_LOW: 3,

  /**
   * Function is used to reset the checker for next pull review.
   *
   * @return {undefined}
   */
  reset: function ESLintReset() {
    this.checkedFiles = [];
  },

  /**
   * Indicates to the caller if this checker is interested in given
   * file.
   *
   * @param {string} file   Relative path of file.
   * @returns {boolean}     If this checker validates given file.
   */
  doesValidate: function ESLintDoesValidate( file ) {
    var validates = false;
    var included = ['.js'];

    included.forEach( function eachInclude( e ) {
      if ( file.substr( -e.length) === e ) {
        validates = true;
      }
    });

    return validates;
  },

  /**
   * Process a new file both its current and proposed version.
   *
   * @param {string} from         Path of the base file.
   * @param {string} baseSource   Content of the base source file.
   * @param {string} to           Path of the head file.
   * @param {string} headSource   Content of the head source file.
   * @param {function} callback   Callback method to let everyone know
   *                              we are done.
   *
   * @returns {undefined}
   */
  start: function ESLintStart( from, baseSource, to, headSource, callback ) {
    var errors = {};
    var maxComplexity = 4;
    var indentSpaces = 2;

    var linter = require('eslint').linter;
    var rules = {
      'no-cond-assign': this.SEVERITY_HIGH,
      'no-console': this.SEVERITY_HIGH,
      'no-constant-condition': this.SEVERITY_HIGH,
      'no-dupe-args': this.SEVERITY_HIGH,
      'no-dupe-keys': this.SEVERITY_HIGH,
      'no-duplicate-case': this.SEVERITY_HIGH,
      'no-ex-assign': this.SEVERITY_HIGH,
      'no-extra-parens': this.SEVERITY_MEDIUM,
      'no-extra-semi': this.SEVERITY_MEDIUM,
      'no-func-assign': this.SEVERITY_HIGH,
      'no-irregular-whitespace': this.SEVERITY_HIGH,
      'no-sparse-arrays': this.SEVERITY_HIGH,
      'no-unexpected-multiline': this.SEVERITY_HIGH,
      'no-unreachable': this.SEVERITY_HIGH,
      'valid-jsdoc': this.SEVERITY_HIGH,
      'valid-typeof': this.SEVERITY_HIGH,
      'accessor-pairs': this.SEVERITY_HIGH,
      'array-callback-return': this.SEVERITY_HIGH,
      'block-scoped-var': this.SEVERITY_HIGH,
      'complexity': [this.SEVERITY_HIGH, { 'max': maxComplexity }],
      'consistent-return': this.SEVERITY_HIGH,
      'curly': this.SEVERITY_HIGH,
      'dot-notation': this.SEVERITY_HIGH,
      'eqeqeq': this.SEVERITY_HIGH,
      'no-eval': this.SEVERITY_MEDIUM,
      'no-lone-blocks': this.SEVERITY_HIGH,
      'no-loop-func': this.SEVERITY_HIGH,
      'no-magic-numbers': [this.SEVERITY_HIGH, {'ignore': [0, 1, -1]}],
      'no-multi-spaces': this.SEVERITY_HIGH,
      'no-native-reassign': this.SEVERITY_HIGH,
      'no-new': this.SEVERITY_HIGH,
      'no-new-func': this.SEVERITY_HIGH,
      'no-proto': this.SEVERITY_HIGH,
      'no-redeclare': this.SEVERITY_HIGH,
      'no-return-assign': this.SEVERITY_HIGH,
      'no-self-assign': this.SEVERITY_HIGH,
      'no-self-compare': this.SEVERITY_HIGH,
      'no-unmodified-loop-condition': this.SEVERITY_HIGH,
      'no-unused-expressions': this.SEVERITY_HIGH,
      'no-useless-call': this.SEVERITY_HIGH,
      'no-useless-concat': this.SEVERITY_HIGH,
      'no-useless-escape': this.SEVERITY_HIGH,
      'no-shadow': this.SEVERITY_LOW,
      'no-shadow-restricted-names': this.SEVERITY_LOW,
      'array-bracket-spacing': [this.SEVERITY_LOW, 'never'],
      'block-spacing': this.SEVERITY_LOW,
      'brace-style': this.SEVERITY_LOW,
      'camelcase': this.SEVERITY_LOW,
      'comma-spacing': this.SEVERITY_LOW,
      'consistent-this': [this.SEVERITY_LOW, 'me'],
      'func-names': this.SEVERITY_LOW,
      'indent': [this.SEVERITY_LOW, indentSpaces],
      'key-spacing': this.SEVERITY_LOW,
      'keyword-spacing': this.SEVERITY_LOW,
      'quotes': [this.SEVERITY_LOW, 'single'],
      'semi': this.SEVERITY_LOW,
      'semi-spacing': this.SEVERITY_LOW
    };

    // Lint the base source.
    errors.base = linter.verify( baseSource, {
      rules: rules
    });

    // Lint the head source.
    errors.head = linter.verify( headSource, {
      rules: rules
    });

    // Remember this report.
    var report = {
      file: to,
      errors: errors
    };

    this.checkedFiles.push( report );

    callback();
  },

  /**
   * Processes a step in the diff file.
   *
   * @param {Object} change       Line being read
   * @param {string} path         File path
   * @param {number} position     Position in file
   * @param {function} callback   Once processing is done.
   *
   * @returns {undefined}
   */
  step: function ESLintStep( change, path, position, callback ) {
    var comment = '';

    // On the line, only report on changes that were made.
    if ( change.add ) {
      for ( j = 0; j < this.checkedFiles.length; j++ ) {
        var f = this.checkedFiles[j];
        if ( f.file === path ) {
          for ( i = 0; i < f.errors.head.length; i++ ) {
            if ( f.errors.head[i] !== null && f.errors.head[i].line === change.ln ) {
              comment += f.errors.head[i].message + '\n```javascript\n' + f.errors.head[i].source + '\n```\n';
              f.errors.head[i].reported = true;
            }
          }
        }
      }
    }

    callback( comment );
  },

  /**
   * This event indicates the current pull request diff is completed.
   * It gives checker the opportunity to make a comment to the full
   * diff.
   *
   * @param {function} callback    Once processing is done.
   *
   * @returns {undefined}
   */
  done: function ESLintDone( callback ) {
    var comment = '';
    var maxErrorsPerFile = 5;

    // Look through all changed files and ensure that we
    // have not added more errors in this pull.
    for ( i = 0; i < this.checkedFiles.length; i++ ) {
      f = this.checkedFiles[i];

      // We are only interested if the head branch still has
      // lint issues.
      if ( f.errors.head.length > 0 ) {
        baseIndex = 0;
        headIndex = 0;

        // We want to limit to no more than 5 comments per file
        errorsCount = 0;

        // Keep searching till we get to the end of the issues
        // on head branch.
        while ( f.errors.head !== null && headIndex < f.errors.head.length && errorsCount < maxErrorsPerFile ) {
          // Make sure the current head error is not a null
          if ( f.errors.head[ headIndex] === null ) {
            headIndex++;
            continue;
          }

          // If we still have issues to look at on the base branch.
          if ( f.errors.base !== null && baseIndex < f.errors.base.length ) {

            // Make sure the current base error is not a null
            if ( f.errors.base[ baseIndex] === null ) {
              baseIndex++;
              continue;
            }

            // If this error is in both branches.
            if ( f.errors.base[ baseIndex ].line === f.errors.head[ headIndex ].line ) {

              // Ignore this line.
              baseIndex++;
              headIndex++;
            } else if ( f.errors.base[ baseIndex ].line < f.errors.head[ headIndex ].line ) {
              // Go to the next error as this error has
              // been removed from the head branch.
              baseIndex++;
            } else {
              // All these comments are not in the base branch, so they
              // are additional comments. Need to make sure we did not
              // report them in the line by line review.
              if ( !f.errors.head[headIndex].reported && f.errors.head[headIndex].severity >= this.SEVERITY_HIGH ) {
                comment += '\n**' + f.file + '(' + f.errors.head[ headIndex ].line + '):** *' + f.errors.head[ headIndex ].message + '*';
                comment += '\n```javascript\n' + f.errors.head[headIndex].source + '\n```\n';
                errorsCount++;
              }

              headIndex++;
            }
          } else {
            // All these comments are not in the base branch, so they
            // are additional comments. Need to make sure we did not
            // report them in the line by line review.
            if ( !f.errors.head[headIndex].reported && f.errors.head[headIndex].severity >= this.SEVERITY_HIGH ) {
              comment += '\n**' + f.file + '(' + f.errors.head[ headIndex ].line + '):** *' + f.errors.head[ headIndex ].message + '*';
              comment += '\n```javascript\n' + f.errors.head[headIndex].source + '\n```\n';
              errorsCount++;
            }

            headIndex++;
          }
        }
      }
    }

    callback( comment );
  }
};

// Make the module available to all
module.exports = checker;<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : networkHandler.js
* Module : NetworkHandler
* Location : /lib/businessTier/networkHandler
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-19   Matteo Furlan    Initial code
* =========================================================
*/

var Socket=require('../../presentationTier/socket.js');
var Routes=require('../../presentationTier/routes.js');

function NetworkHandler(app,io,norrisNamespace){
	if(app===undefined || io===undefined || norrisNamespace===undefined ||
		typeof app !== 'function' || app.lazyrouter===undefined ||
		typeof io !== 'object' || io.nsps===undefined ||
		typeof norrisNamespace !== 'string' || norrisNamespace.length<2 || norrisNamespace.indexOf('/')!==0
		){
		console.log('Error: 811');
		return;
	}
	this._app = app;
	this._io=io;
	this._norrisNamespace=norrisNamespace;
	this._routes=new Routes(this._app,this._norrisNamespace);
	this._routes.addRoutingPath(this._norrisNamespace,'pageList'); //page is pageList.ejs;
}
NetworkHandler.prototype.addPageToRouting = function(namespacePage) {
	if(typeof namespacePage !== 'string' || namespacePage.length<2 || namespacePage.indexOf('/')!==0){
		return false;
	}
	return this._routes.addRoutingPath(namespacePage,'page'); //page is page.ejs;
};
NetworkHandler.prototype.createSocket = function(namespace,attachedObject) {
	var sock=new Socket(this._io,namespace);
	sock.attachedObject(attachedObject,'configPageList');
	return sock;
};
module.exports = NetworkHandler;<commit_msg>fix networkhandler<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : networkHandler.js
* Module : NetworkHandler
* Location : /lib/businessTier/networkHandler
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-19   Matteo Furlan    Initial code
* =========================================================
*/

var Socket=require('../../presentationTier/socket.js');
var Routes=require('../../presentationTier/routes.js');

function NetworkHandler(app,io,norrisNamespace){
	if(app===undefined || io===undefined || norrisNamespace===undefined ||
		typeof app !== 'function' || app.lazyrouter===undefined ||
		typeof io !== 'object' || io.nsps===undefined ||
		typeof norrisNamespace !== 'string' || norrisNamespace.length<2 || norrisNamespace.indexOf('/')!==0
		){
		console.log('Error: 811');
		return;
	}
	this._app = app;
	this._io=io;
	this._norrisNamespace=norrisNamespace;
	this._routes=new Routes(this._app,this._norrisNamespace);
	this._routes.addRoutingPath(this._norrisNamespace,'pageList'); //page is pageList.ejs;
}
NetworkHandler.prototype.addPageToRouting = function(namespacePage) {
	if(typeof namespacePage !== 'string' || namespacePage.length<2 || namespacePage.indexOf('/')!==0){
		return false;
	}
	return this._routes.addRoutingPath(namespacePage,'page'); //page is page.ejs;
};
NetworkHandler.prototype.createSocket = function(namespace,attachedObject) {
	var sock=new Socket(this._io,namespace);
	sock.attachObject(attachedObject,'configPageList');
	return sock;
};
module.exports = NetworkHandler;<|endoftext|>


<commit_before>/**
 * 2D planar texture backend
 *
 */

define(["krusovice/thirdparty/jquery", "krusovice/thirdparty/three-bundle"], function($, THREE) {

    "use strict";

    function TextureBackground(options, data) {
        this.options = options;
        this.data = data || {};
    }

    $.extend(TextureBackground.prototype, {

        // The loaded Three.js texture
        texture : null,

        // Plane mesh presenting the background texture
        mesh : null,

        // horizon, wall
        type : null,

        /**
         * Load the referred texture in the memory
         */
        prepare : function(loader) {
            var self = this;

            function done(texture) {
                self.texture = texture;
            }

            this.type = this.data.type || "horizon";

            // Asynchronous texture load / co-operate
            // with show resource manager
            loader.loadTexture(this.options.src, undefined, done);
        },

        /**
         * Create an infinite plane with continous texture.
         *
         * The plane is always XY and Z=0
         *
         */
        buildScene : function(krusoviceRenderer) {

            var renderer = krusoviceRenderer.renderer; // ThreeJS backend

            var sizeOfMYJewelry = 100000;

            // https://github.com/mrdoob/three.js/blob/master/examples/webgl_materials_texture_anisotropy.html
            var maxAnisotropy = renderer.getMaxAnisotropy ? renderer.getMaxAnisotropy() : 16;
            var texture1 = this.texture;

            if(!texture1) {
                throw new Error("Texture loading has failed, cannot proceed");
            }

            var material1 = new THREE.MeshBasicMaterial( { color: 0xffffff, map: texture1 } );

            texture1.anisotropy = maxAnisotropy;
            texture1.wrapS = texture1.wrapT = THREE.RepeatWrapping;
            texture1.repeat.set( 512, 512 );

            var geometry = new THREE.PlaneGeometry(sizeOfMYJewelry, sizeOfMYJewelry);

            var mesh1 = new THREE.Mesh( geometry, material1 );
            mesh1.rotation.x = - Math.PI / 2;
            var scene = krusoviceRenderer.scene;
            scene.add(mesh1);

            // Object type hint for 2d post-processing
            mesh1.krusoviceTypeHint = "background";

            this.setupPlanePosition(mesh1);

            this.mesh = mesh1;

        },

        setupPlanePosition : function(mesh) {
            if(this.type == "horizon") {
                mesh.position.z = -10000;
                mesh.position.y = 2000;
                mesh.rotation.x = -1.1*Math.PI/3;
                mesh.updateMatrixWorld();
            } else {
                throw new Error("Unknown background texture plane type " + this.type);
            }
        },

        // XXX: Nothing to do
        render3d : function(krusoviceRenderer) {

            // Access Three.JS renderer instance
            var renderer = krusoviceRenderer.renderer;

            //this.mesh.position.z -= 1;

            //this.mesh.position.y += 1;
            //this.mesh.rotation.x -= 0.01;
            this.mesh.updateMatrixWorld();
        }

    });

    return TextureBackground;
});<commit_msg>Horizon background texture done<commit_after>/**
 * 2D planar texture backend
 *
 */

define(["krusovice/thirdparty/jquery", "krusovice/thirdparty/three-bundle"], function($, THREE) {

    "use strict";

    function TextureBackground(options, data) {
        this.options = options;
        this.data = data || {};
    }

    $.extend(TextureBackground.prototype, {

        // The loaded Three.js texture
        texture : null,

        // Plane mesh presenting the background texture
        mesh : null,

        // horizon, wall
        type : null,

        /**
         * Load the referred texture in the memory
         */
        prepare : function(loader) {
            var self = this;

            function done(texture) {
                self.texture = texture;
            }

            this.type = this.data.type || "horizon";

            // Asynchronous texture load / co-operate
            // with show resource manager
            loader.loadTexture(this.options.src, undefined, done);
        },

        /**
         * Create an infinite plane with continous texture.
         *
         * The plane is always XY and Z=0
         *
         */
        buildScene : function(krusoviceRenderer) {

            var renderer = krusoviceRenderer.renderer; // ThreeJS backend

            var sizeOfMYJewelry = 100000;

            // https://github.com/mrdoob/three.js/blob/master/examples/webgl_materials_texture_anisotropy.html
            var maxAnisotropy = renderer.getMaxAnisotropy ? renderer.getMaxAnisotropy() : 16;
            var texture1 = this.texture;

            if(!texture1) {
                throw new Error("Texture loading has failed, cannot proceed");
            }

            var material1 = new THREE.MeshBasicMaterial( { color: 0xffffff, map: texture1 } );

            texture1.anisotropy = maxAnisotropy;
            texture1.wrapS = texture1.wrapT = THREE.RepeatWrapping;
            texture1.repeat.set( 50, 50 );

            var geometry = new THREE.PlaneGeometry(sizeOfMYJewelry, sizeOfMYJewelry);

            var mesh = new THREE.Mesh( geometry, material1 );
            mesh.rotation.x = - Math.PI / 2;
            var scene = krusoviceRenderer.scene;
            scene.add(mesh);

            // Object type hint for 2d post-processing
            mesh.krusoviceTypeHint = "background";

            // Allow photos to cast shadows on wall like background
            mesh.receiveShadow = true;

            this.setupPlane(krusoviceRenderer, scene, mesh);

            this.mesh = mesh;

        },

        /**
         * Do plane type specific setup
         */
        setupPlane : function(krusoviceRenderer, scene, mesh) {
            if(this.type == "horizon") {
                mesh.position.z = -10000;
                mesh.position.y = 2000;
                mesh.rotation.x = -1.1*Math.PI/3;

                mesh.scale = new THREE.Vector3(100, 100, 100);

                mesh.updateMatrixWorld();

                // Fade to horizon
                scene.fog = new THREE.Fog(krusoviceRenderer.backgroundColor, 8000, 10000);
            } else {
                throw new Error("Unknown background texture plane type " + this.type);
            }
        },

        // XXX: Nothing to do
        render3d : function(krusoviceRenderer) {

            // Access Three.JS renderer instance
            var renderer = krusoviceRenderer.renderer;

            //this.mesh.position.z -= 1;
            //
            var mesh = this.mesh;
            mesh.scale.x += 100;
            mesh.scale.y += 100;
            mesh.scale.z += 100;

            //this.mesh.position.y += 1;
            //this.mesh.rotation.x -= 0.01;
            this.mesh.updateMatrixWorld();
        }

    });

    return TextureBackground;
});<|endoftext|>


<commit_before>'use strict'

//Globals will be the stage which is the parrent of all graphics, canvas object for resizing and the renderer which is pixi.js framebuffer.
var stage = new PIXI.Container();;
var canvas = document.getElementById("game");;
var renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );

// Create or grab the application
var app = app || {};

function init(){
        resize();
        renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );
        renderer.backgroundColor = 0x50503E;
        canvas.focus();

        app.Game.init(renderer, window, canvas, stage);
}

function resize(){
	var gameWidth = window.innerWidth;
	var gameHeight = window.innerHeight;
	var scaleToFitX = gameWidth / 1000;
	var scaleToFitY = gameHeight / 500;
	// Scaling statement belongs to: https://www.davrous.com/2012/04/06/modernizing-your-html5-canvas-games-part-1-hardware-scaling-css3/
	var optimalRatio = Math.min(scaleToFitX, scaleToFitY);
	var currentScreenRatio = gameWidth / gameHeight;
	if(currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
		canvas.style.width = gameWidth + "px";
		canvas.style.height = gameHeight + "px";
	}else{
		canvas.style.width = 1000 * optimalRatio + "px";
		canvas.style.height = 500 * optimalRatio + "px";
	}
}

window.addEventListener('resize', resize, false);
window.addEventListener('orientationchange', resize, false);<commit_msg>quick add person function<commit_after>'use strict'

//Globals will be the stage which is the parrent of all graphics, canvas object for resizing and the renderer which is pixi.js framebuffer.
var stage = new PIXI.Container();;
var canvas = document.getElementById("game");;
var renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );

// Create or grab the application
var app = app || {};

function init(){
        resize();
        renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );
        renderer.backgroundColor = 0x50503E;
        canvas.focus();

        app.Game.init(renderer, window, canvas, stage);
}

function resize(){
	var gameWidth = window.innerWidth;
	var gameHeight = window.innerHeight;
	var scaleToFitX = gameWidth / 1000;
	var scaleToFitY = gameHeight / 500;
	// Scaling statement belongs to: https://www.davrous.com/2012/04/06/modernizing-your-html5-canvas-games-part-1-hardware-scaling-css3/
	var optimalRatio = Math.min(scaleToFitX, scaleToFitY);
	var currentScreenRatio = gameWidth / gameHeight;
	if(currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
		canvas.style.width = gameWidth + "px";
		canvas.style.height = gameHeight + "px";
	}else{
		canvas.style.width = 1000 * optimalRatio + "px";
		canvas.style.height = 500 * optimalRatio + "px";
	}
}

//Creates a person
function makePerson(){
	var head = new PIXI.Graphics();
	var body = new PIXI.Graphics();
	var personCon = new PIXI.Container();

	head.lineStyle(2, 0x000000);
	head.beginFill(0xFFFF08, 0.5);
	head.drawCircle(100, 50, 30);
	head.endFill();

	body.lineStyle(2, 0x000000);
	body.beginFill(0xff0000, 0.5);
	body.drawEllipse(100, 50, 100, 50);
	body.endFill();

	personCon.addChild(body);
	personCon.addChild(head);
	stage.addChild(personCon);
}

window.addEventListener('resize', resize, false);
window.addEventListener('orientationchange', resize, false);
<|endoftext|>


<commit_before>const debug = require('debug')('dejaqu');

class DejaQu {
  constructor(redis = null, namespace = 'dejaqu') {
    if (redis == null) {
      throw new Error('Initialized without a Redis client.');
    }
    this.redis = redis.createClient();
    this.namespace = namespace;
    this.queues = [];
    this.expirationHanlder = new ExpirationHanlder(redis);
  }

  createQueue(name, userId) {
    const q = new Queue(redis, name, userId);
    this.queues.push(q);
  }
}

class Message {
  static deserialize(messageString) {
    return JSON.parse(messageString);
  }

  constructor(body, userId = null, refId = null, expiry = null) {
    if (body == null) {
      throw new Error('A message body is required.');
    }

    if (userId == null) {
      throw new Error('A userId is required.');
    }

    this.body = body;
    this.userId = userId;
    this.refId = refId;
    this.expiry = expiry;
  }

  serialize() {
    JSON.stringify(this);
  }
}

// sets up a FIFO queue
class Queue {
	constructor(redis, name = 'timeline', userId) {
    if (redis == null) {
      throw new Error('Redis is required. Duh.');
    }

    if (userId == null) {
      throw new Error('A userId is required.');
    }
    this.redis = redis;
    this.key = `user:${userId}:${name}`;
  }

	push(message) {
    return new Promise((resolve) => {
      const serializedMessage = message.serialize();
      if (message.expiry == null) {
        // push message to queue and don't publish an expire event
        this.redis.rpush(key, serializedMessage, () => {
          debug(`Pushed message ${message.id} to ${key}`);
          return resolve();
        });
      } else {
        // push message to queue and publish an expire event
        this.redis.multi()
          .rpush(key, serializedMessage)
          .set(`expires:user:${message.userId}:msg:${message.id}`, null, 'EX', message.expiry)
          .exec(() => {
            debug(`Pushed message ${message.id} to ${key}`);
            return resolve();
          });
      }
    });
  }

  // get messages in a certain range from the top of the list, i.e: 0..5
  // returns a Promise with the messages
	get(start = 0, stop = 5) {
    return new Promise((resolve) => {
      this.redis.lrange(key, start, stop, (err, res) => {
        debug(`Retrieving messages ${start}..${stop} from ${key}`);
        return resolve(res);
      });
    });
  }

  // delete the top message in the queue
  // returns a Promise with the deleted message
	pop() {
    return new Promise((resolve) => {
      this.redis.lpop(key, (err, res) => {
        debug(`Deleted top message in ${key}`);
        return resolve(res);
      });
    });
  }
}

// Subscribes to Redis keyspace events to delete expired messages from queues
class ExpirationHandler {
  constructor(redis) {
    subscriber = redis.createClient();
    subscriber.config('SET', 'notify-keyspace-events', 'Ex');

    client.on('error', function(err) {
      console.log('Error ' + err);
    });

    subscriber.on('error', function(err) {
      console.log('Error ' + err);
    });

    subscriber.psubscribe('__keyevent@0__:expired');

    subscriber.on('pmessage', function(pattern, channel, expiredKey) {
      // console.log('key [' +  expiredKey + '] has expired');
      var userUUID = expiredKey.split(':')[0];
      var User = require('../models/user');
      User.expireMessageForUser(userUUID, function(cb) {
        // console.log('expired message for user ' + userUUID);
      });
    });
  }
}

module.exports = {
  DejaQu,
  Message,
  Queue,
};
<commit_msg>Expiration key deserialization<commit_after>const debug = require('debug')('dejaqu');

class DejaQu {
  constructor(redis = null, namespace = 'dejaqu') {
    if (redis == null) {
      throw new Error('Initialized without a Redis client.');
    }
    this.redis = redis.createClient();
    this.namespace = namespace;
    this.queues = [];
    this.expirationHanlder = new ExpirationHanlder(redis);
  }

  createQueue(name, userId) {
    const q = new Queue(redis, name, userId);
    this.queues.push(q);
  }
}

class Message {
  static deserialize(messageString) {
    return JSON.parse(messageString);
  }

  constructor(body, userId = null, refId = null, expiry = null) {
    if (body == null) {
      throw new Error('A message body is required.');
    }

    if (userId == null) {
      throw new Error('A userId is required.');
    }

    this.body = body;
    this.userId = userId;
    this.refId = refId;
    this.expiry = expiry;
  }

  serialize() {
    JSON.stringify(this);
  }
}

// sets up a FIFO queue
class Queue {
	constructor(redis, name = 'timeline', userId) {
    if (redis == null) {
      throw new Error('Redis is required. Duh.');
    }

    if (userId == null) {
      throw new Error('A userId is required.');
    }
    this.redis = redis;
    this.key = `user:${userId}:${name}`;
  }

	push(message) {
    return new Promise((resolve) => {
      const serializedMessage = message.serialize();
      if (message.expiry == null) {
        // push message to queue and don't publish an expire event
        this.redis.rpush(key, serializedMessage, () => {
          debug(`Pushed message ${message.id} to ${key}`);
          return resolve();
        });
      } else {
        // push message to queue and publish an expire event
        const expirationKey = new ExpirationKey(name, userId, message);
        this.redis.multi()
          .rpush(key, serializedMessage)
          .set(expirationKey, null, 'EX', message.expiry)
          .exec(() => {
            debug(`Pushed message ${message.id} to ${key}`);
            return resolve();
          });
      }
    });
  }

  // get messages in a certain range from the top of the list, i.e: 0..5
  // returns a Promise with the messages
	get(start = 0, stop = 5) {
    return new Promise((resolve) => {
      this.redis.lrange(key, start, stop, (err, res) => {
        debug(`Retrieving messages ${start}..${stop} from ${key}`);
        return resolve(res);
      });
    });
  }

  // delete the top message in the queue
  // returns a Promise with the deleted message
	pop() {
    return new Promise((resolve) => {
      this.redis.lpop(key, (err, res) => {
        debug(`Deleted top message in ${key}`);
        return resolve(res);
      });
    });
  }
}

class ExpirationKey {
  static unpack(expiredKey) {
    const tokens = expiredKey.split(':');
    const userId = token[2];
    const queueName = token[3];
    const messageId = token[4];
    return new ExpirationKey(queueName, userId, messageId);
  }

  constructor(queueName, userId, message) {
    this.key = `expires:user:${userId}:${queueName}:${message.id}`;
  }
}

// Subscribes to Redis keyspace events to delete expired messages from queues
class ExpirationHandler {
  constructor(redis) {
    subscriber = redis.createClient();
    subscriber.config('SET', 'notify-keyspace-events', 'Ex');

    client.on('error', function(err) {
      console.log('Error ' + err);
    });

    subscriber.on('error', function(err) {
      console.log('Error ' + err);
    });

    subscriber.psubscribe('__keyevent@0__:expired');

    subscriber.on('pmessage', function(pattern, channel, expiredKey) {
      const expirationKey = ExpirationKey.unpack(expiredKey);
      const queueName = expirationKey.queueName;
      // iterate through queues and find the right one
      // q.pop();
    });
  }
}

module.exports = {
  DejaQu,
  Message,
  Queue,
};
<|endoftext|>


<commit_before>/* eslint-disable camelcase */

import r from 'src/db/connect'

import {
  lookupChapterId,
  lookupCycleId,
  writeCSV,
  parseArgs,
  shortenedPlayerId,
} from './util'
import {
  avgProjHours,
  avgHealthCulture,
  avgHealthTeamPlay,
  estimationBias,
  estimationAccuracy,
  avgProjCompleteness,
  avgProjQuality,
  playerReviewCount,
  recentCycleIds,
  recentProjectIds,
  recentProjStats,
  projReviewCounts,
} from './playerStatHelpers'

const HEADERS = [
  'cycle_no',
  'player_id',
  'xp',
  // FIXME: We'd rather have `avg_cycle_hours` than `avg_proj_hours`.
  'avg_proj_hours',
  'avg_proj_comp',
  'avg_proj_qual',
  'health_culture',
  'health_team_play',
  'health_technical',
  'est_accuracy',
  'est_bias',
  'no_proj_rvws',
  'elo',
]

export default function requestHandler(req, res) {
  return runReport(req.query, res)
    .then(result => writeCSV(result, res, {headers: HEADERS}))
}

async function runReport(args) {
  const {cycleNumber, chapterName} = parseArgs(args)

  const chapterId = await lookupChapterId(chapterName)
  const cycleId = await lookupCycleId(chapterId, cycleNumber)

  return await statReport({chapterId, cycleId, cycleNumber})
}

async function statReport(params) {
  const {chapterId, cycleNumber} = params
  const latestProjIds = recentProjectIds(recentCycleIds(chapterId, cycleNumber))
  const reviewCount = projReviewCounts()

  return await r.table('players')
    .filter(r.row('chapterId').eq(chapterId)
             .and(r.row('active').eq(true)
             .and(r.row('stats').hasFields('projects'))))
    .merge(avgProjHours)
    .merge(recentProjStats(latestProjIds))
    .merge(avgHealthCulture)
    .merge(avgHealthTeamPlay)
    .merge(estimationBias)
    .merge(estimationAccuracy)
    .merge(playerReviewCount(reviewCount))
    .merge(avgProjCompleteness)
    .merge(avgProjQuality)
    .map(player => {
      return {
        cycle_no: cycleNumber,
        player_id: shortenedPlayerId(player('id')),
        xp: player('stats')('xp'),
        health_culture: player('health_culture'),
        health_team_play: player('health_team_play'),
        est_bias: player('est_bias'),
        est_accuracy: player('est_accuracy'),
        avg_proj_hours: player('avg_proj_hours'),
        avg_proj_comp: player('avg_proj_comp'),
        avg_proj_qual: player('avg_proj_qual'),
        no_proj_rvws: player('no_proj_rvws'),
        elo: player('stats')('elo')('rating'),
      }
    })
}
<commit_msg>Remove unused cycleId<commit_after>/* eslint-disable camelcase */

import r from 'src/db/connect'

import {
  lookupChapterId,
  writeCSV,
  parseArgs,
  shortenedPlayerId,
} from './util'
import {
  avgProjHours,
  avgHealthCulture,
  avgHealthTeamPlay,
  estimationBias,
  estimationAccuracy,
  avgProjCompleteness,
  avgProjQuality,
  playerReviewCount,
  recentCycleIds,
  recentProjectIds,
  recentProjStats,
  projReviewCounts,
} from './playerStatHelpers'

const HEADERS = [
  'cycle_no',
  'player_id',
  'xp',
  // FIXME: We'd rather have `avg_cycle_hours` than `avg_proj_hours`.
  'avg_proj_hours',
  'avg_proj_comp',
  'avg_proj_qual',
  'health_culture',
  'health_team_play',
  'health_technical',
  'est_accuracy',
  'est_bias',
  'no_proj_rvws',
  'elo',
]

export default function requestHandler(req, res) {
  return runReport(req.query, res)
    .then(result => writeCSV(result, res, {headers: HEADERS}))
}

async function runReport(args) {
  const {cycleNumber, chapterName} = parseArgs(args)

  const chapterId = await lookupChapterId(chapterName)

  return await statReport({chapterId, cycleNumber})
}

async function statReport(params) {
  const {chapterId, cycleNumber} = params
  const latestProjIds = recentProjectIds(recentCycleIds(chapterId, cycleNumber))
  const reviewCount = projReviewCounts()

  return await r.table('players')
    .filter(r.row('chapterId').eq(chapterId)
             .and(r.row('active').eq(true)
             .and(r.row('stats').hasFields('projects'))))
    .merge(avgProjHours)
    .merge(recentProjStats(latestProjIds))
    .merge(avgHealthCulture)
    .merge(avgHealthTeamPlay)
    .merge(estimationBias)
    .merge(estimationAccuracy)
    .merge(playerReviewCount(reviewCount))
    .merge(avgProjCompleteness)
    .merge(avgProjQuality)
    .map(player => {
      return {
        cycle_no: cycleNumber,
        player_id: shortenedPlayerId(player('id')),
        xp: player('stats')('xp'),
        health_culture: player('health_culture'),
        health_team_play: player('health_team_play'),
        est_bias: player('est_bias'),
        est_accuracy: player('est_accuracy'),
        avg_proj_hours: player('avg_proj_hours'),
        avg_proj_comp: player('avg_proj_comp'),
        avg_proj_qual: player('avg_proj_qual'),
        no_proj_rvws: player('no_proj_rvws'),
        elo: player('stats')('elo')('rating'),
      }
    })
}
<|endoftext|>


<commit_before>var newwindow

function popup_new_window(url)
{
    newwindow=window.open(url,'help','width=800,height=400,scrollbars=yes,menubar=no,resizable=yes,toolbar=no,status=no');
}
function popup(url) {
    if (newwindow)
	newwindow.close();

    newwindow=window.open(url,'help','width=600,height=400,scrollbars=yes,menubar=no,resizable=yes,toolbar=no,status=no');
    newwindow.moveTo(220, 100)
}
function popupWithSizes(url, width, height) {
    if (newwindow) newwindow.close();
    newwindow=window.open(url,'help','width=' + width + ',height=' + height + ',scrollbars=yes,menubar=no,resizable=yes,toolbar=no,status=no');
}
function openHelp(tag) {
	var url = '/treebase-web/help.html?helpTag=' + tag;
	var req = new Ajax.Request(url, {
		'method':'get',
		'onSuccess':function(response){
			top.consoleRef=window.open('','help',
		  		'width=400,height=350'
		   		+',menubar=no'
		   		+',toolbar=no'
		   		+',location=no'
		   		+',status=no'
		   		+',top=100'
		   		+',left=100'
		   		+',scrollbars=yes'
		   		+',resizable=yes');
		   	if ( top.consoleRef == null || top.consoleRef.closed ) {
		   		alert("Couldn't open window! The help system requires that popups are allowed for the TreeBASE site.");
		   	}
		 	top.consoleRef.document.writeln(response.responseText);
		 	top.consoleRef.document.close();
		}
	});
}

/*
	The TreeBASE object has three functions:
	1. it provides for a way to scope our javascript code within the TreeBASE
	namespace so it doesn't clash with all the other libraries we're using
	2. it allows you to register callbacks with it
	3. it implements a TreeBASE.initialize() method that executes those
	registered callbacks. Typically we would call this from within the
	body tag, i.e. , as is done in the
	main template. This allows us to write more unobtrusive javascript.
*/
var TreeBASE = {
	'init' : [],
	'initialize' : function () {
		for ( var i = 0; i < TreeBASE.init.length; i++ ) {
			TreeBASE.init[i]();
		}
	},
	'register' : function(func) {
		TreeBASE.init.push(func);
	}
};

/*
	Here we register a function that fetches all table headers for columns that
	contain icon buttons (i.e. of class "iconColumn"). It sets the background of
	those header cells to pink, and places a link to the icon legend in the first
	of these header cells.
*/
TreeBASE.register(
	function () {
		var headers = document.getElementsByTagName('th');
		var iconColumnHeaders = new Array();
		for ( var i = 0; i < headers.length; i++ ) {
			if ( headers[i].className == 'iconColumn' ) {
				iconColumnHeaders.push(headers[i]);
			}
		}
		if ( iconColumnHeaders.length > 0 ) {
			iconColumnHeaders[0].innerHTML = '';
			for ( var i = 0; i < iconColumnHeaders.length; i++ ) {
				iconColumnHeaders[i].style.backgroundColor = 'pink';
			}
		}
	}
);

/*
	Here we register a function that fetches all input elements for text of class
	"textCell", to which we add the following behaviours:
	1. onfocus (i.e. we click in the input) it selects the text it contains
	2. onfocus we change the border to soft blue
	3. onblur (i.e. we leave the input) we go back to the previous border
*/

TreeBASE.register(
	function() {
		var inputs = $$('.textCell');
		for ( var i = 0; i < inputs.length; i++ ) {
			if ( inputs[i] ) {
				var currentColor = inputs[i].style.borderColor;
				inputs[i].onfocus = function () {
					this.style.borderColor = '#3863A4';
					this.select();
				}
				inputs[i].onblur = function () {
					this.style.borderColor = currentColor;
				}
			}
		}
	}
);

TreeBASE.register(
	function () {
	    if ( document.getElementsByClassName ) {
            var checkBoxCells = $$('.checkBoxColumn');
            var buttonContainer = $('buttonContainer');
            if ( checkBoxCells.length > 0 && buttonContainer ) {
                var checkButton = new Element('input',{'type':'button','value':'Check all'});
                checkButton.observe('click',function () {
                    for ( var i = 0; i < checkBoxCells.length; i++ ) {
                        if ( checkBoxCells[i] ) {
                            var checkBoxes = $(checkBoxCells[i]).select('input');
                            for ( var j = 0; j < checkBoxes.length; j++ ) {
                                if ( checkBoxes[j] && checkBoxes[j].type == 'checkbox' || checkBoxes[j].type == 'radio' ) {
                                    if ( ! checkBoxes[j].disabled ) {
                                        checkBoxes[j].checked = 'checked';
                                    }
                                }
                            }
                        }
                    }
                });
                var uncheckButton = new Element('input',{'type':'button','value':'Uncheck all'});
                uncheckButton.observe('click',function () {
                    for ( var i = 0; i < checkBoxCells.length; i++ ) {
                        if ( checkBoxCells[i] ) {
                            var checkBoxes = $(checkBoxCells[i]).select('input');
                            for ( var j = 0; j < checkBoxes.length; j++ ) {
                                if ( checkBoxes[j] && checkBoxes[j].type == 'checkbox' || checkBoxes[j].type == 'radio' ) {
                                    if ( ! checkBoxes[j].disabled ) {
                                        checkBoxes[j].checked = null;
                                    }
                                }
                            }
                        }
                    }
                });
                var invertButton = new Element('input',{'type':'button','value':'Invert'});
                invertButton.observe('click',function () {
                    for ( var i = 0; i < checkBoxCells.length; i++ ) {
                        if ( checkBoxCells[i] ) {
                            var checkBoxes = $(checkBoxCells[i]).select('input');
                            for ( var j = 0; j < checkBoxes.length; j++ ) {
                                if ( checkBoxes[j] && checkBoxes[j].type == 'checkbox' || checkBoxes[j].type == 'radio' ) {
                                    if ( ! checkBoxes[j].disabled ) {
                                        if ( checkBoxes[j].checked ) {
                                            checkBoxes[j].checked = null;
                                        }
                                        else {
                                            checkBoxes[j].checked = 'checked';
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
                buttonContainer.insertBefore(invertButton,buttonContainer.firstChild);
                buttonContainer.insertBefore(uncheckButton,buttonContainer.firstChild);
                buttonContainer.insertBefore(checkButton,buttonContainer.firstChild);
            }
		}
	}
);

/* add a tooltip for the help buttons */
TreeBASE.register(
	function() {
		var links = document.getElementsByTagName('a');
		for ( var i = 0; i < links.length; i++ ) {
			var link = $(links[i]);
			if ( link.hasClassName('openHelp') ) {
				if ( link.title == null || link.title == '' ) {
					link.title = 'Open help popup';
				}
			}
		}
	}
);

/*
	Collapse/expands elements (identified by id), where
	the expanded version is shown as 'displayAs' (i.e.
	'block' or 'inline'). This behaviour is added to
	'link', such that:

*/
TreeBASE.collapseExpand = function(id,displayAs,link) {
	var objToExpand = $(id);
	var img = $(link).firstDescendant();
	if ( img == null ) {
		img = document.createElement(img);
		link.appendChild(img);
	}
	if ( objToExpand.style.display == 'none' ) {
		objToExpand.style.display = displayAs;
		img.src='/treebase-web/images/minus.gif';
		img.alt='collapse'
		link.title='collapse';
	}
	else {
		objToExpand.style.display = 'none';
		img.src='/treebase-web/images/plus.gif';
		img.alt='expand';
		link.title='expand';
	}
}
//expands what a user types in the text box into a PhyloWS query
TreeBASE.expandQuery = function () {
  var query = $('query').value;
  var split = TreeBASE.splitWords(query);
  var terms = new Array();
  for ( var i = 0; i < split.length; i++ ) {
    var type = TreeBASE.inferType(split[i]);
    var index = predicates[type];
    for ( var j = 0; j < index.length; j++ ) {
      terms.push( index[j] + '=' + split[i] );
    }
  }
  var joiner = ' or ';
  if ( $('all').checked ) {
    joiner = ' and ';
  }
  $('expanded').value = terms.join(joiner);
  return false;
};

// splits a string on words (including curies) and quoted phrases
TreeBASE.splitWords = function(query){
  //return query.match(/[A-Za-z0-9: ]+|"[^"]+"|'[^']+'|/g);
	return query.split(",");
};

// infers whether a search word is an identifier or a string
TreeBASE.inferType = function(word) {
  if ( word.match(/^([A-Z][a-z]*)\d+$/) ) {
    return 'id';
  }
  else if ( word.match(/^\d+$/) ) {
    return 'integer';
  }
  else if ( word.match(/^doi:.+$/) ) {
    return 'doi';
  }
  else if ( word.match(/^pmid:.+$/) ) {
    return 'pubmed';
  }
  else {
    return 'word';
  }
};

// redirects to the phylows api
TreeBASE.redirect = function(newLocation){
  window.location = newLocation;
  return false;
};
<commit_msg>TreeBASE.splitWords() now splits on commas, afterwords double-quotes words with spaces in them.<commit_after>var newwindow

function popup_new_window(url)
{
    newwindow=window.open(url,'help','width=800,height=400,scrollbars=yes,menubar=no,resizable=yes,toolbar=no,status=no');
}
function popup(url) {
    if (newwindow)
	newwindow.close();

    newwindow=window.open(url,'help','width=600,height=400,scrollbars=yes,menubar=no,resizable=yes,toolbar=no,status=no');
    newwindow.moveTo(220, 100)
}
function popupWithSizes(url, width, height) {
    if (newwindow) newwindow.close();
    newwindow=window.open(url,'help','width=' + width + ',height=' + height + ',scrollbars=yes,menubar=no,resizable=yes,toolbar=no,status=no');
}
function openHelp(tag) {
	var url = '/treebase-web/help.html?helpTag=' + tag;
	var req = new Ajax.Request(url, {
		'method':'get',
		'onSuccess':function(response){
			top.consoleRef=window.open('','help',
		  		'width=400,height=350'
		   		+',menubar=no'
		   		+',toolbar=no'
		   		+',location=no'
		   		+',status=no'
		   		+',top=100'
		   		+',left=100'
		   		+',scrollbars=yes'
		   		+',resizable=yes');
		   	if ( top.consoleRef == null || top.consoleRef.closed ) {
		   		alert("Couldn't open window! The help system requires that popups are allowed for the TreeBASE site.");
		   	}
		 	top.consoleRef.document.writeln(response.responseText);
		 	top.consoleRef.document.close();
		}
	});
}

/*
	The TreeBASE object has three functions:
	1. it provides for a way to scope our javascript code within the TreeBASE
	namespace so it doesn't clash with all the other libraries we're using
	2. it allows you to register callbacks with it
	3. it implements a TreeBASE.initialize() method that executes those
	registered callbacks. Typically we would call this from within the
	body tag, i.e. , as is done in the
	main template. This allows us to write more unobtrusive javascript.
*/
var TreeBASE = {
	'init' : [],
	'initialize' : function () {
		for ( var i = 0; i < TreeBASE.init.length; i++ ) {
			TreeBASE.init[i]();
		}
	},
	'register' : function(func) {
		TreeBASE.init.push(func);
	}
};

/*
	Here we register a function that fetches all table headers for columns that
	contain icon buttons (i.e. of class "iconColumn"). It sets the background of
	those header cells to pink, and places a link to the icon legend in the first
	of these header cells.
*/
TreeBASE.register(
	function () {
		var headers = document.getElementsByTagName('th');
		var iconColumnHeaders = new Array();
		for ( var i = 0; i < headers.length; i++ ) {
			if ( headers[i].className == 'iconColumn' ) {
				iconColumnHeaders.push(headers[i]);
			}
		}
		if ( iconColumnHeaders.length > 0 ) {
			iconColumnHeaders[0].innerHTML = '';
			for ( var i = 0; i < iconColumnHeaders.length; i++ ) {
				iconColumnHeaders[i].style.backgroundColor = 'pink';
			}
		}
	}
);

/*
	Here we register a function that fetches all input elements for text of class
	"textCell", to which we add the following behaviours:
	1. onfocus (i.e. we click in the input) it selects the text it contains
	2. onfocus we change the border to soft blue
	3. onblur (i.e. we leave the input) we go back to the previous border
*/

TreeBASE.register(
	function() {
		var inputs = $$('.textCell');
		for ( var i = 0; i < inputs.length; i++ ) {
			if ( inputs[i] ) {
				var currentColor = inputs[i].style.borderColor;
				inputs[i].onfocus = function () {
					this.style.borderColor = '#3863A4';
					this.select();
				}
				inputs[i].onblur = function () {
					this.style.borderColor = currentColor;
				}
			}
		}
	}
);

TreeBASE.register(
	function () {
	    if ( document.getElementsByClassName ) {
            var checkBoxCells = $$('.checkBoxColumn');
            var buttonContainer = $('buttonContainer');
            if ( checkBoxCells.length > 0 && buttonContainer ) {
                var checkButton = new Element('input',{'type':'button','value':'Check all'});
                checkButton.observe('click',function () {
                    for ( var i = 0; i < checkBoxCells.length; i++ ) {
                        if ( checkBoxCells[i] ) {
                            var checkBoxes = $(checkBoxCells[i]).select('input');
                            for ( var j = 0; j < checkBoxes.length; j++ ) {
                                if ( checkBoxes[j] && checkBoxes[j].type == 'checkbox' || checkBoxes[j].type == 'radio' ) {
                                    if ( ! checkBoxes[j].disabled ) {
                                        checkBoxes[j].checked = 'checked';
                                    }
                                }
                            }
                        }
                    }
                });
                var uncheckButton = new Element('input',{'type':'button','value':'Uncheck all'});
                uncheckButton.observe('click',function () {
                    for ( var i = 0; i < checkBoxCells.length; i++ ) {
                        if ( checkBoxCells[i] ) {
                            var checkBoxes = $(checkBoxCells[i]).select('input');
                            for ( var j = 0; j < checkBoxes.length; j++ ) {
                                if ( checkBoxes[j] && checkBoxes[j].type == 'checkbox' || checkBoxes[j].type == 'radio' ) {
                                    if ( ! checkBoxes[j].disabled ) {
                                        checkBoxes[j].checked = null;
                                    }
                                }
                            }
                        }
                    }
                });
                var invertButton = new Element('input',{'type':'button','value':'Invert'});
                invertButton.observe('click',function () {
                    for ( var i = 0; i < checkBoxCells.length; i++ ) {
                        if ( checkBoxCells[i] ) {
                            var checkBoxes = $(checkBoxCells[i]).select('input');
                            for ( var j = 0; j < checkBoxes.length; j++ ) {
                                if ( checkBoxes[j] && checkBoxes[j].type == 'checkbox' || checkBoxes[j].type == 'radio' ) {
                                    if ( ! checkBoxes[j].disabled ) {
                                        if ( checkBoxes[j].checked ) {
                                            checkBoxes[j].checked = null;
                                        }
                                        else {
                                            checkBoxes[j].checked = 'checked';
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
                buttonContainer.insertBefore(invertButton,buttonContainer.firstChild);
                buttonContainer.insertBefore(uncheckButton,buttonContainer.firstChild);
                buttonContainer.insertBefore(checkButton,buttonContainer.firstChild);
            }
		}
	}
);

/* add a tooltip for the help buttons */
TreeBASE.register(
	function() {
		var links = document.getElementsByTagName('a');
		for ( var i = 0; i < links.length; i++ ) {
			var link = $(links[i]);
			if ( link.hasClassName('openHelp') ) {
				if ( link.title == null || link.title == '' ) {
					link.title = 'Open help popup';
				}
			}
		}
	}
);

/*
	Collapse/expands elements (identified by id), where
	the expanded version is shown as 'displayAs' (i.e.
	'block' or 'inline'). This behaviour is added to
	'link', such that:

*/
TreeBASE.collapseExpand = function(id,displayAs,link) {
	var objToExpand = $(id);
	var img = $(link).firstDescendant();
	if ( img == null ) {
		img = document.createElement(img);
		link.appendChild(img);
	}
	if ( objToExpand.style.display == 'none' ) {
		objToExpand.style.display = displayAs;
		img.src='/treebase-web/images/minus.gif';
		img.alt='collapse'
		link.title='collapse';
	}
	else {
		objToExpand.style.display = 'none';
		img.src='/treebase-web/images/plus.gif';
		img.alt='expand';
		link.title='expand';
	}
}
//expands what a user types in the text box into a PhyloWS query
TreeBASE.expandQuery = function () {
  var query = $('query').value;
  var split = TreeBASE.splitWords(query);
  var terms = new Array();
  for ( var i = 0; i < split.length; i++ ) {
    var type = TreeBASE.inferType(split[i]);
    var index = predicates[type];
    for ( var j = 0; j < index.length; j++ ) {
      terms.push( index[j] + '=' + split[i] );
    }
  }
  var joiner = ' or ';
  if ( $('all').checked ) {
    joiner = ' and ';
  }
  $('expanded').value = terms.join(joiner);
  return false;
};

// splits a string on commas, strip leading and trailing white space, quote words with spaces in them
TreeBASE.splitWords = function(query){
	var words = query.split(",");
	var split = new Array();
	for ( var i = 0; i < words.length; i++ ) {
		var word = words[i].replace(/^ */,'');
		word = word.replace(/ *$/,'';)
		if ( word.match(/ /) ) {
			split.push('"' + word + '"');
		}
		else {
			split.push(word);
		}
	}
	return split;
};

// infers whether a search word is an identifier or a string
TreeBASE.inferType = function(word) {
  if ( word.match(/^([A-Z][a-z]*)\d+$/) ) {
    return 'id';
  }
  else if ( word.match(/^\d+$/) ) {
    return 'integer';
  }
  else if ( word.match(/^doi:.+$/) ) {
    return 'doi';
  }
  else if ( word.match(/^pmid:.+$/) ) {
    return 'pubmed';
  }
  else {
    return 'word';
  }
};

// redirects to the phylows api
TreeBASE.redirect = function(newLocation){
  window.location = newLocation;
  return false;
};
<|endoftext|>


<commit_before>import React from 'react';
import { shallow } from 'enzyme';
import TestUtils from 'react-dom/test-utils';
import Decimal from './decimal.component';
import Textbox from '../textbox/textbox.component';

function render(props) {
  const onChange = props.onChange ? props.onChange : () => true;

  return shallow(
    <Decimal
      onChange={ onChange }
      value={ props.value }
      precision={ props.precision }
    />
  );
}

function renderIntoDocument(props) {
  return TestUtils.renderIntoDocument(
    <Decimal value={ props.value } precision={ props.precision } />
  );
}

function assertCorrectlyFormattedVal(instance, value) {
  return expect(instance.formatValue()).toEqual(value);
}

function assertCorrectTextboxVal(wrapper, value) {
  return expect(wrapper.find(Textbox).prop('value')).toEqual(value);
}

describe('Decimal', () => {
  describe('Input validation', () => {
    it('renders the correct value', () => {
      const wrapper = render({ value: '9.87' });
      assertCorrectTextboxVal(wrapper, '9.87');
    });

    it('renders a value from props exactly even when invalid', () => {
      const wrapper = render({ value: '12abc.85' });
      assertCorrectTextboxVal(wrapper, '12abc.85');
    });

    it('updates an external state onChange', () => {
      const onChange = jest.fn();
      const wrapper = render({ onChange });
      const input = wrapper.find(Textbox);
      input.simulate('change', { target: { value: '14.79' } });
      expect(onChange).toHaveBeenCalledWith({ target: { value: '14.79' } });
    });

    it('does not allow the user to enter letters or special characters', () => {
      const wrapper = render({ value: '12.34' });
      wrapper.instance().onChange({ target: { value: '1!@£$%^&*()#_+=}{|":;\<>?qwertyuiopasd\'fghjklzxcvbnm1.27' } });
      assertCorrectTextboxVal(wrapper, '12.34');
    });

    it('does not allow the user to enter commas after the decimal point', () => {
      const wrapper = render({ value: '34.56' });
      wrapper.instance().onChange({ target: { value: '34.5,,,,6' } });
      assertCorrectTextboxVal(wrapper, '34.56');
    });

    it('forces change event if user blurs', () => {
      const onChange = jest.fn();
      const wrapper = render({ onChange });
      wrapper.instance().onBlur({ target: { value: '1' } });
      expect(onChange).toHaveBeenCalled();
    });

    it('formats with delimiters with input is not active', () => {
      const instance = renderIntoDocument({ value: '1234567.00' });
      assertCorrectlyFormattedVal(instance, '1,234,567.00');
    });

    it('updates the value after increasing the precison', () => {
      const instance = renderIntoDocument({ value: '99.99', precision: 4 });
      assertCorrectlyFormattedVal(instance, '99.9900');
    });

    it('updates the value after decreasing the precison', () => {
      const instance = renderIntoDocument({ value: '234.1234567', precision: 4 });
      assertCorrectlyFormattedVal(instance, '234.1235');
    });

    it('does not allow the precison to be greater than 15', () => {
      const instance = renderIntoDocument({ value: '4.1234', precision: 20 });
      assertCorrectlyFormattedVal(instance, '4.123400000000000');
    });

    it('does not format number if input is active', () => {
      const instance = renderIntoDocument({ value: '1234567.00' });
      instance._document = {
        activeElement: instance.input.current
      };
      assertCorrectlyFormattedVal(instance, '1234567.00');
    });
  });
  describe('Input handling', () => {
    it('calls setSelection after passing invalid value', async () => {
      const setSelectionMock = jest.fn();
      jest.useFakeTimers();
      const evt = {
        target: {
          value: '123s456.78',
          setSelectionRange: setSelectionMock,
          selectionEnd: 3
        }
      };
      const input = render({ value: '1234567.00' });
      input.instance().onChange(evt);
      jest.runAllTimers();
      expect(setSelectionMock).toHaveBeenCalledWith(2, 2);
    });
  });
});
<commit_msg>Update Decimal Specs with Mount Func<commit_after>import React from 'react';
import { shallow, mount } from 'enzyme';
import Decimal from './decimal.component';
import Textbox from '../textbox/textbox.component';

function render(props, render = shallow) {
  const onChange = props.onChange ? props.onChange : () => true;

  return render(
    <Decimal
      onChange={ onChange }
      value={ props.value }
      precision={ props.precision }
    />
  );
}

function assertCorrectTextboxVal(wrapper, value) {
  return expect(wrapper.find(Textbox).prop('value')).toEqual(value);
}

describe('Decimal', () => {
  describe('Input validation', () => {
    it('renders the correct value', () => {
      const wrapper = render({ value: '9.87' });
      assertCorrectTextboxVal(wrapper, '9.87');
    });

    it('renders a value from props exactly even when invalid', () => {
      const wrapper = render({ value: '12abc.85' });
      assertCorrectTextboxVal(wrapper, '12abc.85');
    });

    it('updates an external state onChange', () => {
      const onChange = jest.fn();
      const wrapper = render({ onChange });
      const input = wrapper.find(Textbox);
      input.simulate('change', { target: { value: '14.79' } });
      expect(onChange).toHaveBeenCalledWith({ target: { value: '14.79' } });
    });

    it('does not allow the user to enter letters or special characters', () => {
      const wrapper = render({ value: '12.34' });
      wrapper.instance().onChange({ target: { value: '1!@£$%^&*()#_+=}{|":;\<>?qwertyuiopasd\'fghjklzxcvbnm1.27' } });
      assertCorrectTextboxVal(wrapper, '12.34');
    });

    it('does not allow the user to enter commas after the decimal point', () => {
      const wrapper = render({ value: '34.56' });
      wrapper.instance().onChange({ target: { value: '34.5,,,,6' } });
      assertCorrectTextboxVal(wrapper, '34.56');
    });

    it('forces change event if user blurs', () => {
      const onChange = jest.fn();
      const wrapper = render({ onChange });
      wrapper.instance().onBlur({ target: { value: '1' } });
      expect(onChange).toHaveBeenCalled();
    });

    it('formats with delimiters when input is not active', () => {
      const wrapper = render({ value: '12345.00' }, mount);

      wrapper.setProps({ value: '1234567.00' });
      assertCorrectTextboxVal(wrapper, '1,234,567.00');
    });

    it('updates the value after increasing the precison', () => {
      const wrapper = render({ value: '99.99' }, mount);

      wrapper.setProps({ precision: 4 });
      assertCorrectTextboxVal(wrapper, '99.9900');
    });

    it('updates the value after decreasing the precison', () => {
      const wrapper = render({ value: '234.1234567' }, mount);

      wrapper.setProps({ precision: 4 });
      assertCorrectTextboxVal(wrapper, '234.1235');
    });

    it('does not allow the precison to be greater than 15', () => {
      const wrapper = render({ value: '4.1234' }, mount);

      wrapper.setProps({ precision: 20 });
      assertCorrectTextboxVal(wrapper, '4.123400000000000');
    });

    it('does not format number if input is active', () => {
      const wrapper = render({ value: '1234.00' }, mount);

      wrapper.instance()._document = {
        activeElement: wrapper.instance().input.current
      };
      wrapper.setProps({ value: '1234.00' });
      assertCorrectTextboxVal(wrapper, '1234.00');
    });
  });
  describe('Input handling', () => {
    it('calls setSelection after passing invalid value', async () => {
      const setSelectionMock = jest.fn();
      jest.useFakeTimers();
      const evt = {
        target: {
          value: '123s456.78',
          setSelectionRange: setSelectionMock,
          selectionEnd: 3
        }
      };
      const input = render({ value: '1234567.00' });
      input.instance().onChange(evt);
      jest.runAllTimers();
      expect(setSelectionMock).toHaveBeenCalledWith(2, 2);
    });
  });
});
<|endoftext|>


<commit_before>//Create browser compatible event listener
function listener(elem, evnt, func, parentSocketConnection)
{
  if (elem.addEventListener)
      elem.addEventListener(evnt,func,false);
  else if (elem.attachEvent) // For IE
      return elem.attachEvent("on" + evnt, func);
}
function player(properties){
  //define public vars
  this.monsters = [];
  this.x = 0;
  this.y = 0;
  this.health = 0;
  this.maxhealth = 0;
  this.color = "#FFFFFF";
  //define constructor
  if (properties.hasOwnProperty("x")) {
    this.x = properties.x;
  }
  if (properties.hasOwnProperty("y")) {
    this.y = properties.y;
  }
  if (properties.hasOwnProperty("color")) {
    this.color = properties.color;
  }
  if (properties.hasOwnProperty("health")) {
    this.health = properties.health;
  }
  if (properties.hasOwnProperty("maxhealth")) {
    this.maxhealth = properties.maxhealth;
  }
  if (properties.hasOwnProperty("monsters")) {
    if (Array.isArray(properties.monsters)) {

    }
  }
  if (properties.hasOwnProperty('canvas')) {
    this.canvas = properties.canvas;
  }
  if (properties.hasOwnProperty('parentSocketConnection')) {
  this.parentSocketConnection =  properties.parentSocketConnection;
  }
  this.draw();
  function movePlayer(e){
    console.log(e);
  }
  /*
Keyboard event listener
  */
listener(document, 'keydown', movePlayer,this.parentSocketConnection);

}
player.prototype.draw = function () {
  var canvas = document.getElementById(String(this.canvas));
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = String(this.color);
  ctx.fillRect(this.x*10,this.y*10,10,10);
}
<commit_msg>send data to server<commit_after>//Create browser compatible event listener with parameter passing
function listener(elem, evnt, func, parameters)
{
  elem.socketConnection = parameters[0];
  elem.x = parameters[1];
  elem.x = parameters[2];
  if (elem.addEventListener) {

      elem.addEventListener(evnt,func,false);
    } else if (elem.attachEvent) { // For IE

      return elem.attachEvent("on" + evnt, func);
    }
}
function player(properties){
  //define public vars
  this.monsters = [];
  this.x = 0;
  this.y = 0;
  this.health = 0;
  this.maxhealth = 0;
  this.color = "#FFFFFF";
  //define constructor
  if (properties.hasOwnProperty("x")) {
    this.x = properties.x;
  }
  if (properties.hasOwnProperty("y")) {
    this.y = properties.y;
  }
  if (properties.hasOwnProperty("color")) {
    this.color = properties.color;
  }
  if (properties.hasOwnProperty("health")) {
    this.health = properties.health;
  }
  if (properties.hasOwnProperty("maxhealth")) {
    this.maxhealth = properties.maxhealth;
  }
  if (properties.hasOwnProperty("monsters")) {
    if (Array.isArray(properties.monsters)) {

    }
  }
  if (properties.hasOwnProperty('canvas')) {
    this.canvas = properties.canvas;
  }
  if (properties.hasOwnProperty('parentSocketConnection')) {
  this.parentSocketConnection =  properties.parentSocketConnection;
  }
  this.draw();
  function movePlayer(e){
  switch (e.keyCode) {
    case 38:
      //up
      e.target.socketConnection.socket.emit('action', {
          "type":"move",
          "direction":"up"
      });
      break;
      case 38:
        //up
        break;
    default:
  }
  //send action to server

  }
  /*
Keyboard event listener
  */
listener(document, 'keydown', movePlayer, [this.parentSocketConnection,this.x,this.y]);

}
player.prototype.draw = function () {
  var canvas = document.getElementById(String(this.canvas));
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = String(this.color);
  ctx.fillRect(this.x*10,this.y*10,10,10);
}
<|endoftext|>


<commit_before>$(function () {

          var data = [
                    { "Name": "John Smith", "Age": 45 },
                    { "Name": "Mary Johnson", "Age": 32 },
                    { "Name": "Bob Ferguson", "Age": 27 }
              ];

          $("#grid").igGrid({
              dataSource: data //JSON Array defined above
          });
      });
<commit_msg>Update demo.js<commit_after>$(function () {

          var data = [
                    { "Name": "John Smith", "Age": 45 },
                    { "Name": "Mary Johnson", "Age": 32 },
                    { "Name": "Bob Ferguson", "Age": 27 }
              ];
          console.log("creating grid");
          $("#grid").igGrid({
              dataSource: data //JSON Array defined above
          });
      });
<|endoftext|>


<commit_before>/*
 * Simple jQuery Dialog Linker
 * https://github.com/filamentgroup/dialog
 *
 * Copyright (c) 2013 Filament Group, Inc.
 * Author: @scottjehl
 * Licensed under the MIT, GPL licenses.
 */

(function( w, $ ){

	$( w.document )
		// open on matching a[href=#id] click
		.bind( "click", function( e ){

			var $a = $( e.target ).closest( "a" );

			if( $a.length && $a.is( "[data-dialog-link]" ) ){

				$.get( $a.attr( "href" ), function( content ){

					if( $a.is( "[data-dialog-selector]" ) ){

					}

					var id = "dialog-" + new Date().getTime();

					$a
						.attr("href", "#" + id )
						.removeAttr( "data-dialog-link" );

					$( "

" )
							.append( content )
							.appendTo( "body" )
							.dialog()
							.trigger( "dialog-open" );
				});

				e.preventDefault();
			}
		});

}( this, window.jQuery ));
<commit_msg>Adds option to dialog linker to reuse id attribute from link for dialog id.<commit_after>/*
 * Simple jQuery Dialog Linker
 * https://github.com/filamentgroup/dialog
 *
 * Copyright (c) 2013 Filament Group, Inc.
 * Author: @scottjehl
 * Licensed under the MIT, GPL licenses.
 */

(function( w, $ ){

	$( w.document )
		// open on matching a[href=#id] click
		.bind( "click", function( e ){

			var $a = $( e.target ).closest( "a" );

			if( $a.length && $a.is( "[data-dialog-link]" ) ){

				$.get( $a.attr( "href" ), function( content ){

					var id = ( $a.attr( "id" ) + "-dialog" ) ||
						( "dialog-" + new Date().getTime() );

					$a
						.attr("href", "#" + id )
						.removeAttr( "data-dialog-link" );

					$( "

" )
							.append( content )
							.appendTo( "body" )
							.dialog()
							.trigger( "dialog-open" );
				});

				e.preventDefault();
			}
		});

}( this, window.jQuery ));
<|endoftext|>


<commit_before>/*
  nr is the prefix for this function space.
  */
function ddg_spice_xkcd(xk) {
  var img,snippet,link,div;

  // validity check
  if (xk['img'] && xk['alt']) {

    // snippet shown in 0-click
    snippet = d.createElement('span');

    // route image through internal server
    var imgUrl = '/iu/?u='+xk['img'];
    if (nur) img = nur('', xk['alt'], imgUrl);

    if (img) {
      YAHOO.util.Dom.addClass(img,'img_zero_click_big');
      div = d.createElement('div');
      div.appendChild(img);
      snippet.appendChild(div);

      link = d.createElement('a');
      link.href = '/?q=xkcd ' + (parseInt(xk['num']) - 1)
      link.appendChild(d.createTextNode('Prev'));
      snippet.appendChild(link);
      snippet.appendChild(d.createTextNode('\u00a0 \u00a0'));
    }

    items = new Array();
    items[0] = new Array();
    items[0]['a'] = snippet;

    items[0]['h'] = xk['safe_title'];

     // Source name and url for the More at X link.
     items[0]['s'] = 'XKCD';
     items[0]['u'] = 'http://xkcd.com/' + xk['num'];

     // Force no compression.
     items[0]['f'] = 1;

     // The rendering function is nra.
     nra(items);
  }
}<commit_msg>XKCD now w/ cannonical header style `+ " (XKCD)"`<commit_after>/*
  nr is the prefix for this function space.
  */
function ddg_spice_xkcd(xk) {
  var img,snippet,link,div;

  // validity check
  if (xk['img'] && xk['alt']) {

    // snippet shown in 0-click
    snippet = d.createElement('span');

    // route image through internal server
    var imgUrl = '/iu/?u='+xk['img'];
    if (nur) img = nur('', xk['alt'], imgUrl);

    if (img) {
      YAHOO.util.Dom.addClass(img,'img_zero_click_big');
      div = d.createElement('div');
      div.appendChild(img);
      snippet.appendChild(div);

      link = d.createElement('a');
      link.href = '/?q=xkcd ' + (parseInt(xk['num']) - 1)
      link.appendChild(d.createTextNode('Prev'));
      snippet.appendChild(link);
      snippet.appendChild(d.createTextNode('\u00a0 \u00a0'));
    }

    items = new Array();
    items[0] = new Array();
    items[0]['a'] = snippet;

    items[0]['h'] = xk['safe_title'] + ' (XKCD)';

     // Source name and url for the More at X link.
     items[0]['s'] = 'XKCD';
     items[0]['u'] = 'http://xkcd.com/' + xk['num'];

     // Force no compression.
     items[0]['f'] = 1;

     // The rendering function is nra.
     nra(items);
  }
}
<|endoftext|>


<commit_before>// Global UI elements:
//  - log: event log
//  - trans: transcription window

// Global objects:
//  - isConnected: true iff we are connected to a worker
//  - tt: simple structure for managing the list of hypotheses
//  - dictate: dictate object with control methods 'init', 'startListening', ...
//       and event callbacks onResults, onError, ...
var isConnected = false;

var tt = new Transcription();

var dictate = new Dictate({
		server : $("#servers").val().split('|')[0],
		serverStatus : $("#servers").val().split('|')[1],
		recorderWorkerPath : '../lib/recorderWorker.js',
		onReadyForSpeech : function() {
			isConnected = true;
			__message("READY FOR SPEECH");
			$("#buttonToggleListening").html('Stop');
			$("#buttonToggleListening").addClass('highlight');
			$("#buttonToggleListening").prop("disabled", false);
			$("#buttonCancel").prop("disabled", false);
		},
		onEndOfSpeech : function() {
			__message("END OF SPEECH");
			$("#buttonToggleListening").html('Stopping...');
			$("#buttonToggleListening").prop("disabled", true);
		},
		onEndOfSession : function() {
			isConnected = false;
			__message("END OF SESSION");
			$("#buttonToggleListening").html('Start');
			$("#buttonToggleListening").removeClass('highlight');
			$("#buttonToggleListening").prop("disabled", false);
			$("#buttonCancel").prop("disabled", true);
		},
		onServerStatus : function(json) {
			__serverStatus(json.num_workers_available);
			$("#serverStatusBar").toggleClass("highlight", json.num_workers_available == 0);
			// If there are no workers and we are currently not connected
			// then disable the Start/Stop button.
			if (json.num_workers_available == 0 && ! isConnected) {
				$("#buttonToggleListening").prop("disabled", true);
			} else {
				$("#buttonToggleListening").prop("disabled", false);
			}
		},
		onPartialResults : function(hypos) {
			tt.add(hypos[0].transcript, false);
			__updateTranscript(tt.toString());
		},
		onResults : function(hypos) {
			tt.add(hypos[0].transcript, true);
			__updateTranscript(tt.toString());
		},
		onError : function(code, data) {
			dictate.cancel();
			__error(code, data);
			// TODO: show error in the GUI
		},
		onEvent : function(code, data) {
			__message(code, data);
		}
	});

// Private methods (called from the callbacks)
function __message(code, data) {
	log.innerHTML = "msg: " + code + ": " + (data || '') + "\n" + log.innerHTML;
}

function __error(code, data) {
	log.innerHTML = "ERR: " + code + ": " + (data || '') + "\n" + log.innerHTML;
}

function __serverStatus(msg) {
	serverStatusBar.innerHTML = msg;
}

function __updateTranscript(text) {
	$("#trans").val(text);
}

// Public methods (called from the GUI)
function toggleListening() {
	if (isConnected) {
		dictate.stopListening();
	} else {
		dictate.startListening();
	}
}

function cancel() {
	dictate.cancel();
}

function clearTranscription() {
	tt = new Transcription();
	$("#trans").val("");
}

$(document).ready(function() {
	dictate.init();

	$("#servers").change(function() {
		dictate.cancel();
		var servers = $("#servers").val().split('|');
		dictate.setServer(servers[0]);
		dictate.setServerStatus(servers[1]);
	});

});
<commit_msg>Ugly logic to handle spaces and titlecase at the begiining and middle of utterances<commit_after>// Global UI elements:
//  - log: event log
//  - trans: transcription window

// Global objects:
//  - isConnected: true iff we are connected to a worker
//  - tt: simple structure for managing the list of hypotheses
//  - dictate: dictate object with control methods 'init', 'startListening', ...
//       and event callbacks onResults, onError, ...
var isConnected = false;

var tt = new Transcription();

var startPosition = 0;
var endPosition = 0;
var doUpper = false;
var doPrependSpace = true;

function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function prettyfyHyp(text, doCapFirst, doPrependSpace) {
	if (doCapFirst) {
		text = capitaliseFirstLetter(text);
	}
	tokens = text.split(" ");
	text = "";
	if (doPrependSpace) {
		text = " ";
	}
	doCapitalizeNext = false;
	tokens.map(function(token) {
		if (text.trim().length > 0) {
			text = text + " ";
		}
		if (doCapitalizeNext) {
			text = text + capitaliseFirstLetter(token);
		} else {
			text = text + token;
		}
		if (token == "." ||  /\n$/.test(token)) {
			doCapitalizeNext = true;
		} else {
			doCapitalizeNext = false;
		}
	});

	text = text.replace(/ ([,.!?:;])/g,  "\$1");
	text = text.replace(/ ?\n ?/g,  "\n");
	return text;
}

var dictate = new Dictate({
		server : $("#servers").val().split('|')[0],
		serverStatus : $("#servers").val().split('|')[1],
		recorderWorkerPath : '../lib/recorderWorker.js',
		onReadyForSpeech : function() {
			isConnected = true;
			__message("READY FOR SPEECH");
			$("#buttonToggleListening").html('Stop');
			$("#buttonToggleListening").addClass('highlight');
			$("#buttonToggleListening").prop("disabled", false);
			$("#buttonCancel").prop("disabled", false);
			startPosition = $("#trans").prop("selectionStart");
			endPosition = startPosition;
			var textBeforeCaret = $("#trans").val().slice(0, startPosition);
			if ((textBeforeCaret.length == 0) || /\. *$/.test(textBeforeCaret) ||  /\n *$/.test(textBeforeCaret)) {
				doUpper = true;
			} else {
				doUpper = false;
			}
			doPrependSpace = (textBeforeCaret.length > 0) && !(/\n *$/.test(textBeforeCaret));
		},
		onEndOfSpeech : function() {
			__message("END OF SPEECH");
			$("#buttonToggleListening").html('Stopping...');
			$("#buttonToggleListening").prop("disabled", true);
		},
		onEndOfSession : function() {
			isConnected = false;
			__message("END OF SESSION");
			$("#buttonToggleListening").html('Start');
			$("#buttonToggleListening").removeClass('highlight');
			$("#buttonToggleListening").prop("disabled", false);
			$("#buttonCancel").prop("disabled", true);
		},
		onServerStatus : function(json) {
			__serverStatus(json.num_workers_available);
			$("#serverStatusBar").toggleClass("highlight", json.num_workers_available == 0);
			// If there are no workers and we are currently not connected
			// then disable the Start/Stop button.
			if (json.num_workers_available == 0 && ! isConnected) {
				$("#buttonToggleListening").prop("disabled", true);
			} else {
				$("#buttonToggleListening").prop("disabled", false);
			}
		},
		onPartialResults : function(hypos) {
			hypText = prettyfyHyp(hypos[0].transcript, doUpper, doPrependSpace);
			val = $("#trans").val();
			$("#trans").val(val.slice(0, startPosition) + hypText + val.slice(endPosition));
			endPosition = startPosition + hypText.length;
			$("#trans").prop("selectionStart", endPosition);
		},
		onResults : function(hypos) {
			hypText = prettyfyHyp(hypos[0].transcript, doUpper, doPrependSpace);
			val = $("#trans").val();
			$("#trans").val(val.slice(0, startPosition) + hypText + val.slice(endPosition));
			startPosition = startPosition + hypText.length;
			endPosition = startPosition;
			$("#trans").prop("selectionStart", endPosition);
			if (/\. *$/.test(hypText) ||  /\n *$/.test(hypText)) {
				doUpper = true;
			} else {
				doUpper = false;
			}
			doPrependSpace = (hypText.length > 0) && !(/\n *$/.test(hypText));
		},
		onError : function(code, data) {
			dictate.cancel();
			__error(code, data);
			// TODO: show error in the GUI
		},
		onEvent : function(code, data) {
			__message(code, data);
		}
	});

// Private methods (called from the callbacks)
function __message(code, data) {
	log.innerHTML = "msg: " + code + ": " + (data || '') + "\n" + log.innerHTML;
}

function __error(code, data) {
	log.innerHTML = "ERR: " + code + ": " + (data || '') + "\n" + log.innerHTML;
}

function __serverStatus(msg) {
	serverStatusBar.innerHTML = msg;
}

function __updateTranscript(text) {
	$("#trans").val(text);
}

// Public methods (called from the GUI)
function toggleListening() {
	if (isConnected) {
		dictate.stopListening();
	} else {
		dictate.startListening();
	}
}

function cancel() {
	dictate.cancel();
}

function clearTranscription() {
	$("#trans").val("");
	// needed, otherwise selectionStart will retain its old value
	$("#trans").prop("selectionStart", 0);
	$("#trans").prop("selectionEnd", 0);
}

$(document).ready(function() {
	dictate.init();

	$("#servers").change(function() {
		dictate.cancel();
		var servers = $("#servers").val().split('|');
		dictate.setServer(servers[0]);
		dictate.setServerStatus(servers[1]);
	});

});
<|endoftext|>