<commit_before>//
// ShatterPlatePiece.js
//
// Author: Liv Erickson
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
/* globals Entities, SoundCache */

(function(){
    var VELOCITY_TO_BREAK = 2;
    var EMIT_TIME = 2000;
    var breakURL = Script.resolvePath("sound/glass-break.wav");
    var breakSound = SoundCache.getSound(breakURL);
    var volumeLevel = 0.25;
    var canBreak = false;
    var _entityID;

    var PlatePiece = function(){};
    var shouldBreak = function(velocity){
        return Math.abs(velocity.x) >= VELOCITY_TO_BREAK ||
            Math.abs(velocity.y) >= VELOCITY_TO_BREAK ||
            Math.abs(velocity.z) >= VELOCITY_TO_BREAK;
    };

    var createParticles = function(position) {
        var splat = Entities.addEntity({
            "type":"ParticleEffect",
            "position": position,
            "collisionless":1,
            "dynamic":0,
            "name":"Plate Particle Effect",
            "isEmitting":true,
            "lifespan":"0.2",
            "lifetime" : 0.5,
            "maxParticles":"500",
            "textures":"http://hifi-content.s3.amazonaws.com/alan/dev/Particles/Bokeh-Particle.png",
            "emitRate":"145",
            "emitSpeed": 0.05,
            "emitDimensions":{"x":"0.1","y":".1","z":".1"},
            "emitOrientation":{"x":"-90","y":"0","z":"0"},
            "emitterShouldTrail":false,
            "particleRadius":"0.02",
            "radiusSpread":"6",
            "radiusStart":"0.01",
            "radiusFinish":"0",
            "color":{"red":"171","blue":"171","green":"171"},
            "colorSpread":{"red":"0","blue":"0","green":"0"},
            "colorStart":{"red":"255","blue":"255","green":"255"},
            "colorFinish":{"red":"255","blue":"255","green":"255"},
            "emitAcceleration":{"x":"-0.0","y":"2.5","z":"-0.1"},
            "accelerationSpread":{"x":"0.5","y":"3","z":"0.5"},
            "alpha":"1",
            "alphaSpread":"0",
            "alphaStart":"1",
            "alphaFinish":"1",
            "polarStart":"0",
            "polarFinish":"17",
            "azimuthStart":"-180",
            "azimuthFinish":"180"
        }, true);
        Entities.editEntity(_entityID, {visible: false});
        Script.setTimeout(function() {
            Entities.editEntity(splat, { isEmitting: false });
            Entities.deleteEntity(_entityID);
        }, EMIT_TIME);
    };

    PlatePiece.prototype = {
        preload: function(entityID) {
            _entityID = entityID;
        },
        startNearGrab: function() {
            Entities.editEntity(_entityID, {
                visible : true,
                collidesWith: "static,dynamic,kinematic,"
            });
            canBreak = true;
        },
        collisionWithEntity : function(myID, theirID, collision) {
            if (canBreak) {
                var properties = Entities.getEntityProperties(myID, 'velocity', 'position');
                var velocity = properties.velocity;
                var position = properties.position;
                if (shouldBreak(velocity)) {
                    if (breakSound.downloaded) {
                        Audio.playSound(breakSound, {
                            volume: volumeLevel,
                            position: position
                        });
                    }
                    createParticles(position);
                }
            }

        }
    };

    return new PlatePiece();

});
<commit_msg>last CR thing<commit_after>//
// ShatterPlatePiece.js
//
// Author: Liv Erickson
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
/* globals Entities, SoundCache */

(function() {
    var VELOCITY_TO_BREAK = 2;
    var EMIT_TIME = 2000;
    var breakURL = Script.resolvePath("sound/glass-break.wav");
    var breakSound = SoundCache.getSound(breakURL);
    var volumeLevel = 0.25;
    var canBreak = false;
    var _entityID;

    var PlatePiece = function(){};
    var shouldBreak = function(velocity){
        return Math.abs(velocity.x) >= VELOCITY_TO_BREAK ||
            Math.abs(velocity.y) >= VELOCITY_TO_BREAK ||
            Math.abs(velocity.z) >= VELOCITY_TO_BREAK;
    };

    var createParticles = function(position) {
        var splat = Entities.addEntity({
            "type":"ParticleEffect",
            "position": position,
            "collisionless":1,
            "dynamic":0,
            "name":"Plate Particle Effect",
            "isEmitting":true,
            "lifespan":"0.2",
            "lifetime" : 0.5,
            "maxParticles":"500",
            "textures":"http://hifi-content.s3.amazonaws.com/alan/dev/Particles/Bokeh-Particle.png",
            "emitRate":"145",
            "emitSpeed": 0.05,
            "emitDimensions":{"x":"0.1","y":".1","z":".1"},
            "emitOrientation":{"x":"-90","y":"0","z":"0"},
            "emitterShouldTrail":false,
            "particleRadius":"0.02",
            "radiusSpread":"6",
            "radiusStart":"0.01",
            "radiusFinish":"0",
            "color":{"red":"171","blue":"171","green":"171"},
            "colorSpread":{"red":"0","blue":"0","green":"0"},
            "colorStart":{"red":"255","blue":"255","green":"255"},
            "colorFinish":{"red":"255","blue":"255","green":"255"},
            "emitAcceleration":{"x":"-0.0","y":"2.5","z":"-0.1"},
            "accelerationSpread":{"x":"0.5","y":"3","z":"0.5"},
            "alpha":"1",
            "alphaSpread":"0",
            "alphaStart":"1",
            "alphaFinish":"1",
            "polarStart":"0",
            "polarFinish":"17",
            "azimuthStart":"-180",
            "azimuthFinish":"180"
        }, true);
        Entities.editEntity(_entityID, {visible: false});
        Script.setTimeout(function() {
            Entities.editEntity(splat, { isEmitting: false });
            Entities.deleteEntity(_entityID);
        }, EMIT_TIME);
    };

    PlatePiece.prototype = {
        preload: function(entityID) {
            _entityID = entityID;
        },
        startNearGrab: function() {
            Entities.editEntity(_entityID, {
                visible : true,
                collidesWith: "static,dynamic,kinematic,"
            });
            canBreak = true;
        },
        collisionWithEntity : function(myID, theirID, collision) {
            if (canBreak) {
                var properties = Entities.getEntityProperties(myID, 'velocity', 'position');
                var velocity = properties.velocity;
                var position = properties.position;
                if (shouldBreak(velocity)) {
                    if (breakSound.downloaded) {
                        Audio.playSound(breakSound, {
                            volume: volumeLevel,
                            position: position
                        });
                    }
                    createParticles(position);
                }
            }

        }
    };

    return new PlatePiece();

});
<|endoftext|>


<commit_before>/**
 * @module Rendering
 * @submodule Rendering
 * @for p5
 */

'use strict';

var p5 = require('./main');
var constants = require('./constants');

/**
 * Thin wrapper around a renderer, to be used for creating a
 * graphics buffer object. Use this class if you need
 * to draw into an off-screen graphics buffer. The two parameters define the
 * width and height in pixels. The fields and methods for this class are
 * extensive, but mirror the normal drawing API for p5.
 *
 * @class p5.Graphics
 * @extends p5.Element
 * @param {Number} w            width
 * @param {Number} h            height
 * @param {Constant} renderer   the renderer to use, either P2D or WEBGL
 * @param {p5} [pInst]          pointer to p5 instance
 */
p5.Graphics = function(w, h, renderer, pInst) {
  var r = renderer || constants.P2D;

  this.canvas = document.createElement('canvas');
  var node = pInst._userNode || document.body;
  node.appendChild(this.canvas);

  p5.Element.call(this, this.canvas, pInst, false);

  // bind methods and props of p5 to the new object
  for (var p in p5.prototype) {
    if (!this[p]) {
      if (typeof p5.prototype[p] === 'function') {
        this[p] = p5.prototype[p].bind(this);
      } else {
        this[p] = p5.prototype[p];
      }
    }
  }

  p5.prototype._initializeInstanceVariables.apply(this);
  this.width = w;
  this.height = h;
  this._pixelDensity = pInst._pixelDensity;

  if (r === constants.WEBGL) {
    this._renderer = new p5.RendererGL(this.canvas, this, false);
  } else {
    this._renderer = new p5.Renderer2D(this.canvas, this, false);
  }
  pInst._elements.push(this);

  this._renderer.resize(w, h);
  this._renderer._applyDefaults();
  return this;
};

p5.Graphics.prototype = Object.create(p5.Element.prototype);

/**
 * Removes a Graphics object from the page and frees any resources
 * associated with it.
 *
 * @method remove
 *
 * @example
 *

 * let bg;
 * function setup() {
 *   bg = createCanvas(100, 100);
 *   bg.background(0);
 *   image(bg, 0, 0);
 *   bg.remove();
 * }
 *

 *
 *

 * let bg;
 * function setup() {
 *   pixelDensity(1);
 *   createCanvas(100, 100);
 *   stroke(255);
 *   fill(0);
 *
 *   // create and draw the background image
 *   bg = createGraphics(100, 100);
 *   bg.background(200);
 *   bg.ellipse(50, 50, 80, 80);
 * }
 * function draw() {
 *   let t = millis() / 1000;
 *   // draw the background
 *   if (bg) {
 *     image(bg, frameCount % 100, 0);
 *     image(bg, frameCount % 100 - 100, 0);
 *   }
 *   // draw the foreground
 *   let p = p5.Vector.fromAngle(t, 35).add(50, 50);
 *   ellipse(p.x, p.y, 30);
 * }
 * function mouseClicked() {
 *   // remove the background
 *   if (bg) {
 *     bg.remove();
 *     bg = null;
 *   }
 * }
 *

 *
 * @alt
 * no image
 * a multi-colored circle moving back and forth over a scrolling background.
 *
 */
p5.Graphics.prototype.remove = function() {
  if (this.elt.parentNode) {
    this.elt.parentNode.removeChild(this.elt);
  }
  var idx = this._pInst._elements.indexOf(this);
  if (idx !== -1) {
    this._pInst._elements.splice(idx, 1);
  }
  for (var elt_ev in this._events) {
    this.elt.removeEventListener(elt_ev, this._events[elt_ev]);
  }
};

module.exports = p5.Graphics;
<commit_msg>Remove unused parameter in p5.Element constructor in p5.Graphics file<commit_after>/**
 * @module Rendering
 * @submodule Rendering
 * @for p5
 */

'use strict';

var p5 = require('./main');
var constants = require('./constants');

/**
 * Thin wrapper around a renderer, to be used for creating a
 * graphics buffer object. Use this class if you need
 * to draw into an off-screen graphics buffer. The two parameters define the
 * width and height in pixels. The fields and methods for this class are
 * extensive, but mirror the normal drawing API for p5.
 *
 * @class p5.Graphics
 * @extends p5.Element
 * @param {Number} w            width
 * @param {Number} h            height
 * @param {Constant} renderer   the renderer to use, either P2D or WEBGL
 * @param {p5} [pInst]          pointer to p5 instance
 */
p5.Graphics = function(w, h, renderer, pInst) {
  var r = renderer || constants.P2D;

  this.canvas = document.createElement('canvas');
  var node = pInst._userNode || document.body;
  node.appendChild(this.canvas);

  p5.Element.call(this, this.canvas, pInst);

  // bind methods and props of p5 to the new object
  for (var p in p5.prototype) {
    if (!this[p]) {
      if (typeof p5.prototype[p] === 'function') {
        this[p] = p5.prototype[p].bind(this);
      } else {
        this[p] = p5.prototype[p];
      }
    }
  }

  p5.prototype._initializeInstanceVariables.apply(this);
  this.width = w;
  this.height = h;
  this._pixelDensity = pInst._pixelDensity;

  if (r === constants.WEBGL) {
    this._renderer = new p5.RendererGL(this.canvas, this, false);
  } else {
    this._renderer = new p5.Renderer2D(this.canvas, this, false);
  }
  pInst._elements.push(this);

  this._renderer.resize(w, h);
  this._renderer._applyDefaults();
  return this;
};

p5.Graphics.prototype = Object.create(p5.Element.prototype);

/**
 * Removes a Graphics object from the page and frees any resources
 * associated with it.
 *
 * @method remove
 *
 * @example
 *

 * let bg;
 * function setup() {
 *   bg = createCanvas(100, 100);
 *   bg.background(0);
 *   image(bg, 0, 0);
 *   bg.remove();
 * }
 *

 *
 *

 * let bg;
 * function setup() {
 *   pixelDensity(1);
 *   createCanvas(100, 100);
 *   stroke(255);
 *   fill(0);
 *
 *   // create and draw the background image
 *   bg = createGraphics(100, 100);
 *   bg.background(200);
 *   bg.ellipse(50, 50, 80, 80);
 * }
 * function draw() {
 *   let t = millis() / 1000;
 *   // draw the background
 *   if (bg) {
 *     image(bg, frameCount % 100, 0);
 *     image(bg, frameCount % 100 - 100, 0);
 *   }
 *   // draw the foreground
 *   let p = p5.Vector.fromAngle(t, 35).add(50, 50);
 *   ellipse(p.x, p.y, 30);
 * }
 * function mouseClicked() {
 *   // remove the background
 *   if (bg) {
 *     bg.remove();
 *     bg = null;
 *   }
 * }
 *

 *
 * @alt
 * no image
 * a multi-colored circle moving back and forth over a scrolling background.
 *
 */
p5.Graphics.prototype.remove = function() {
  if (this.elt.parentNode) {
    this.elt.parentNode.removeChild(this.elt);
  }
  var idx = this._pInst._elements.indexOf(this);
  if (idx !== -1) {
    this._pInst._elements.splice(idx, 1);
  }
  for (var elt_ev in this._events) {
    this.elt.removeEventListener(elt_ev, this._events[elt_ev]);
  }
};

module.exports = p5.Graphics;
<|endoftext|>


<commit_before>/*globals window, module */

(function () {
    'use strict';

    var functions = {
        quacksLike: quacksLike,
        verifyInstance: verifyInstance,
        isInstance: isInstance,
        verifyObject: verifyObject,
        isObject: isObject,
        verifyArray: verifyArray,
        isArray: isArray,
        verifyFunction: verifyFunction,
        isFunction: isFunction,
        verifyUnemptyString: verifyUnemptyString,
        isUnemptyString:isUnemptyString,
        verifyString: verifyString,
        isString: isString,
        verifyNumber: verifyNumber,
        isNumber: isNumber
    };

    //if (typeof window === 'undefined') {
        module.exports = functions;
    //} else {
    //    window.check = functions;
    //}

    /**
     * Public function `quacksLike`.
     *
     * Tests whether an object 'quacks like a duck'.
     * Returns `true` if the first argument has all of
     * the properties of the second, archetypal argument
     * (the 'duck'). Returns `false` otherwise. If either
     * argument is not an object, an exception is thrown.
     *
     * @param thing {object} The object to test.
     * @param duck {object}  The archetypal object, or 'duck'
     *                       that the test is against.
     */
    function quacksLike (thing, duck) {
        var property;

        verifyObject(thing);
        verifyObject(duck);

        for (property in duck) {
            if (thing.hasOwnProperty(property) === false) {
                return false;
            }

            if (typeof thing[property] !== typeof duck[property]) {
                return false;
            }
        }

        return true;
    }

    /**
     * Public function `verifyInstance`.
     *
     * Throws an exception if an object is not an instance
     * of a prototype.
     *
     * @param thing {object}       The object to test.
     * @param prototype {function} The prototype that the
     *                             test is against.
     * @param [message] {string}   An optional error message
     *                             to set on the thrown Error.
     */
    function verifyInstance (thing, prototype, message) {
        if (isInstance(thing, prototype) === false) {
            throw new Error(message || 'Invalid type');
        }
    }

    /**
     * Public function `isInstance`.
     *
     * Returns `true` if an object is an instance of a prototype,
     * `false` otherwise.
     *
     * @param thing {object}       The object to test.
     * @param prototype {function} The prototype that the
     *                             test is against.
     */
    function isInstance (thing, prototype) {
        if (typeof thing === 'undefined' || thing === null) {
            return false;
        }

        if (isFunction(prototype) && thing instanceof prototype) {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyObject`.
     *
     * Throws an exception unless something is a non-null,
     * non-array object.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyObject (thing, message) {
        if (isObject(thing) === false) {
            throw new Error(message || 'Invalid object');
        }
    }

    /**
     * Public function `isObject`.
     *
     * Returns `true` if something is a non-null, non-array
     * object, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isObject (thing) {
        if (typeof thing === 'object' && thing !== null && isArray(thing) === false) {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyArray`.
     *
     * Throws an exception unless something is an array.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyArray (thing, message) {
        if (isArray(thing) === false) {
            throw new Error(message || 'Invalid array');
        }
    }

    /**
     * Public function `isArray`.
     *
     * Returns `true` something is an array, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isArray (thing) {
        if (Object.prototype.toString.call(thing) === '[object Array]') {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyFunction`.
     *
     * Throws an exception unless something is function.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyFunction (thing, message) {
        if (isFunction(thing) === false) {
            throw new Error(message || 'Invalid function');
        }
    }

    /**
     * Public function `isFunction`.
     *
     * Returns `true` if something is function, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isFunction (thing) {
        if (typeof thing === 'function') {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyUnemptyString`.
     *
     * Throws an exception unless something is a non-empty string.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyUnemptyString (thing, message) {
        if (isUnemptyString(thing) === false) {
            throw new Error(message || 'Invalid string');
        }
    }

    /**
     * Public function `isUnemptyString`.
     *
     * Returns `true` if something is a non-empty string, `false`
     * otherwise.
     *
     * @param thing          The thing to test.
     */
    function isUnemptyString (thing) {
        if (isString(thing) && thing !== '') {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyString`.
     *
     * Throws an exception unless something is a string.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyString (thing, message) {
        if (isString(thing) === false) {
            throw new Error(message || 'Invalid string');
        }
    }

    /**
     * Public function `isString`.
     *
     * Returns `true` if something is a string, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isString (thing) {
        if (typeof thing === 'string') {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyNumber`.
     *
     * Throws an exception unless something is a number (also excluding NaN).
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyNumber (thing, message) {
        if (isNumber(thing) === false) {
            throw new Error(message || 'Invalid number');
        }
    }

    /**
     * Public function `isNumber`.
     *
     * Returns `true` if something a number other than NaN, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isNumber (thing) {
        if (isNaN(thing) === true) {
            return false;
        }

        if (typeof thing === 'number') {
            return true;
        }

        return false;
    }
}());

<commit_msg>Uncomment code.<commit_after>/*globals window, module */

(function () {
    'use strict';

    var functions = {
        quacksLike: quacksLike,
        verifyInstance: verifyInstance,
        isInstance: isInstance,
        verifyObject: verifyObject,
        isObject: isObject,
        verifyArray: verifyArray,
        isArray: isArray,
        verifyFunction: verifyFunction,
        isFunction: isFunction,
        verifyUnemptyString: verifyUnemptyString,
        isUnemptyString:isUnemptyString,
        verifyString: verifyString,
        isString: isString,
        verifyNumber: verifyNumber,
        isNumber: isNumber
    };

    if (typeof window === 'undefined') {
        module.exports = functions;
    } else {
        window.check = functions;
    }

    /**
     * Public function `quacksLike`.
     *
     * Tests whether an object 'quacks like a duck'.
     * Returns `true` if the first argument has all of
     * the properties of the second, archetypal argument
     * (the 'duck'). Returns `false` otherwise. If either
     * argument is not an object, an exception is thrown.
     *
     * @param thing {object} The object to test.
     * @param duck {object}  The archetypal object, or 'duck'
     *                       that the test is against.
     */
    function quacksLike (thing, duck) {
        var property;

        verifyObject(thing);
        verifyObject(duck);

        for (property in duck) {
            if (thing.hasOwnProperty(property) === false) {
                return false;
            }

            if (typeof thing[property] !== typeof duck[property]) {
                return false;
            }
        }

        return true;
    }

    /**
     * Public function `verifyInstance`.
     *
     * Throws an exception if an object is not an instance
     * of a prototype.
     *
     * @param thing {object}       The object to test.
     * @param prototype {function} The prototype that the
     *                             test is against.
     * @param [message] {string}   An optional error message
     *                             to set on the thrown Error.
     */
    function verifyInstance (thing, prototype, message) {
        if (isInstance(thing, prototype) === false) {
            throw new Error(message || 'Invalid type');
        }
    }

    /**
     * Public function `isInstance`.
     *
     * Returns `true` if an object is an instance of a prototype,
     * `false` otherwise.
     *
     * @param thing {object}       The object to test.
     * @param prototype {function} The prototype that the
     *                             test is against.
     */
    function isInstance (thing, prototype) {
        if (typeof thing === 'undefined' || thing === null) {
            return false;
        }

        if (isFunction(prototype) && thing instanceof prototype) {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyObject`.
     *
     * Throws an exception unless something is a non-null,
     * non-array object.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyObject (thing, message) {
        if (isObject(thing) === false) {
            throw new Error(message || 'Invalid object');
        }
    }

    /**
     * Public function `isObject`.
     *
     * Returns `true` if something is a non-null, non-array
     * object, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isObject (thing) {
        if (typeof thing === 'object' && thing !== null && isArray(thing) === false) {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyArray`.
     *
     * Throws an exception unless something is an array.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyArray (thing, message) {
        if (isArray(thing) === false) {
            throw new Error(message || 'Invalid array');
        }
    }

    /**
     * Public function `isArray`.
     *
     * Returns `true` something is an array, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isArray (thing) {
        if (Object.prototype.toString.call(thing) === '[object Array]') {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyFunction`.
     *
     * Throws an exception unless something is function.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyFunction (thing, message) {
        if (isFunction(thing) === false) {
            throw new Error(message || 'Invalid function');
        }
    }

    /**
     * Public function `isFunction`.
     *
     * Returns `true` if something is function, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isFunction (thing) {
        if (typeof thing === 'function') {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyUnemptyString`.
     *
     * Throws an exception unless something is a non-empty string.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyUnemptyString (thing, message) {
        if (isUnemptyString(thing) === false) {
            throw new Error(message || 'Invalid string');
        }
    }

    /**
     * Public function `isUnemptyString`.
     *
     * Returns `true` if something is a non-empty string, `false`
     * otherwise.
     *
     * @param thing          The thing to test.
     */
    function isUnemptyString (thing) {
        if (isString(thing) && thing !== '') {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyString`.
     *
     * Throws an exception unless something is a string.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyString (thing, message) {
        if (isString(thing) === false) {
            throw new Error(message || 'Invalid string');
        }
    }

    /**
     * Public function `isString`.
     *
     * Returns `true` if something is a string, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isString (thing) {
        if (typeof thing === 'string') {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyNumber`.
     *
     * Throws an exception unless something is a number (also excluding NaN).
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyNumber (thing, message) {
        if (isNumber(thing) === false) {
            throw new Error(message || 'Invalid number');
        }
    }

    /**
     * Public function `isNumber`.
     *
     * Returns `true` if something a number other than NaN, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isNumber (thing) {
        if (isNaN(thing) === true) {
            return false;
        }

        if (typeof thing === 'number') {
            return true;
        }

        return false;
    }
}());

<|endoftext|>


<commit_before>(function (jui, _tools) {
	var root = document.querySelector('body');
	var parseHeadCallback = null, submitCallback = null;
	var customSingleLineElements = [], customElements = [];

	var lastLoaded = window.location.href;

	var sendElements = [];
	var beforeParseCallback = null;

	var headers = null;

	jui.views = {};
	jui.padding;
	jui.paddingLeft;

	jui.init = function(pRoot) {
		if(pRoot === null || pRoot === undefined) {
			root = document.querySelector('body');
		} else {
			root = pRoot;
		}
	};

	jui.clean = function() {
		root.innerHTML = '';
		root.style.padding = jui.padding;
		root.style.paddingLeft = jui.paddingLeft;
		root.style.marginTop = 0;

		window.jui.ui.datePicker.abort();

		document.querySelector('body').style.backgroundColor = 'transparent';
	};

	jui.parse = function(jsonObject, parentElement, allElements) {

		if(_tools.isString(jsonObject)) {
			jsonObject = _tools.parseJuiJSON(jsonObject);
		}

		if(!_tools.empty(beforeParseCallback) && _tools.isFunction(beforeParseCallback)) {
			var returnedBool = beforeParseCallback(jsonObject, parentElement);
		}

		if(!_tools.isBoolean(returnedBool) || returnedBool) {
			if(jsonObject['head'] !== null && jsonObject['head'] !== undefined) {
				parseHead(jsonObject['head']);
				var data = jsonObject['data'];
			} else if( !_tools.empty(jsonObject['data']) ) {
				var data = jsonObject['data'];
			} else {
				var data = jsonObject;
			}

			var fragment = document.createDocumentFragment();

			if(!_tools.empty(data)) {
				sendElements = [];

				for(var i = 0, x = data.length; i < x; i++) {
					var el = parseElement(data[i], allElements);

					if(!_tools.empty(el)) {
						el = el.getDomElement();
					}

					if(!_tools.empty(el)) {
						if(data[i]['id'] !== null && data[i]['id'] !== undefined) {
							el.id = data[i]['id'];
						}

						fragment.appendChild(el);
					}
				}
			}

			if(parentElement === true) {
				return fragment;
			} else if(!_tools.empty(parentElement)) {
				parentElement.appendChild(fragment);
			} else {
				this.clean();
				root.appendChild(fragment);
			}
		}
	}

	jui.setHeadCallback = function(callback) {
		if(!_tools.empty(callback) && _tools.isFunction(callback)) {
			parseHeadCallback = callback;
		}
	};

	jui.setSubmitCallback = function(callback) {
		if(!_tools.empty(callback) && _tools.isFunction(callback)) {
			submitCallback = callback;
		}
	};

	jui.registerSubmitElement = function (name, element) {
		sendElements.push({
			name: name,
			element: element
		})
	}

	jui.addOnBeforeParseListener = function(callback) {
		if(!_tools.empty(callback) && _tools.isFunction(callback)) {
			beforeParseCallback = callback;
		}
	}

	jui.registerCustomSingleLineElement = function (type, constructClass, shType) {
		if(_tools.empty(shType)) shType = type;

		customSingleLineElements.push({
			type: type,
			construct: constructClass,
			shType: shType
		})
	}

	jui.registerCustomElement = function (type, constructClass, shType) {
		if(_tools.empty(shType)) shType = type;

		customElements.push({
			type: type,
			construct: constructClass,
			shType: shType
		})
	}

	var parseHead = function(jsonObject) {
		if (jsonObject['bgcolor'] != null) {
			document.querySelector('body').style.backgroundColor = jsonObject['bgcolor'];
		}

		if(parseHeadCallback !== null) {
			parseHeadCallback(jsonObject);
		}
	}

	var parseElement = function(jsonObject, allElements) {
		if(_tools.empty(allElements)) allElements = true;

		if(_tools.empty(jsonObject)) return null;
		if(jsonObject['type'] === null) return null;

		var el = parseSingleLineElements(jsonObject);

		if(allElements) {
			if(jsonObject['type'] == 'list') {
				el = new window.jui.views.list(jsonObject);
			} else if(jsonObject['type'] == 'table') {
				el = new window.jui.views.table(jsonObject, this);
			} else if(jsonObject['type'] == 'frame') {
				el = new window.jui.views.frame(jsonObject);
			} else if(jsonObject['type'] == 'range') { /* TODO */
				el = new window.jui.views.range(jsonObject);
			} else if(jsonObject['type'] == 'container') {
				el = new window.jui.views.container(jsonObject);
			} else if(jsonObject['type'] == 'select') {
				el = new window.jui.views.select(jsonObject);
			} else if(!_tools.empty(customElements)) {
				for(var i = 0, x = customElements.length; i < x; i++) {
					var customElement = customElements[i];

					if(customElement.type.toLowerCase() == jsonObject['type'].toLowerCase() ||
						customElement.shType.toLowerCase() == jsonObject['type'].toLowerCase()) {

						el = new customElement.construct(jsonObject);

						if(!_tools.empty(el)) {
							return el;
						}
					}
				}
			}

		}

		return el;
	}

	var parseSingleLineElements = function(jsonObject) {
		var el = null;

		if(jsonObject['type'] == 'text') {
			el = new window.jui.views.text(jsonObject);
		} else if(jsonObject['type'] == 'heading') {
			el = new window.jui.views.heading(jsonObject);
		} else if(jsonObject['type'] == 'input') {
			el = new window.jui.views.input(jsonObject);
		} else if(jsonObject['type'] == 'button') {
			el = new window.jui.views.button(jsonObject);
		} else if(jsonObject['type'] == 'checkbox') {
			el = new window.jui.views.checkbox(jsonObject);
		} else if(jsonObject['type'] == 'nl') {
			el = new window.jui.views.newline();
		} else if(jsonObject['type'] == 'hline') {
			el = new window.jui.views.horizontalline();
		} else if(jsonObject['type'] == 'file') {
			el = new window.jui.views.file(jsonObject);
		} else if(jsonObject['type'] == 'image') {
			el = new window.jui.views.image(jsonObject);
		} else if(jsonObject['type'] == 'link') {
			el = new window.jui.views.link(jsonObject);
		} else if(!_tools.empty(customSingleLineElements)) {
			for(var i = 0, x = customSingleLineElements.length; i < x; i++) {
				var customSingleLineElement = customSingleLineElements[i];

				if(customSingleLineElement.type.toLowerCase() == jsonObject['type'].toLowerCase() ||
					customSingleLineElement.shType.toLowerCase() == jsonObject['type'].toLowerCase()) {

					el = new customSingleLineElement.construct(jsonObject);

					if(!_tools.empty(el)) {
						return el;
					}
				}
			}
		}

		return el;
	};

	jui.requestParse = function(url, data, pHeaders, callback) {
		if(!_tools.empty(pHeaders)) {
			pHeaders = headers;
		}

		window.jui.tools.requestSite(url, null, pHeaders, function(content, status) {
			if(status === 200) {
				var tmpContent = window.jui.tools.parseJuiJSON(content);
				window.jui.parse(tmpContent);

				lastLoaded = url;
			}

			if(!_tools.empty(callback) && _tools.isFunction(callback)) {
				callback.call(window, content, status);
			}
		});
	}

	jui.setDefaultHeaders = function(pHeaders) {
		headers = pHeaders
	};

	jui.getSubmitElements = function() {
		return sendElements;
	};

	jui.getHeaders = function() {
		return headers;
	}

	jui.submit = function(url) {
		var formData = new FormData();

		for(var i = 0, x = sendElements.length; i < x; i++) {

			var name = sendElements[i].name;
			var element = sendElements[i].element;
			var tagName = element.tagName;

			if(tagName && tagName.toLowerCase() == "input" &&
				 		(element.type.toLowerCase() == "text" ||
						 element.type.toLowerCase() == "password" ||
						 element.type.toLowerCase() == "number" ||
						 element.type.toLowerCase() == "range" ||
						 element.type.toLowerCase() == "color" ||
						 element.type.toLowerCase() == "date")) {

				if(!_tools.empty(element.value)) {
					formData.append(name, element.value);
				}
			} else if(tagName && tagName.toLowerCase() == "select") {
				console.log("Hi");
			} else if(tagName && tagName.toLowerCase() == "input" &&
				 		element.type.toLowerCase() == "checkbox") {

				if(element.checked) formData.append(name, 1);
			} else if(tagName && tagName.toLowerCase() == "input" &&
				 		element.type.toLowerCase() == "file") {

				for(var j = 0, k = element.files.length; j < k; j++) {
					formData.append(name + '[]', element.files[j]);
				}
			} else if(tagName && tagName.toLowerCase() == "textarea") {
				if(!_tools.empty(element.value)) {
					formData.append(name, element.value);
				}
			} else if(element.classList.contains('dateButton') && element.dataset != undefined) {
				formData.append(name, element.dataset.value || '0');
			} else if(element.classList.contains('.editor') && element.querySelector('.html') != null) {
				if(!_tools.empty(element.querySelector('.html').innerHTML)) {
					formData.append(name, element.querySelector('.html').innerHTML);
				}
			} else {
				if(!_tools.empty(submitCallback)) {
					submitCallback(formData, name, element);
				}
			}

		}

		window.jui.tools.requestSite(lastLoaded, formData, headers, function(content, status) {
			if(status === 200) {
				content = JSON.parse(content);
				window.jui.parse(content);

				if(!_tools.empty(url))
					lastLoaded = url;
			}
		});
	};
})(window.jui, window.jui.tools);
<commit_msg>Rermoved Editor (custom component) from Jui.submit<commit_after>(function (jui, _tools) {
	var root = document.querySelector('body');
	var parseHeadCallback = null, submitCallback = null;
	var customSingleLineElements = [], customElements = [];

	var lastLoaded = window.location.href;

	var sendElements = [];
	var beforeParseCallback = null;

	var headers = null;

	jui.views = {};
	jui.padding;
	jui.paddingLeft;

	jui.init = function(pRoot) {
		if(pRoot === null || pRoot === undefined) {
			root = document.querySelector('body');
		} else {
			root = pRoot;
		}
	};

	jui.clean = function() {
		root.innerHTML = '';
		root.style.padding = jui.padding;
		root.style.paddingLeft = jui.paddingLeft;
		root.style.marginTop = 0;

		window.jui.ui.datePicker.abort();

		document.querySelector('body').style.backgroundColor = 'transparent';
	};

	jui.parse = function(jsonObject, parentElement, allElements) {

		if(_tools.isString(jsonObject)) {
			jsonObject = _tools.parseJuiJSON(jsonObject);
		}

		if(!_tools.empty(beforeParseCallback) && _tools.isFunction(beforeParseCallback)) {
			var returnedBool = beforeParseCallback(jsonObject, parentElement);
		}

		if(!_tools.isBoolean(returnedBool) || returnedBool) {
			if(jsonObject['head'] !== null && jsonObject['head'] !== undefined) {
				parseHead(jsonObject['head']);
				var data = jsonObject['data'];
			} else if( !_tools.empty(jsonObject['data']) ) {
				var data = jsonObject['data'];
			} else {
				var data = jsonObject;
			}

			var fragment = document.createDocumentFragment();

			if(!_tools.empty(data)) {
				sendElements = [];

				for(var i = 0, x = data.length; i < x; i++) {
					var el = parseElement(data[i], allElements);

					if(!_tools.empty(el)) {
						el = el.getDomElement();
					}

					if(!_tools.empty(el)) {
						if(data[i]['id'] !== null && data[i]['id'] !== undefined) {
							el.id = data[i]['id'];
						}

						fragment.appendChild(el);
					}
				}
			}

			if(parentElement === true) {
				return fragment;
			} else if(!_tools.empty(parentElement)) {
				parentElement.appendChild(fragment);
			} else {
				this.clean();
				root.appendChild(fragment);
			}
		}
	}

	jui.setHeadCallback = function(callback) {
		if(!_tools.empty(callback) && _tools.isFunction(callback)) {
			parseHeadCallback = callback;
		}
	};

	jui.setSubmitCallback = function(callback) {
		if(!_tools.empty(callback) && _tools.isFunction(callback)) {
			submitCallback = callback;
		}
	};

	jui.registerSubmitElement = function (name, element) {
		sendElements.push({
			name: name,
			element: element
		})
	}

	jui.addOnBeforeParseListener = function(callback) {
		if(!_tools.empty(callback) && _tools.isFunction(callback)) {
			beforeParseCallback = callback;
		}
	}

	jui.registerCustomSingleLineElement = function (type, constructClass, shType) {
		if(_tools.empty(shType)) shType = type;

		customSingleLineElements.push({
			type: type,
			construct: constructClass,
			shType: shType
		})
	}

	jui.registerCustomElement = function (type, constructClass, shType) {
		if(_tools.empty(shType)) shType = type;

		customElements.push({
			type: type,
			construct: constructClass,
			shType: shType
		})
	}

	var parseHead = function(jsonObject) {
		if (jsonObject['bgcolor'] != null) {
			document.querySelector('body').style.backgroundColor = jsonObject['bgcolor'];
		}

		if(parseHeadCallback !== null) {
			parseHeadCallback(jsonObject);
		}
	}

	var parseElement = function(jsonObject, allElements) {
		if(_tools.empty(allElements)) allElements = true;

		if(_tools.empty(jsonObject)) return null;
		if(jsonObject['type'] === null) return null;

		var el = parseSingleLineElements(jsonObject);

		if(allElements) {
			if(jsonObject['type'] == 'list') {
				el = new window.jui.views.list(jsonObject);
			} else if(jsonObject['type'] == 'table') {
				el = new window.jui.views.table(jsonObject, this);
			} else if(jsonObject['type'] == 'frame') {
				el = new window.jui.views.frame(jsonObject);
			} else if(jsonObject['type'] == 'range') { /* TODO */
				el = new window.jui.views.range(jsonObject);
			} else if(jsonObject['type'] == 'container') {
				el = new window.jui.views.container(jsonObject);
			} else if(jsonObject['type'] == 'select') {
				el = new window.jui.views.select(jsonObject);
			} else if(!_tools.empty(customElements)) {
				for(var i = 0, x = customElements.length; i < x; i++) {
					var customElement = customElements[i];

					if(customElement.type.toLowerCase() == jsonObject['type'].toLowerCase() ||
						customElement.shType.toLowerCase() == jsonObject['type'].toLowerCase()) {

						el = new customElement.construct(jsonObject);

						if(!_tools.empty(el)) {
							return el;
						}
					}
				}
			}

		}

		return el;
	}

	var parseSingleLineElements = function(jsonObject) {
		var el = null;

		if(jsonObject['type'] == 'text') {
			el = new window.jui.views.text(jsonObject);
		} else if(jsonObject['type'] == 'heading') {
			el = new window.jui.views.heading(jsonObject);
		} else if(jsonObject['type'] == 'input') {
			el = new window.jui.views.input(jsonObject);
		} else if(jsonObject['type'] == 'button') {
			el = new window.jui.views.button(jsonObject);
		} else if(jsonObject['type'] == 'checkbox') {
			el = new window.jui.views.checkbox(jsonObject);
		} else if(jsonObject['type'] == 'nl') {
			el = new window.jui.views.newline();
		} else if(jsonObject['type'] == 'hline') {
			el = new window.jui.views.horizontalline();
		} else if(jsonObject['type'] == 'file') {
			el = new window.jui.views.file(jsonObject);
		} else if(jsonObject['type'] == 'image') {
			el = new window.jui.views.image(jsonObject);
		} else if(jsonObject['type'] == 'link') {
			el = new window.jui.views.link(jsonObject);
		} else if(!_tools.empty(customSingleLineElements)) {
			for(var i = 0, x = customSingleLineElements.length; i < x; i++) {
				var customSingleLineElement = customSingleLineElements[i];

				if(customSingleLineElement.type.toLowerCase() == jsonObject['type'].toLowerCase() ||
					customSingleLineElement.shType.toLowerCase() == jsonObject['type'].toLowerCase()) {

					el = new customSingleLineElement.construct(jsonObject);

					if(!_tools.empty(el)) {
						return el;
					}
				}
			}
		}

		return el;
	};

	jui.requestParse = function(url, data, pHeaders, callback) {
		if(!_tools.empty(pHeaders)) {
			pHeaders = headers;
		}

		window.jui.tools.requestSite(url, null, pHeaders, function(content, status) {
			if(status === 200) {
				var tmpContent = window.jui.tools.parseJuiJSON(content);
				window.jui.parse(tmpContent);

				lastLoaded = url;
			}

			if(!_tools.empty(callback) && _tools.isFunction(callback)) {
				callback.call(window, content, status);
			}
		});
	}

	jui.setDefaultHeaders = function(pHeaders) {
		headers = pHeaders
	};

	jui.getSubmitElements = function() {
		return sendElements;
	};

	jui.getHeaders = function() {
		return headers;
	}

	jui.submit = function(url) {
		var formData = new FormData();

		for(var i = 0, x = sendElements.length; i < x; i++) {

			var name = sendElements[i].name;
			var element = sendElements[i].element;
			var tagName = element.tagName;

			if(tagName && tagName.toLowerCase() == "input" &&
				 		(element.type.toLowerCase() == "text" ||
						 element.type.toLowerCase() == "password" ||
						 element.type.toLowerCase() == "number" ||
						 element.type.toLowerCase() == "range" ||
						 element.type.toLowerCase() == "color" ||
						 element.type.toLowerCase() == "date")) {

				if(!_tools.empty(element.value)) {
					formData.append(name, element.value);
				}
			} else if(tagName && tagName.toLowerCase() == "select") {
				console.log("Hi");
			} else if(tagName && tagName.toLowerCase() == "input" &&
				 		element.type.toLowerCase() == "checkbox") {

				if(element.checked) formData.append(name, 1);
			} else if(tagName && tagName.toLowerCase() == "input" &&
				 		element.type.toLowerCase() == "file") {

				for(var j = 0, k = element.files.length; j < k; j++) {
					formData.append(name + '[]', element.files[j]);
				}
			} else if(tagName && tagName.toLowerCase() == "textarea") {
				if(!_tools.empty(element.value)) {
					formData.append(name, element.value);
				}
			} else if(element.classList.contains('dateButton') && element.dataset != undefined) {
				formData.append(name, element.dataset.value || '0');
			} else {
				if(!_tools.empty(submitCallback)) {
					submitCallback(formData, name, element);
				}
			}

		}

		window.jui.tools.requestSite(lastLoaded, formData, headers, function(content, status) {
			if(status === 200) {
				content = JSON.parse(content);
				window.jui.parse(content);

				if(!_tools.empty(url))
					lastLoaded = url;
			}
		});
	};
})(window.jui, window.jui.tools);
<|endoftext|>


<commit_before>var inno = new IframeHelper();

var App = function (config) {
    this.eTpl = "
{0}

{2}

";

    this.eCont      = config.eventContainer;
    this.eHeader    = config.eventHeader;
    this.pCont      = config.profileContainer;

    this.cache = "";
    this.settings = {};
};

App.prototype = {
    updateView: function (data) {
        var self = this;

        try {
            data = JSON.parse(data);
        } catch (e) {
            data = {};
        }

        if (!data.data) {
            return false;
        } else {
            data = data.data;
        }

        if (data.events) {
            var max = 0,
                tpl = "";

            data.events.forEach(function (event) {
                max += event.count;
            });

            data.events.forEach(function (event) {
                var prc = Math.round((event.count / max) * 100), xTpl,
                    text = "";

                xTpl = self.eTpl.replace(/\{0\}/g, "Event defenition: " + event.event_id);
                xTpl = xTpl.replace(/\{1\}/g, prc);

                text = self.settings.ev_prc ? prc + "%" : "";
                text += self.settings.ev_count ? " [" + event.count + "]" : "";

                xTpl = xTpl.replace(/\{2\}/g, text);

                tpl += xTpl;
            });

            if (max > 0) {
                this.eHeader.textContent = "All events: " + max;
                this.eCont.innerHTML = tpl;
            } else {
                this.eCont.textContent = "No data";
            }

        }

        if (data.profiles) {
            var max = 0,
                tpl = "";

            data.profiles.forEach(function (profile) {
                max += profile.count;
            });

            data.profiles.forEach(function (profile) {
                var prc = Math.round((profile.count / max) * 100), xTpl,
                    text = "";
                xTpl = self.eTpl.replace(/\{0\}/g, "Profile: " + profile.profile_id);
                xTpl = xTpl.replace(/\{1\}/g, prc);

                text = self.settings.ev_prc ? prc + "%" : "";
                text += self.settings.ev_count ? " [" + profile.count + "]" : "";

                xTpl = xTpl.replace(/\{2\}/g, text);

                tpl += xTpl;
            });

            if (max > 0) {
                this.pCont.innerHTML = tpl;
            } else {
                this.pCont.textContent = "No data";
            }

        }
    },

    initData: function () {
        var color = "";

        switch (this.settings.ev_color) {
            case "green"    : color = "progress-bar-success"; break;
            case "orange"   : color = "progress-bar-warning"; break;
            case "red"      : color = "progress-bar-danger"; break;
        }

        this.eTpl = this.eTpl.replace(/\{color\}/g, color);
    },

    requestData: function () {
        var url  = inno.getCurrentApp().url,
            self = this;

        var request = new XMLHttpRequest();

        request.open("GET", url + "/statistics", true);
        request.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                var text = this.responseText;
                if (text !== self.cache) {
                    self.cache = text;
                    self.updateView(text);
                }
            }
        }

        request.send(null);
    },

    requestSettings: function (callback) {
        var self = this;
        inno.getProperties(function (status, data) {
            if (status) {
                self.settings = data;
                callback(data);
            } else {
                throw Error("Error requesting data");
            }
        });
    },

    start: function (callback) {
        var self = this;

        this.requestSettings(function () {
            self.initData();
            self.requestData();
            self.updateInterval = window.setInterval(self.requestData.bind(self), 10000);
        });
    },

    clear: function () {
        if (this.updateInterval) {
            window.clearInterval(this.updateInterval);
        }
    }
}

document.addEventListener("DOMContentLoaded", function () {
    var config = {
        eventContainer      : document.getElementById("eventDef"),
        eventHeader         : document.getElementById("header-eds-all"),
        profileContainer    : document.getElementById("profiles")
    };

    var app = new App(config);

    inno.onReady(function () {
        app.start();
    });

    window.onbeforeunload = function () {
        app.clear();
    };
});<commit_msg>fix beanstalk with url<commit_after>var inno = new IframeHelper();

var App = function (config) {
    this.eTpl = "
{0}

{2}

";

    this.eCont      = config.eventContainer;
    this.eHeader    = config.eventHeader;
    this.pCont      = config.profileContainer;

    this.cache = "";
    this.settings = {};
};

App.prototype = {
    updateView: function (data) {
        var self = this;

        try {
            data = JSON.parse(data);
        } catch (e) {
            data = {};
        }

        if (!data.data) {
            return false;
        } else {
            data = data.data;
        }

        if (data.events) {
            var max = 0,
                tpl = "";

            data.events.forEach(function (event) {
                max += event.count;
            });

            data.events.forEach(function (event) {
                var prc = Math.round((event.count / max) * 100), xTpl,
                    text = "";

                xTpl = self.eTpl.replace(/\{0\}/g, "Event defenition: " + event.event_id);
                xTpl = xTpl.replace(/\{1\}/g, prc);

                text = self.settings.ev_prc ? prc + "%" : "";
                text += self.settings.ev_count ? " [" + event.count + "]" : "";

                xTpl = xTpl.replace(/\{2\}/g, text);

                tpl += xTpl;
            });

            if (max > 0) {
                this.eHeader.textContent = "All events: " + max;
                this.eCont.innerHTML = tpl;
            } else {
                this.eCont.textContent = "No data";
            }

        }

        if (data.profiles) {
            var max = 0,
                tpl = "";

            data.profiles.forEach(function (profile) {
                max += profile.count;
            });

            data.profiles.forEach(function (profile) {
                var prc = Math.round((profile.count / max) * 100), xTpl,
                    text = "";
                xTpl = self.eTpl.replace(/\{0\}/g, "Profile: " + profile.profile_id);
                xTpl = xTpl.replace(/\{1\}/g, prc);

                text = self.settings.ev_prc ? prc + "%" : "";
                text += self.settings.ev_count ? " [" + profile.count + "]" : "";

                xTpl = xTpl.replace(/\{2\}/g, text);

                tpl += xTpl;
            });

            if (max > 0) {
                this.pCont.innerHTML = tpl;
            } else {
                this.pCont.textContent = "No data";
            }

        }
    },

    initData: function () {
        var color = "";

        switch (this.settings.ev_color) {
            case "green"    : color = "progress-bar-success"; break;
            case "orange"   : color = "progress-bar-warning"; break;
            case "red"      : color = "progress-bar-danger"; break;
        }

        this.eTpl = this.eTpl.replace(/\{color\}/g, color);
    },

    requestData: function () {
        var url  = inno.getCurrentApp().url,
            self = this;

        var request = new XMLHttpRequest();

        request.open("GET", url + "statistics", true);
        request.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                var text = this.responseText;
                if (text !== self.cache) {
                    self.cache = text;
                    self.updateView(text);
                }
            }
        }

        request.send(null);
    },

    requestSettings: function (callback) {
        var self = this;
        inno.getProperties(function (status, data) {
            if (status) {
                self.settings = data;
                callback(data);
            } else {
                throw Error("Error requesting data");
            }
        });
    },

    start: function (callback) {
        var self = this;

        this.requestSettings(function () {
            self.initData();
            self.requestData();
            self.updateInterval = window.setInterval(self.requestData.bind(self), 10000);
        });
    },

    clear: function () {
        if (this.updateInterval) {
            window.clearInterval(this.updateInterval);
        }
    }
}

document.addEventListener("DOMContentLoaded", function () {
    var config = {
        eventContainer      : document.getElementById("eventDef"),
        eventHeader         : document.getElementById("header-eds-all"),
        profileContainer    : document.getElementById("profiles")
    };

    var app = new App(config);

    inno.onReady(function () {
        app.start();
    });

    window.onbeforeunload = function () {
        app.clear();
    };
});<|endoftext|>


<commit_before>/*:
*
 * @plugindesc KR_Drag_Window
 * @author Kleberson Romero (GS_TEAM)
 * @version 2.0
 * @help
 * Esse plugin adiciona um metodo de arrasto de janela drag and move.
 * Log Versão 2.0
 *
 * Adicionado função de fechamento de janela.
 * Adicionado Sons de fechamento ou não da janela.
 * Corrigido Bug da Area.
 * Alguns bug's de posicionamento corrigidos.
 *
 * Log Versão 1.0
 *
 * Criado as funções de arrasto da janela.
 *
 */

  //=======================================================================//
 //  ** Metodo Alias do Window_Base.initialize                            //
//=======================================================================//
var alias_Window_Base_initialize_drag = Window_Base.prototype.initialize;
Window_Base.prototype.initialize = function(x, y, width, height) {
    alias_Window_Base_initialize_drag.call(this);
    Window.prototype.initialize.call(this);
    this.loadWindowskin();
    this.move(x, y, width, height);
    this.createContents();
    this.draggable = true;
    this.closeable = true;
    this.widgets = [];
    this.max_X = Graphics.width - this.width;
    this.max_Y = Graphics.height - this.height;
};
  //=======================================================================//
 //  ** Metodo Alias do Window_Base.update                                //
//=======================================================================//
var alias_Window_Base_update_drag = Window_Base.prototype.update;
Window_Base.prototype.update = function() {
    alias_Window_Base_update_drag.call(this,arguments);
    this.update_drag_move();
    this.on_close();
};
  //=======================================================================//
 //  ** Metodo Alias do Window_Base.on_close                              //
//=======================================================================//
Window_Base.prototype.on_close = function(){
if (TouchInput.isTriggered()){
      if (this.in_area(this.width-16,0,16,16)){
       if (this.closeable){
       	SoundManager.playOk();
       	this.hide();
       }else{
       	SoundManager.playBuzzer();
       }
      }
    }
};
  //=======================================================================//
 //  ** Metodo de atualização drag_move Window_Base                       //
//=======================================================================//
Window_Base.prototype.update_drag_move = function() {
    this.check_dragability();
    if(this.in_draging)
        this.update_in_drag();
};
  //=======================================================================//
 //  ** Metodo de verificação de arrasto na area(grid) Window_Base        //
//=======================================================================//
Window_Base.prototype.check_dragability = function() {
    if(TouchInput.isPressed()){
        if(this.can_drag()) {  // Verifica se é possivel arrastar a janela
            if (this.in_area(0,0,this.width-16,16) == true){ // se estiver na area de arrasto
            	this.in_drag();          // arrasta a janela
            }
        }
    } else {
        if(this.in_draging)
           this.drag_cancel();         // Cancela o arrasto
    }
};
  //=======================================================================//
 //  ** Metodo de verificação se janela é arrastevel Window_Base          //
//=======================================================================//
Window_Base.prototype.can_drag = function() {
	if (this.draggable){
    	return true
	}else{
   		return false
   	}
};
  //=======================================================================//
 //  ** Metodo de verificação se está dentro a área da janela             //
//=======================================================================//
Window_Base.prototype.in_area = function(x,y,width,height) {
    var tx = TouchInput.x;
    var ty = TouchInput.y;
    if(tx >= this.x+x && tx <= (this.x+this.width) && ty >= this.y+y && ty <= (this.y+height)) {
      	return true
    }else{
    	return false
    }
};
  //=======================================================================//
 //  ** Metodo de verificação está arrastando?                            //
//=======================================================================//
Window_Base.prototype.in_drag = function() {
    this.in_draging = true;
    this.ini_pos_drag = [this.x,this.y];
    this.ini_pos_touch_drag = [TouchInput.x,TouchInput.y];
    this.backOpacity = 120;
};
  //=======================================================================//
 //  ** Metodo de cancelamento do arrasto                                 //
//=======================================================================//
Window_Base.prototype.drag_cancel = function() {
    this.in_draging = false;
    this.update_pos_grid();
    this.backOpacity = 200;

};
  //=======================================================================//
 //  ** Metodo de Atualização da posição do arrasto                       //
//=======================================================================//
Window_Base.prototype.update_in_drag = function() {
    var difX = TouchInput.x - this.ini_pos_touch_drag[0];
    var difY = TouchInput.y - this.ini_pos_touch_drag[1];
    this.x = this.ini_pos_drag[0] + difX;
    this.y = this.ini_pos_drag[1] + difY;
};
  //==========================================================================//
 //  ** Metodo de Atualização da posição do arrasto dentro da area do grafico //
//===========================================================================//
Window_Base.prototype.update_pos_grid = function() {
    if (this.x > this.max_X){
    	return this.x = this.max_X;
    }else if (this.x < 0) {
    	return this.x = 0;
    }
    if (this.y > this.max_Y){
    	return this.y = this.max_Y;
    }else if (this.y < 0) {
		return this.y = 0;
    }
};
<commit_msg>Update KR_Drag_Window.js<commit_after>/*:
*
 * @plugindesc KR_Drag_Window
 * @author Kleberson Romero (GS_TEAM)
 * @version 2.2
 *
 * @param Dragable
 * @desc true/false para Ativar ou Desativar o arrasto da Janela
 * @default true
 *
 * @param Closeable
 * @desc true/false para Ativar ou Desativar o Fechamento da Janela
 * @default true
 *
 * @help
 * Esse plugin adiciona várias funções na Window_Base padrão do RMMV.
 *
 * Log Versão 2.2
 *
 * Adicionado Configurações no PluginManager.
 * Corrigido Bug do Arrasto na Diagonal.
 * Melhorias dos Codigos.
 * Adição de Variavel Global $window que suporta todas as Janelas derivadas da Window_Base.

 * Log Versão 2.0
 *
 * Adicionado função de fechamento de janela.
 * Adicionado Sons de fechamento ou não da janela.
 * Corrigido Bug da Area.
 * Alguns bug's de posicionamento corrigidos.
 * Opacidade ao Arrastar janela.
 *
 * Log Versão 1.0
 *
 * Criado as funções de arrasto da janela.
 *
 */

// Cria uma Variavel KR
var KR = KR || {};
KR.Window.version = 2.2;
// Verifica se possui o KR_Plugin
if (KR["KR_Plugin"] === undefined) {
  alert("Please add KR_Plugin before KR_Hud!");
  alert("https://github.com/klebersonromero/KR_MV/tree/master/Plugins");
  throw new Error("Please add KR_Plugin before KR_Hud!");
};
// Verifica a versão do KR_Plugin
if (KR["version"] <= 1.4) {
  alert("Please update KR_Plugin!");
  alert("https://github.com/klebersonromero/KR_MV/tree/master/Plugins");
  throw new Error("Please update KR_Plugin!");
}
// Variais do PluginManager
KR.Window.parameters   = PluginManager.parameters('KR_Drag_Window');
KR.Window.Dragable     = JSON.parse(KR.Window.parameters['Dragable']);
KR.Window.Closeable    = JSON.parse(KR.Window.parameters['Closeable']);
// Variavel Global de Janelas derivadas da Window_Base
$window = []
  //=======================================================================//
 //  ** Metodo Alias do Window_Base.initialize                            //
//=======================================================================//
var alias_Window_Base_initialize_drag = Window_Base.prototype.initialize;
Window_Base.prototype.initialize = function(x, y, width, height) {
    alias_Window_Base_initialize_drag.call(this,arguments);
    Window.prototype.initialize.call(this,arguments);
    this.loadWindowskin();
    this.move(x, y, width, height);
    this.createContents();
    this.draggable = KR.Window.Dragable;
    this.closeable = KR.Window.Closeable;
    this.max_X = Graphics.width - this.width;
    this.max_Y = Graphics.height - this.height;
    $window = this;
};
  //=======================================================================//
 //  ** Metodo Alias do Window_Base.update                                //
//=======================================================================//
var alias_Window_Base_update_drag = Window_Base.prototype.update;
Window_Base.prototype.update = function() {
    alias_Window_Base_update_drag.call(this,arguments);
    this.update_drag_move();
    this.on_close();
};
  //=======================================================================//
 //  ** Metodo Alias do Window_Base.on_close                              //
//=======================================================================//
Window_Base.prototype.on_close = function(){
if (TouchInput.isTriggered() && (this.in_area(this.width-16,0,16,16)) && (this.closeable)){
  SoundManager.playOk();
  this.hide();
}else if (TouchInput.isTriggered() && (this.in_area(this.width-16,0,16,16)) && (!this.closeable)){ SoundManager.playBuzzer() }
};
  //=======================================================================//
 //  ** Metodo de atualização drag_move Window_Base                       //
//=======================================================================//
Window_Base.prototype.update_drag_move = function() {
    this.check_dragability();
    if(this.in_draging){ this.update_in_drag() }
};
  //=======================================================================//
 //  ** Metodo de verificação de arrasto na area(grid) Window_Base        //
//=======================================================================//
Window_Base.prototype.check_dragability = function() {
    if(TouchInput.isPressed()){
    if(this.can_drag() && (this.in_area(0,0,this.width-16,16))) { this.in_drag()}} // Verifica se é possivel arrastar a janela e se está na area
    else{ if(this.in_draging){ this.drag_cancel() }}        // Cancela o arrasto
};
  //=======================================================================//
 //  ** Metodo de verificação se janela é arrastevel Window_Base          //
//=======================================================================//
Window_Base.prototype.can_drag = function() {
	if (this.draggable){ return true }else{ return false	}
};
  //=======================================================================//
 //  ** Metodo de verificação se está dentro a área da janela             //
//=======================================================================//
Window_Base.prototype.in_area = function(x,y,width,height) {
    var tx = TouchInput.x;
    var ty = TouchInput.y;
    if(tx >= this.x+x && tx <= (this.x+this.width) && ty >= this.y+y && ty <= (this.y+height)) { return true} else{ return false }
};
  //=======================================================================//
 //  ** Metodo de verificação está arrastando?                            //
//=======================================================================//
Window_Base.prototype.in_drag = function() {
    this.in_draging = true;
    this.ini_pos_drag = [this.x,this.y];
    this.ini_pos_touch_drag = [TouchInput.x,TouchInput.y];
    this.backOpacity = 120;
};
  //=======================================================================//
 //  ** Metodo de cancelamento do arrasto                                 //
//=======================================================================//
Window_Base.prototype.drag_cancel = function() {
    this.in_draging = false;
    this.update_pos_grid();
    this.backOpacity = 200;
};
  //=======================================================================//
 //  ** Metodo de Atualização da posição do arrasto                       //
//=======================================================================//
Window_Base.prototype.update_in_drag = function() {
    var difX = TouchInput.x - this.ini_pos_touch_drag[0];
    var difY = TouchInput.y - this.ini_pos_touch_drag[1];
    this.x = this.ini_pos_drag[0] + difX;
    this.y = this.ini_pos_drag[1] + difY;
};
  //==========================================================================//
 //  ** Metodo de Atualização da posição do arrasto dentro da area do grafico //
//===========================================================================//
Window_Base.prototype.update_pos_grid = function() {
    // Calculo de Maximo X
    if (this.x > this.max_X){
    	this.x = this.max_X;
    if (this.x > this.max_X && this.y > this.max_Y){
      this.x = this.max_X;
      this.y = this.max_Y;
    }
    }else if (this.x < 0) {
    	this.x = 0;
    if (this.x && this.y < 0){ this.x = 0; this.y = 0 }
    }
    // Calculo de Maximo Y
    if (this.y > this.max_Y){
    	this.y = this.max_Y;
    }else if (this.y < 0) {
		  this.y = 0;
    if (this.y && this.x < 0){ this.x = 0; this.y = 0 }
    }
};
<|endoftext|>


<commit_before>
//   listSubmittedFiles.js

//////////////////////////////////

// JavaScript directive:   all variables have to be declared with "var", maybe other things

"use strict";

$(document).ready(function()  {

		initPage();

});

/////////////

function initPage() {

	updateFileList();

}

///////////////

function updateFileList( params ) {

	$("#submitted_fasta_files").empty();

	var statusArray = null;
	var callAfterUpdate = null;

	if ( params ) {
		statusArray = params.statusArray;

		callAfterUpdate = params.callAfterUpdate;
	}

	if ( ! statusArray ) {

		statusArray = [];
	}

	var _URL = contextPathJSVar + "/services/submittedFiles/list";

	var ajaxRequestData = {

			status : statusArray
	};

	$.ajax({
		cache: false,
		type: "GET",
		url: _URL,
		dataType: "json",
		data: ajaxRequestData,  //  The data sent as params on the URL

		traditional: true,  //  Force traditional serialization of the data sent
		//   One thing this means is that arrays are sent as the object property instead of object property followed by "[]".
		//   So searchIds array is passed as "searchIds=<value>" which is what Jersey expects

		success: function(data)	{

			updateFileListProcessResponse( { ajaxResponseData: data, ajaxRequestData: ajaxRequestData, callAfterUpdate : callAfterUpdate });

		},
		failure: function(errMsg) {
			handleAJAXFailure( errMsg );
		},
		error: function(jqXHR, textStatus, errorThrown) {

			handleAJAXError( jqXHR, textStatus, errorThrown );
		}
	});
}

function updateFileListProcessResponse( params ) {

	updateStatusTimerObject.cancelUpdateStatusTimers();

	var ajaxResponseData = params.ajaxResponseData;
	var callAfterUpdate = params.callAfterUpdate;

	if ( ajaxResponseData && ajaxResponseData.length > 0 ) {

		var fileList = ajaxResponseData;

		//   Copy the overall table to the display div

		var file_list_table_template_html = $("#file_list_table_template").html();
		$("#submitted_fasta_files").html( file_list_table_template_html );

		//  select the table within the div
		var $submitted_fasta_files_table = $("#submitted_fasta_files table");

		//  Get the Handlebars template for an entry and compile it
		var $file_list_entry_template = $("#file_list_entry_template tbody");
		var source = $file_list_entry_template.html();
		var template = Handlebars.compile(source);

		//  process the file list
		for ( var fileListIndex = 0; fileListIndex < fileList.length; fileListIndex++ ) {

			var fileEntry = fileList[ fileListIndex ];

			var context = fileEntry;

			var html = template(context);

//			var $file_list_entry =
				$(html).appendTo( $submitted_fasta_files_table );

//			var statusData = fileEntry.statusData;

//			if ( ! ( statusData.importComplete || statusData.userInputRequired ) ) {
//
//				//  Hide link for details since file may not exist or is incomplete
//
//				var $mapping_details_link_jq =  $file_list_entry.find(".mapping_details_link_jq");
//				$mapping_details_link_jq.hide();
//			}

			processStatus( { statusData : fileEntry.statusData , file_import_id : fileEntry.item.id, updateOtherFields : false } );

		}
	}

//	if ( callAfterUpdate ) {
//
//		callAfterUpdate();
//
//	}

	showFileDetailsForIdInHiddenField();
}

<commit_msg>Fix minor page formatting error when click link in email.<commit_after>
//   listSubmittedFiles.js

//////////////////////////////////

// JavaScript directive:   all variables have to be declared with "var", maybe other things

"use strict";

$(document).ready(function()  {

		initPage();

});

/////////////

function initPage() {

	updateFileList();

}

///////////////

function updateFileList( params ) {

	$("#submitted_fasta_files").empty();

	var statusArray = null;
	var callAfterUpdate = null;

	if ( params ) {
		statusArray = params.statusArray;

		callAfterUpdate = params.callAfterUpdate;
	}

	if ( ! statusArray ) {

		statusArray = [];
	}

	var _URL = contextPathJSVar + "/services/submittedFiles/list";

	var ajaxRequestData = {

			status : statusArray
	};

	$.ajax({
		cache: false,
		type: "GET",
		url: _URL,
		dataType: "json",
		data: ajaxRequestData,  //  The data sent as params on the URL

		traditional: true,  //  Force traditional serialization of the data sent
		//   One thing this means is that arrays are sent as the object property instead of object property followed by "[]".
		//   So searchIds array is passed as "searchIds=<value>" which is what Jersey expects

		success: function(data)	{

			updateFileListProcessResponse( { ajaxResponseData: data, ajaxRequestData: ajaxRequestData, callAfterUpdate : callAfterUpdate });

		},
		failure: function(errMsg) {
			handleAJAXFailure( errMsg );
		},
		error: function(jqXHR, textStatus, errorThrown) {

			handleAJAXError( jqXHR, textStatus, errorThrown );
		}
	});
}

function updateFileListProcessResponse( params ) {

	updateStatusTimerObject.cancelUpdateStatusTimers();

	var ajaxResponseData = params.ajaxResponseData;
	var callAfterUpdate = params.callAfterUpdate;

	if ( ajaxResponseData && ajaxResponseData.length > 0 ) {

		var fileList = ajaxResponseData;

		//   Copy the overall table to the display div

		var file_list_table_template_html = $("#file_list_table_template").html();
		$("#submitted_fasta_files").html( file_list_table_template_html );

		//  select the table within the div
		var $submitted_fasta_files_table = $("#submitted_fasta_files table");

		//  Get the Handlebars template for an entry and compile it
		var $file_list_entry_template = $("#file_list_entry_template tbody");
		var source = $file_list_entry_template.html();
		var template = Handlebars.compile(source);

		//  process the file list
		for ( var fileListIndex = 0; fileListIndex < fileList.length; fileListIndex++ ) {

			var fileEntry = fileList[ fileListIndex ];

			var context = fileEntry;

			var html = template(context);

//			var $file_list_entry =
				$(html).appendTo( $submitted_fasta_files_table );

//			var statusData = fileEntry.statusData;

//			if ( ! ( statusData.importComplete || statusData.userInputRequired ) ) {
//
//				//  Hide link for details since file may not exist or is incomplete
//
//				var $mapping_details_link_jq =  $file_list_entry.find(".mapping_details_link_jq");
//				$mapping_details_link_jq.hide();
//			}

			processStatus( { statusData : fileEntry.statusData , file_import_id : fileEntry.item.id, updateOtherFields : false } );

		}
	}

//	if ( callAfterUpdate ) {
//
//		callAfterUpdate();
//
//	}
	window.setTimeout( function() {

		showFileDetailsForIdInHiddenField();
	}, 1000);
}

<|endoftext|>


<commit_before>"use strict";

jsns.run(function (using) {
    var storage = using("htmlrest.storage");
    var component = using("htmlrest.components");

    var navMenu = Sizzle('[data-editor-navmenu]')[0];
    var navItems = Sizzle('[data-editor-navitem]');
    navItems.forEach(function (item) {
        navMenu.appendChild(item);
        item.style.display = "";
    });

    var navItems = storage.getInInstance("edit-nav-menu-items", []);
    navItems.forEach(function (item) {
        component.single(item.name, null, navMenu, item.created);
    });
});<commit_msg>Removed dead way of finding buttons for the nav menu.<commit_after>"use strict";

jsns.run(function (using) {
    var storage = using("htmlrest.storage");
    var component = using("htmlrest.components");

    var navMenu = $('[data-editor-navmenu]')[0];

    var navItems = storage.getInInstance("edit-nav-menu-items", []);
    navItems.forEach(function (item) {
        component.single(item.name, null, navMenu, item.created);
    });
});<|endoftext|>


<commit_before>'use strict';

var mongodb = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var GenericAdapter = require('@back4app/back4app-entity').Adapter;

module.exports = MongoAdapter;

/**
 * Adapter for MongoDB, extended from entity project Adapter.
 * @constructor
 * @memberof module:back4app/entity-mongodb/models
 * @example
 * module.exports = MongoAdapter;
 */
function MongoAdapter(host, port) {
  var mongo = new GenericAdapter();
  mongo.config = {};
  mongo.config.host = host;
  mongo.config.port = port;

  mongo.db = null;

  mongo.openConnection = openConnection;
  mongo.closeConnection = closeConnection;

  /**
   * Connects the mongoose with the targeted Mongo database.
   * @name module:back4app/entity-mongodb/models/SchemaBuilder~openConnection
   * @function
   * @param {!module:back4app/entity/models/Entity}
   * entity Entity instance containing properties that shall become
   * the Schema properties.
   * @returns {!Promise} Promise that connects the mongoose to mongo database,
   * and returns it to be used in chained functions.
   * @example
   * var promise = openConnection().then(function (db) {
   *   mongo.db = db;
   *   mongo.entitySchema = Schema.buildModel(entity);
   *   return mongo.entitySchema;
   * }, function () {
   *   throw 'connection error';
   * });
   */
  function openConnection() {
    return new Promise(function (resolve, reject) {
      var uri = 'mongodb://';
      uri += mongo.config.host || 'localhost';
      uri += mongo.config.port ? ':' + mongo.config.port : '';
      uri += '/test';
      MongoClient.connect(uri, function(err, db) {
        if (err) {
          reject(db);
          return null;
        }
        mongo.db = db;
        resolve(db);
        return db;
      });
    });
  }

  /**
   * Closes the current connection.
   * @name module:back4app/entity-mongodb/models/SchemaBuilder~closeConnection
   * @function
   */
  function closeConnection() {
    mongo.db.close();
    mongo.db = null;
  }

  return mongo;
}
<commit_msg>Creates the first version for adapting the entity to be saved.<commit_after>'use strict';

var mongodb = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var GenericAdapter = require('@back4app/back4app-entity').Adapter;

module.exports = MongoAdapter;

/**
 * Adapter for MongoDB, extended from entity project Adapter.
 * @constructor
 * @memberof module:back4app/entity-mongodb/models
 * @example
 * module.exports = MongoAdapter;
 */
function MongoAdapter(host, port) {
  var mongo = new GenericAdapter();
  mongo.config = {};
  mongo.config.host = host;
  mongo.config.port = port;

  mongo.db = null;

  mongo.openConnection = openConnection;
  mongo.closeConnection = closeConnection;
  mongo.instanceToJSON = instanceToJSON;

  /**
   * Connects the mongoose with the targeted Mongo database.
   * @name module:back4app/entity-mongodb/models/SchemaBuilder~openConnection
   * @function
   * @param {!module:back4app/entity/models/Entity}
   * entity Entity instance containing properties that shall become
   * the Schema properties.
   * @returns {!Promise} Promise that connects the mongoose to mongo database,
   * and returns it to be used in chained functions.
   * @example
   * var promise = openConnection().then(function (db) {
   *   mongo.db = db;
   *   mongo.entitySchema = Schema.buildModel(entity);
   *   return mongo.entitySchema;
   * }, function () {
   *   throw 'connection error';
   * });
   */
  function openConnection() {
    return new Promise(function (resolve, reject) {
      var uri = 'mongodb://';
      uri += mongo.config.host || 'localhost';
      uri += mongo.config.port ? ':' + mongo.config.port : '';
      uri += '/test';
      MongoClient.connect(uri, function(err, db) {
        if (err) {
          reject(db);
          return null;
        }
        mongo.db = db;
        resolve(db);
        return db;
      });
    });
  }

  /**
   * Closes the current connection.
   * @name module:back4app/entity-mongodb/models/SchemaBuilder~closeConnection
   * @function
   */
  function closeConnection() {
    mongo.db.close();
    mongo.db = null;
  }

  function instanceToJSON(instance) {
    var json = {};
    for(var key in instance.Entity.attributes){
      json[key] = instance[key];
    }

    if (instance.id) {
      json['_id'] = instance.id;
    }

    return json;
  }

  return mongo;
}
<|endoftext|>


<commit_before>import {
  BehaviorSubject,
  ReplaySubject
} from 'rx'

export default function createDispatcher() {
  const dispatcher = new ReplaySubject()
  dispatcher.onNext(null) // Initialisation action

  const identifier = Symbol()
  const cache = []
  const state = []

  // Extend Observable with our Dispatcher methods
  const res = dispatcher.asObservable()
  const proto = Object.create(Object.getPrototypeOf(res))
  Object.setPrototypeOf(res, proto)

  proto.dispatch = action => {
    if (typeof action === 'function') {
      return Promise.resolve(
        action(res => {
          dispatcher.onNext(res)
        })
      ).then(res => {
        dispatcher.onNext(res)
        return res
      })
    }

    dispatcher.onNext(action)
    return Promise.resolve(action)
  }

  proto.getState = fn => {
    if (typeof fn[identifier] === 'number')
      return state[fn[identifier]]()

    throw `Function wasn't yet reduced and is therefore unknown.`
  }

  proto.reduce = (fn, init = null) => {
    if (typeof fn[identifier] === 'number')
      return cache[fn[identifier]]

    const store = new BehaviorSubject(init)
    const anon = store.asObservable()

    dispatcher
      .scan(fn)
      .distinctUntilChanged()
      .subscribe(x => store.onNext(x))

    fn[identifier] = cache.length
    state.push(store.getValue.bind(store))
    cache.push(anon)

    return anon
  }

  return res
}
<commit_msg>Fix initial action to include a type<commit_after>import {
  BehaviorSubject,
  ReplaySubject
} from 'rx'

export default function createDispatcher() {
  const dispatcher = new ReplaySubject()
  dispatcher.onNext({ type: '_INIT_' }) // Initialisation action

  const identifier = Symbol()
  const cache = []
  const state = []

  // Extend Observable with our Dispatcher methods
  const res = dispatcher.asObservable()
  const proto = Object.create(Object.getPrototypeOf(res))
  Object.setPrototypeOf(res, proto)

  proto.dispatch = action => {
    if (typeof action === 'function') {
      return Promise.resolve(
        action(res => {
          dispatcher.onNext(res)
        })
      ).then(res => {
        dispatcher.onNext(res)
        return res
      })
    }

    dispatcher.onNext(action)
    return Promise.resolve(action)
  }

  proto.getState = fn => {
    if (typeof fn[identifier] === 'number')
      return state[fn[identifier]]()

    throw `Function wasn't yet reduced and is therefore unknown.`
  }

  proto.reduce = (fn, init = null) => {
    if (typeof fn[identifier] === 'number')
      return cache[fn[identifier]]

    const store = new BehaviorSubject(init)
    const anon = store.asObservable()

    dispatcher
      .scan(fn)
      .distinctUntilChanged()
      .subscribe(x => store.onNext(x))

    fn[identifier] = cache.length
    state.push(store.getValue.bind(store))
    cache.push(anon)

    return anon
  }

  return res
}
<|endoftext|>


<commit_before>(function ( Backbone, Underscore ) {

  'use strict';

  var bbExtend = Backbone.Model.extend;

  Backbone.Model.extend = function ( properties, classProperties ) {
    var prop, action, propSpec, deps;

    var computedProps = properties.properties;
    delete properties.properties;

    var Class = bbExtend.call( this, properties, classProperties );

    if ( computedProps ) {
      for ( prop in computedProps ) {
        if ( computedProps.hasOwnProperty( prop ) ) {
          propSpec = computedProps[ prop ];
          if ( propSpec instanceof Function ) {
            action = propSpec;
            deps = [];
          } else {
            action = propSpec.action;
            deps = propSpec.deps || [];
          }
          computedProps[ prop ] = {
            action: action,
            deps: deps
          };
        }
      }
    }

    var get = Class.prototype.get;
    Class.prototype.get = function ( attr ) {
      if ( computedProps[ attr ] ) {
        return computedProps[ attr ].action.call( this );
      }
      return get.apply( this, arguments );
    };

    var set = Class.prototype.set;
    Class.prototype.set = function ( attr, value ) {
      if ( computedProps[ attr ] ) {
        computedProps[ attr ].action.call( this, value );
        return this;
      }
      return set.apply( this, arguments );
    };

    return Class;
  };

}( this.Backbone, this.underscore ));
<commit_msg>Rename internal underscore<commit_after>(function ( Backbone, _ ) {

  'use strict';

  var bbExtend = Backbone.Model.extend;

  Backbone.Model.extend = function ( properties, classProperties ) {
    var prop, action, propSpec, deps;

    var computedProps = properties.properties;
    delete properties.properties;

    var Class = bbExtend.call( this, properties, classProperties );

    if ( computedProps ) {
      for ( prop in computedProps ) {
        if ( computedProps.hasOwnProperty( prop ) ) {
          propSpec = computedProps[ prop ];
          if ( propSpec instanceof Function ) {
            action = propSpec;
            deps = [];
          } else {
            action = propSpec.action;
            deps = propSpec.deps || [];
          }
          computedProps[ prop ] = {
            action: action,
            deps: deps
          };
        }
      }
    }

    var get = Class.prototype.get;
    Class.prototype.get = function ( attr ) {
      if ( computedProps[ attr ] ) {
        return computedProps[ attr ].action.call( this );
      }
      return get.apply( this, arguments );
    };

    var set = Class.prototype.set;
    Class.prototype.set = function ( attr, value ) {
      if ( computedProps[ attr ] ) {
        computedProps[ attr ].action.call( this, value );
        return this;
      }
      return set.apply( this, arguments );
    };

    return Class;
  };

}( this.Backbone, this.underscore ));
<|endoftext|>


<commit_before>var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    width = w.innerWidth || e.clientWidth || g.clientWidth,
    height = w.innerHeight || e.clientHeight || g.clientHeight;

var game = new Phaser.Game(width, height, Phaser.AUTO, 'robits', { preload: preload, create: create, update: update, render: render });
var localPlayer, board, map;
var cursors;
var widthInTiles, heightInTiles, tileWidth;
var keyboardMovement = true;
var maxPlayers = 8;
var playerId = 0;
//initiate connection to server
var ignoreArrowKeys,
    players = [];
var socket = io();

var colorScale = chroma.scale('RdYlBu');

function preload() {
    game.load.tilemap('map', 'assets/map1.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tileset', 'assets/tileset.png');
    game.load.image('robot', 'assets/robot.png');
    game.load.image('portal', 'assets/portal.png');
}

function create() {

    setUpSocketReceivers();
    cursors = game.input.keyboard.createCursorKeys();

    game.stage.backgroundColor  = '#787878';

    map = game.add.tilemap('map');
    map.addTilesetImage('tileset');

    map.setCollision(6);
    map.setTileIndexCallback(3, goThroughPortal, this);
    map.setTileIndexCallback(5, fallInHole, this);

    layer = map.createLayer('Tile Layer 1');
    layer.resizeWorld();

    game.world.setBounds(0, 0, map.width, map.height);

    game.physics.startSystem(Phaser.Physics.ARCADE);

    localPlayer = addPlayer();

    game.camera.follow(localPlayer);

    widthInTiles = 16;
    heightInTiles = 12;
    tileWidth = 128;
}

function addPlayer(data) {
    var player = game.add.sprite(64 + 64 * Math.round(Math.random() * 3), 64 + 64 * Math.round(Math.random() * 3), 'robot');
    game.physics.arcade.enable(player);

    player.data = _.extend({
        movementQueue: [],
        id: Math.random()
    }, data);

    _.each(_.range(Math.round(Math.random() * 25) + 25), function () {
        player.data.movementQueue.push(_.partial(moveAtAngle, player, 90 * Math.floor(Math.random() * 4)));
    });

    player.body.collideWorldBounds = true;
  player.body.setSize(128, 128); //TODO set to 128x128 once we have perfect movement

  player.anchor.setTo(0.5, 0.5);

    var color = colorScale(players.length / maxPlayers);
    player.tint = parseInt(color.hex().replace("#", ""), 16);

    players.push(player);

    return player;
}

function update() {
    _.each(players, function (player) {
      game.physics.arcade.collide(player, layer);
      planMovement(player);
        kickoffMovement(player);
    });
}

function render() {
  game.debug.body(localPlayer);
}

function planMovement(player) {
    if (!ignoreArrowKeys) {
        var angle;
        if (cursors.right.isDown) {
            angle = 0;
        } else if (cursors.left.isDown) {
            angle = 180;
        } else if (cursors.down.isDown) {
            angle = 90;
        } else if (cursors.up.isDown) {
            angle = 270;
        }
        if (!_.isUndefined(angle)) {
            player.data.movementQueue.push(_.partial(moveAtAngle, player, angle));
        }
        ignoreArrowKeys = true;
        setTimeout(function () {
            ignoreArrowKeys = false;
        }, 50);
    }
}

function kickoffMovement(player) {
    if (!player.data.stepInProgress) {
        var nextStep = player.data.movementQueue.shift();
        if (nextStep) {
            nextStep();
        }
    }
}

function moveAtAngle(player, angle) {
    player.data.stepInProgress = true;

    var distance = 128;
    var speed = 500;
    var time = distance / speed;

    this.target = [player.x + distance, player.y];

    game.physics.arcade.velocityFromAngle(angle || 0, speed, player.body.velocity);

    setTimeout(_.partial(clearSpriteMovement, player), time * 1000);
}

function disconnect() {
    socket.emit("player left", playerId);
}

function playerDisconnected(){

    socket.emit("player left", playerId )
}

function playerMoved() {
    socket.emit("player moved", 0)
}

function playerDied() {
    socket.emit("player died", playerId)
}

function goThroughPortal(sprite, tile) {
  console.log("going through portal!");
  //teleport to other portal
  return false;
}

function fallInHole(sprite, tile) {
  console.log("fell in hole!");
  // player reset
  sprite.body.x = 0;
  sprite.body.y = 0;
  clearSpriteMovement(sprite);
  return false;
}

function clearSpriteMovement(sprite) {
  sprite.body.velocity.x = 0;
  sprite.body.velocity.y = 0;
  sprite.data.stepInProgress = false;
}

function playerConnected(playerId) {
    addPlayer({id: playerId});
}

function playerWins(playerId) {
    //stop the game. display ./vbcn/message
    alert("Game Over: " + playerId + " wins!");
}

function setUpSocketReceivers() {
    socket.on('player won', playerWins);

    socket.on('player joined', playerConnected);

    socket.on("update", function () {
        //probably list of all players and current positions.

    socket.on('receive id', function(playerId){
        console.log('I got my id it is: ' + playerId)
    });

    });
}

<commit_msg>Only accept keyboard input on debug mode<commit_after>var DEBUG_MODE = true;

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    width = w.innerWidth || e.clientWidth || g.clientWidth,
    height = w.innerHeight || e.clientHeight || g.clientHeight;

var game = new Phaser.Game(width, height, Phaser.AUTO, 'robits', { preload: preload, create: create, update: update, render: render });
var localPlayer, board, map;
var cursors;
var widthInTiles, heightInTiles, tileWidth;
var maxPlayers = 8;
var playerId = 0;
//initiate connection to server
var ignoreArrowKeys,
    players = [];
var socket = io();

var colorScale = chroma.scale('RdYlBu');

function preload() {
    game.load.tilemap('map', 'assets/map1.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tileset', 'assets/tileset.png');
    game.load.image('robot', 'assets/robot.png');
    game.load.image('portal', 'assets/portal.png');
}

function create() {

    setUpSocketReceivers();
    cursors = game.input.keyboard.createCursorKeys();

    game.stage.backgroundColor  = '#787878';

    map = game.add.tilemap('map');
    map.addTilesetImage('tileset');

    map.setCollision(6);
    map.setTileIndexCallback(3, goThroughPortal, this);
    map.setTileIndexCallback(5, fallInHole, this);

    layer = map.createLayer('Tile Layer 1');
    layer.resizeWorld();

    game.world.setBounds(0, 0, map.width, map.height);

    game.physics.startSystem(Phaser.Physics.ARCADE);

    localPlayer = addPlayer();

    game.camera.follow(localPlayer);

    widthInTiles = 16;
    heightInTiles = 12;
    tileWidth = 128;
}

function addPlayer(data) {
    var player = game.add.sprite(64 + 64 * Math.round(Math.random() * 3), 64 + 64 * Math.round(Math.random() * 3), 'robot');
    game.physics.arcade.enable(player);

    player.data = _.extend({
        movementQueue: [],
        id: Math.random()
    }, data);

    _.each(_.range(Math.round(Math.random() * 25) + 25), function () {
        player.data.movementQueue.push(_.partial(moveAtAngle, player, 90 * Math.floor(Math.random() * 4)));
    });

    player.body.collideWorldBounds = true;
  player.body.setSize(128, 128); //TODO set to 128x128 once we have perfect movement

  player.anchor.setTo(0.5, 0.5);

    var color = colorScale(players.length / maxPlayers);
    player.tint = parseInt(color.hex().replace("#", ""), 16);

    players.push(player);

    return player;
}

function update() {
    _.each(players, function (player) {
      game.physics.arcade.collide(player, layer);
      planMovement(player);
        kickoffMovement(player);
    });
}

function render() {
  game.debug.body(localPlayer);
}

function planMovement(player) {
    if(!DEBUG_MODE) {
        return;
    }

    if (!ignoreArrowKeys) {
        var angle;
        if (cursors.right.isDown) {
            angle = 0;
        } else if (cursors.left.isDown) {
            angle = 180;
        } else if (cursors.down.isDown) {
            angle = 90;
        } else if (cursors.up.isDown) {
            angle = 270;
        }
        if (!_.isUndefined(angle)) {
            player.data.movementQueue.push(_.partial(moveAtAngle, player, angle));
        }
        ignoreArrowKeys = true;
        setTimeout(function () {
            ignoreArrowKeys = false;
        }, 50);
    }
}

function kickoffMovement(player) {
    if (!player.data.stepInProgress) {
        var nextStep = player.data.movementQueue.shift();
        if (nextStep) {
            nextStep();
        }
    }
}

function moveAtAngle(player, angle) {
    player.data.stepInProgress = true;

    var distance = 128;
    var speed = 500;
    var time = distance / speed;

    this.target = [player.x + distance, player.y];

    game.physics.arcade.velocityFromAngle(angle || 0, speed, player.body.velocity);

    setTimeout(_.partial(clearSpriteMovement, player), time * 1000);
}

function disconnect() {
    socket.emit("player left", playerId);
}

function playerDisconnected(){

    socket.emit("player left", playerId )
}

function playerMoved() {
    socket.emit("player moved", 0)
}

function playerDied() {
    socket.emit("player died", playerId)
}

function goThroughPortal(sprite, tile) {
  console.log("going through portal!");
  //teleport to other portal
  return false;
}

function fallInHole(sprite, tile) {
  console.log("fell in hole!");
  // player reset
  sprite.body.x = 0;
  sprite.body.y = 0;
  clearSpriteMovement(sprite);
  return false;
}

function clearSpriteMovement(sprite) {
  sprite.body.velocity.x = 0;
  sprite.body.velocity.y = 0;
  sprite.data.stepInProgress = false;
}

function playerConnected(playerId) {
    addPlayer({id: playerId});
}

function playerWins(playerId) {
    //stop the game. display ./vbcn/message
    alert("Game Over: " + playerId + " wins!");
}

function setUpSocketReceivers() {
    socket.on('player won', playerWins);

    socket.on('player joined', playerConnected);

    socket.on("update", function () {
        //probably list of all players and current positions.
    });

    socket.on('receive id', function(playerId){
        console.log('I got my id it is: ' + playerId)
    });

}

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { View, Text, StyleSheet } from 'react-native'

export default class TeamList extends Component {
  renderItem = (text, i) => {
    return (
      <Text style={styles.item}>{text}</Text>
    )
  }

  render() {
    const {list, title, color} = this.props

    return (
      <View>
        <View style={styles.header} backgroundColor={color}>
          <Text style={styles.title}>{title}</Text>
        </View>
        <View>
          {list.map(this.renderItem)}
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  item: {
    backgroundColor: 'whitesmoke',
    marginBottom: 5,
    padding: 15,
  },
  header: {
    backgroundColor: 'skyblue',
    padding: 15,
  },
  title: {
    textAlign: 'center',
    color: 'white',
  },
})
<commit_msg>Add key to TeamList<commit_after>import React, { Component } from 'react'
import { View, Text, StyleSheet } from 'react-native'

export default class TeamList extends Component {
  renderItem = (text, i) => {
    return (
      <Text style={styles.item} key={text}>{text}</Text>
    )
  }

  render() {
    const {list, title, color} = this.props

    return (
      <View>
        <View style={styles.header} backgroundColor={color}>
          <Text style={styles.title}>{title}</Text>
        </View>
        <View>
          {list.map(this.renderItem)}
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  item: {
    backgroundColor: 'whitesmoke',
    marginBottom: 5,
    padding: 15,
  },
  header: {
    backgroundColor: 'skyblue',
    padding: 15,
  },
  title: {
    textAlign: 'center',
    color: 'white',
  },
})
<|endoftext|>