<commit_before>/**
 * @namespace
 */
Z.ui = {};
/**
 * Some instance methods subclasses needs to implement:

 *

 * 1. Optional, returns the Dom element's position offset

 * function getOffset : maptalks.Point

 *

 * 2. Method to create UI's Dom element

 * function buildOn : HTMLElement

 *

 * 3 Optional, to provide an event map to register event listeners.

 * function getEvents : void

 * 4 Optional, a callback when dom is removed.

 * function onDomRemove : void

 * 5 Optional, a callback when UI Component is removed.

 * function onRemove : void

 * @classdesc
 * Base class for all the UI component classes, a UI component is a HTMLElement positioned with geographic coordinate.

 * It is abstract and not intended to be instantiated.
 *
 * @class
 * @category ui
 * @abstract
 * @mixes maptalks.Eventable
 * @memberOf maptalks.ui
 * @name UIComponent
 */
Z.ui.UIComponent = Z.Class.extend(/** @lends maptalks.ui.UIComponent.prototype */{
    includes: [Z.Eventable],

    /**
     * @property {Object} options
     * @property {Boolean} [options.eventsToStop='mousedown dblclick']  - UI's dom events to stop propagation.
     * @property {Number}  [options.dx=0]     - pixel offset on x axis
     * @property {Number}  [options.dy=0]     - pixel offset on y axis
     * @property {Boolean} [options.autoPan=false]  - set it to false if you don't want the map to do panning animation to fit the opened UI.
     * @property {Boolean} [options.single=true]    - whether the UI is a global single one, only one UI will be shown at the same time if set to true.
     */
    options:{
        'eventsToStop' : 'mousedown dblclick',
        'dx'     : 0,
        'dy'     : 0,
        'autoPan' : false,
        'single' : true
    },

    initialize: function (options) {
        Z.Util.setOptions(this, options);
    },

    /**
     * Adds the UI Component to a geometry or a map
     * @param {maptalks.Geometry|maptalks.Map} owner - geometry or map to addto.
     * @returns {maptalks.ui.UIComponent} this
     * @fires maptalks.ui.UIComponent#add
     */
    addTo:function (owner) {
        this._owner = owner;
        /**
         * add event.
         *
         * @event maptalks.ui.UIComponent#add
         * @type {Object}
         * @property {String} type - add
         * @property {maptalks.ui.UIComponent} target - UIComponent
         */
        this.fire('add');
        return this;
    },

    /**
     * Get the map it added to
     * @return {maptalks.Map} map instance
     * @override
     */
    getMap:function () {
        if (this._owner instanceof Z.Map) {
            return this._owner;
        }
        return this._owner.getMap();
    },

    /**
     * Show the UI Component, if it is a global single one, it will close previous one.
     * @param {maptalks.Coordinate} coordinate - coordinate to show
     * @return {maptalks.ui.UIComponent} this
     * @fires maptalks.ui.UIComponent#showstart
     * @fires maptalks.ui.UIComponent#showend
     */
    show: function (coordinate) {
        if (!coordinate) {
            if (this._coordinate) {
                coordinate = this._coordinate;
            } else {
                throw new Error('UI\'s show coordinate is invalid');
            }
        }
        /**
         * showstart event.
         *
         * @event maptalks.ui.UIComponent#showstart
         * @type {Object}
         * @property {String} type - showstart
         * @property {maptalks.ui.UIComponent} target - UIComponent
         */
        this.fire('showstart');
        var map = this.getMap(),
            container = this._getUIContainer();
        if (!this.__uiDOM) {
            this._switchEvents('on');
        }
        this._coordinate = coordinate;
        this._removePrevDOM();
        var dom = this.__uiDOM = this.buildOn(map);
        if (!dom) {
            /**
             * showend event.
             *
             * @event maptalks.ui.UIComponent#showend
             * @type {Object}
             * @property {String} type - showend
             * @property {maptalks.ui.UIComponent} target - UIComponent
             */
            this.fire('showend');
            return this;
        }

        this._measureSize(dom);

        if (this._singleton()) {
            map[this._uiDomKey()] = dom;
        }

        var point = this.getPosition();

        dom.style.position = 'absolute';
        dom.style.left = point.x + 'px';
        dom.style.top  = point.y + 'px';
        dom.style.display = '';

        container.appendChild(dom);

        if (this.options['eventsToStop']) {
            Z.DomUtil.on(dom, this.options['eventsToStop'], Z.DomUtil.stopPropagation);
        }

        //autoPan
        if (this.options['autoPan']) {
            this._autoPan();
        }
        this.fire('showend');
        return this;
    },

    /**
     * Hide the UI Component.
     * @return {maptalks.ui.UIComponent} this
     * @fires maptalks.ui.UIComponent#hide
     */
    hide:function () {
        if (!this.getDOM()) {
            return this;
        }
        this.getDOM().style.display = 'none';
        /**
         * hide event.
         *
         * @event maptalks.ui.UIComponent#hide
         * @type {Object}
         * @property {String} type - hide
         * @property {maptalks.ui.UIComponent} target - UIComponent
         */
        this.fire('hide');
        return this;
    },

    /**
     * Decide whether the ui component is open
     * @returns {Boolean} true|false
     */
    isVisible:function () {
        return this.getDOM() && this.getDOM().style.display !== 'none';
    },

    /**
     * Remove the UI Component
     * @return {maptalks.ui.UIComponent} this
     * @fires maptalks.ui.UIComponent#hide
     * @fires maptalks.ui.UIComponent#remove
     */
    remove: function () {
        this.hide();
        this._switchEvents('off');
        if (this.onRemove) {
            this.onRemove();
        }
        if (!this._singleton() && this.__uiDOM) {
            this._removePrevDOM();
        }
        delete this._owner;
        delete this._map;
        /**
         * remove event.
         *
         * @event maptalks.ui.UIComponent#remove
         * @type {Object}
         * @property {String} type - remove
         * @property {maptalks.ui.UIComponent} target - UIComponent
         */
        this.fire('remove');
        return this;
    },

    /**
     * Get pixel size of the UI Component.
     * @return {maptalks.Size} size
     */
    getSize:function () {
        if (this._size) {
            return this._size.copy();
        } else {
            return null;
        }
    },

    getOwner: function () {
        return this._owner;
    },

    getDOM : function () {
        return this.__uiDOM;
    },

    getPosition : function () {
        var p = this._getViewPoint();
        if (this.getOffset) {
            var o = this.getOffset();
            if (o) { p._add(o); }
        }
        return p;
    },

    _getViewPoint : function () {
        return this.getMap().coordinateToViewPoint(this._coordinate)
                    ._add(this.options['dx'], this.options['dy']);
    },

    _autoPan : function () {
        var map = this.getMap(),
            dom = this.getDOM();
        var point = new Z.Point(parseInt(dom.style.left), parseInt(dom.style.top));
        var mapSize = map.getSize(),
            mapWidth = mapSize['width'],
            mapHeight = mapSize['height'];

        var containerPoint = map.viewPointToContainerPoint(point);
        var clientWidth = parseInt(dom.clientWidth),
            clientHeight = parseInt(dom.clientHeight);
        var left = 0, top = 0;
        if ((containerPoint.x) < 0) {
            left = -(containerPoint.x - clientWidth / 2);
        } else if ((containerPoint.x + clientWidth - 35) > mapWidth) {
            left = (mapWidth - (containerPoint.x + clientWidth * 3 / 2));
        }
        if (containerPoint.y < 0) {
            top = -containerPoint.y + 50;
        } else if (containerPoint.y > mapHeight) {
            top = (mapHeight - containerPoint.y - clientHeight) - 30;
        }
        if (top !== 0 || left !== 0) {
            map._panAnimation(new Z.Point(left, top), 600);
        }
    },

    /**
     * Measure dom's size
     * @param  {HTMLElement} dom - element to measure
     * @return {maptalks.Size} size
     * @private
     */
    _measureSize:function (dom) {
        var container = this._getUIContainer();
        dom.style.position = 'absolute';
        dom.style.left = -99999 + 'px';
        dom.style.top = -99999 + 'px';
        dom.style.display = '';
        container.appendChild(dom);
        this._size = new Z.Size(dom.clientWidth, dom.clientHeight);
        dom.style.display = 'none';
        return this._size;
    },

    /**
     * Remove previous UI DOM if it has.
     *
     * @private
     */
    _removePrevDOM:function () {
        if (this.onDomRemove) {
            this.onDomRemove();
        }
        if (this._singleton()) {
            var map = this.getMap(),
                key = this._uiDomKey();
            if (map[key]) {
                Z.DomUtil.removeDomNode(map[key]);
                delete map[key];
            }
            delete this.__uiDOM;
        } else if (this.__uiDOM) {
            Z.DomUtil.removeDomNode(this.__uiDOM);
            delete this.__uiDOM;
        }
    },

    /**
     * generate the cache key to store the singletong UI DOM
     * @private
     * @return {String} cache key
     */
    _uiDomKey:function () {
        return '__ui_' + this._getClassName();
    },

    _singleton:function () {
        return this.options['single'];
    },

    _getUIContainer : function () {
        return this.getMap()._panels['ui'];
    },

    _getClassName:function () {
        for (var p in Z.ui) {
            if (Z.ui.hasOwnProperty(p)) {
                if (p === 'UIComponent') {
                    continue;
                }
                if (this instanceof (Z.ui[p])) {
                    return p;
                }
            }
        }
        return null;
    },

    _switchEvents: function (to) {
        var events = this._getDefaultEvents();
        if (this.getEvents) {
            Z.Util.extend(events, this.getEvents());
        }
        if (events) {
            var map = this.getMap();
            for (var p in events) {
                if (events.hasOwnProperty(p)) {
                    map[to](p, events[p], this);
                }
            }
        }
    },

    _getDefaultEvents: function () {
        return {
            'zooming' : this.onZooming,
            'zoomend' : this.onZoomEnd
        };
    },

    onZooming : function (param) {
        if (!this.isVisible() || !this.getDOM()) {
            return;
        }
        var dom = this.getDOM(),
            point = this.getMap().coordinateToViewPoint(this._coordinate),
            matrix = param['matrix']['view'];
        var p = matrix.applyToPointInstance(point)._add(this.options['dx'], this.options['dy']);
        if (this.getOffset) {
            var o = this.getOffset();
            if (o) { p._add(o); }
        }
        dom.style.left = p.x + 'px';
        dom.style.top  = p.y + 'px';
    },

    onZoomEnd : function () {
        if (!this.isVisible() || !this.getDOM()) {
            return;
        }
        var dom = this.getDOM(),
            p = this.getPosition();
        dom.style.left = p.x + 'px';
        dom.style.top  = p.y + 'px';
    }
});
<commit_msg>fixed autoPanning repeatedly<commit_after>/**
 * @namespace
 */
Z.ui = {};
/**
 * Some instance methods subclasses needs to implement:

 *

 * 1. Optional, returns the Dom element's position offset

 * function getOffset : maptalks.Point

 *

 * 2. Method to create UI's Dom element

 * function buildOn : HTMLElement

 *

 * 3 Optional, to provide an event map to register event listeners.

 * function getEvents : void

 * 4 Optional, a callback when dom is removed.

 * function onDomRemove : void

 * 5 Optional, a callback when UI Component is removed.

 * function onRemove : void

 * @classdesc
 * Base class for all the UI component classes, a UI component is a HTMLElement positioned with geographic coordinate.

 * It is abstract and not intended to be instantiated.
 *
 * @class
 * @category ui
 * @abstract
 * @mixes maptalks.Eventable
 * @memberOf maptalks.ui
 * @name UIComponent
 */
Z.ui.UIComponent = Z.Class.extend(/** @lends maptalks.ui.UIComponent.prototype */{
    includes: [Z.Eventable],

    /**
     * @property {Object} options
     * @property {Boolean} [options.eventsToStop='mousedown dblclick']  - UI's dom events to stop propagation.
     * @property {Number}  [options.dx=0]     - pixel offset on x axis
     * @property {Number}  [options.dy=0]     - pixel offset on y axis
     * @property {Boolean} [options.autoPan=false]  - set it to false if you don't want the map to do panning animation to fit the opened UI.
     * @property {Boolean} [options.single=true]    - whether the UI is a global single one, only one UI will be shown at the same time if set to true.
     */
    options:{
        'eventsToStop' : 'mousedown dblclick',
        'dx'     : 0,
        'dy'     : 0,
        'autoPan' : false,
        'single' : true
    },

    initialize: function (options) {
        Z.Util.setOptions(this, options);
    },

    /**
     * Adds the UI Component to a geometry or a map
     * @param {maptalks.Geometry|maptalks.Map} owner - geometry or map to addto.
     * @returns {maptalks.ui.UIComponent} this
     * @fires maptalks.ui.UIComponent#add
     */
    addTo:function (owner) {
        this._owner = owner;
        /**
         * add event.
         *
         * @event maptalks.ui.UIComponent#add
         * @type {Object}
         * @property {String} type - add
         * @property {maptalks.ui.UIComponent} target - UIComponent
         */
        this.fire('add');
        return this;
    },

    /**
     * Get the map it added to
     * @return {maptalks.Map} map instance
     * @override
     */
    getMap:function () {
        if (this._owner instanceof Z.Map) {
            return this._owner;
        }
        return this._owner.getMap();
    },

    /**
     * Show the UI Component, if it is a global single one, it will close previous one.
     * @param {maptalks.Coordinate} coordinate - coordinate to show
     * @return {maptalks.ui.UIComponent} this
     * @fires maptalks.ui.UIComponent#showstart
     * @fires maptalks.ui.UIComponent#showend
     */
    show: function (coordinate) {
        if (!coordinate) {
            if (this._coordinate) {
                coordinate = this._coordinate;
            } else {
                throw new Error('UI\'s show coordinate is invalid');
            }
        }
        /**
         * showstart event.
         *
         * @event maptalks.ui.UIComponent#showstart
         * @type {Object}
         * @property {String} type - showstart
         * @property {maptalks.ui.UIComponent} target - UIComponent
         */
        this.fire('showstart');
        var map = this.getMap(),
            container = this._getUIContainer();
        if (!this.__uiDOM) {
            this._switchEvents('on');
        }
        this._coordinate = coordinate;
        this._removePrevDOM();
        var dom = this.__uiDOM = this.buildOn(map);
        if (!dom) {
            /**
             * showend event.
             *
             * @event maptalks.ui.UIComponent#showend
             * @type {Object}
             * @property {String} type - showend
             * @property {maptalks.ui.UIComponent} target - UIComponent
             */
            this.fire('showend');
            return this;
        }

        this._measureSize(dom);

        if (this._singleton()) {
            map[this._uiDomKey()] = dom;
        }

        var point = this.getPosition();

        dom.style.position = 'absolute';
        dom.style.left = point.x + 'px';
        dom.style.top  = point.y + 'px';
        dom.style.display = '';

        container.appendChild(dom);

        if (this.options['eventsToStop']) {
            Z.DomUtil.on(dom, this.options['eventsToStop'], Z.DomUtil.stopPropagation);
        }

        //autoPan
        if (this.options['autoPan']) {
            this._autoPan();
        }
        this.fire('showend');
        return this;
    },

    /**
     * Hide the UI Component.
     * @return {maptalks.ui.UIComponent} this
     * @fires maptalks.ui.UIComponent#hide
     */
    hide:function () {
        if (!this.getDOM()) {
            return this;
        }
        this.getDOM().style.display = 'none';
        /**
         * hide event.
         *
         * @event maptalks.ui.UIComponent#hide
         * @type {Object}
         * @property {String} type - hide
         * @property {maptalks.ui.UIComponent} target - UIComponent
         */
        this.fire('hide');
        return this;
    },

    /**
     * Decide whether the ui component is open
     * @returns {Boolean} true|false
     */
    isVisible:function () {
        return this.getDOM() && this.getDOM().style.display !== 'none';
    },

    /**
     * Remove the UI Component
     * @return {maptalks.ui.UIComponent} this
     * @fires maptalks.ui.UIComponent#hide
     * @fires maptalks.ui.UIComponent#remove
     */
    remove: function () {
        this.hide();
        this._switchEvents('off');
        if (this.onRemove) {
            this.onRemove();
        }
        if (!this._singleton() && this.__uiDOM) {
            this._removePrevDOM();
        }
        delete this._owner;
        delete this._map;
        /**
         * remove event.
         *
         * @event maptalks.ui.UIComponent#remove
         * @type {Object}
         * @property {String} type - remove
         * @property {maptalks.ui.UIComponent} target - UIComponent
         */
        this.fire('remove');
        return this;
    },

    /**
     * Get pixel size of the UI Component.
     * @return {maptalks.Size} size
     */
    getSize:function () {
        if (this._size) {
            return this._size.copy();
        } else {
            return null;
        }
    },

    getOwner: function () {
        return this._owner;
    },

    getDOM : function () {
        return this.__uiDOM;
    },

    getPosition : function () {
        var p = this._getViewPoint();
        if (this.getOffset) {
            var o = this.getOffset();
            if (o) { p._add(o); }
        }
        return p;
    },

    _getViewPoint : function () {
        return this.getMap().coordinateToViewPoint(this._coordinate)
                    ._add(this.options['dx'], this.options['dy']);
    },

    _autoPan : function () {
        var map = this.getMap(),
            dom = this.getDOM();
        if (map._moving || map._panAnimating) {
            return;
        }
        var point = new Z.Point(parseInt(dom.style.left), parseInt(dom.style.top));
        var mapSize = map.getSize(),
            mapWidth = mapSize['width'],
            mapHeight = mapSize['height'];

        var containerPoint = map.viewPointToContainerPoint(point);
        var clientWidth = parseInt(dom.clientWidth),
            clientHeight = parseInt(dom.clientHeight);
        var left = 0, top = 0;
        if ((containerPoint.x) < 0) {
            left = -(containerPoint.x - clientWidth / 2);
        } else if ((containerPoint.x + clientWidth - 35) > mapWidth) {
            left = (mapWidth - (containerPoint.x + clientWidth * 3 / 2));
        }
        if (containerPoint.y < 0) {
            top = -containerPoint.y + 50;
        } else if (containerPoint.y > mapHeight) {
            top = (mapHeight - containerPoint.y - clientHeight) - 30;
        }
        if (top !== 0 || left !== 0) {
            map._panAnimation(new Z.Point(left, top), 600);
        }
    },

    /**
     * Measure dom's size
     * @param  {HTMLElement} dom - element to measure
     * @return {maptalks.Size} size
     * @private
     */
    _measureSize:function (dom) {
        var container = this._getUIContainer();
        dom.style.position = 'absolute';
        dom.style.left = -99999 + 'px';
        dom.style.top = -99999 + 'px';
        dom.style.display = '';
        container.appendChild(dom);
        this._size = new Z.Size(dom.clientWidth, dom.clientHeight);
        dom.style.display = 'none';
        return this._size;
    },

    /**
     * Remove previous UI DOM if it has.
     *
     * @private
     */
    _removePrevDOM:function () {
        if (this.onDomRemove) {
            this.onDomRemove();
        }
        if (this._singleton()) {
            var map = this.getMap(),
                key = this._uiDomKey();
            if (map[key]) {
                Z.DomUtil.removeDomNode(map[key]);
                delete map[key];
            }
            delete this.__uiDOM;
        } else if (this.__uiDOM) {
            Z.DomUtil.removeDomNode(this.__uiDOM);
            delete this.__uiDOM;
        }
    },

    /**
     * generate the cache key to store the singletong UI DOM
     * @private
     * @return {String} cache key
     */
    _uiDomKey:function () {
        return '__ui_' + this._getClassName();
    },

    _singleton:function () {
        return this.options['single'];
    },

    _getUIContainer : function () {
        return this.getMap()._panels['ui'];
    },

    _getClassName:function () {
        for (var p in Z.ui) {
            if (Z.ui.hasOwnProperty(p)) {
                if (p === 'UIComponent') {
                    continue;
                }
                if (this instanceof (Z.ui[p])) {
                    return p;
                }
            }
        }
        return null;
    },

    _switchEvents: function (to) {
        var events = this._getDefaultEvents();
        if (this.getEvents) {
            Z.Util.extend(events, this.getEvents());
        }
        if (events) {
            var map = this.getMap();
            for (var p in events) {
                if (events.hasOwnProperty(p)) {
                    map[to](p, events[p], this);
                }
            }
        }
    },

    _getDefaultEvents: function () {
        return {
            'zooming' : this.onZooming,
            'zoomend' : this.onZoomEnd
        };
    },

    onZooming : function (param) {
        if (!this.isVisible() || !this.getDOM()) {
            return;
        }
        var dom = this.getDOM(),
            point = this.getMap().coordinateToViewPoint(this._coordinate),
            matrix = param['matrix']['view'];
        var p = matrix.applyToPointInstance(point)._add(this.options['dx'], this.options['dy']);
        if (this.getOffset) {
            var o = this.getOffset();
            if (o) { p._add(o); }
        }
        dom.style.left = p.x + 'px';
        dom.style.top  = p.y + 'px';
    },

    onZoomEnd : function () {
        if (!this.isVisible() || !this.getDOM()) {
            return;
        }
        var dom = this.getDOM(),
            p = this.getPosition();
        dom.style.left = p.x + 'px';
        dom.style.top  = p.y + 'px';
    }
});
<|endoftext|>


<commit_before>Bitcoin.ECKey = (function () {
  var ECDSA = Bitcoin.ECDSA;
  var ecparams = getSECCurveByName("secp256k1");
  var rng = new SecureRandom();

  var ECKey = function (input) {
    if (!input) {
      // Generate new key
      var n = ecparams.getN();
      this.priv = ECDSA.getBigRandom(n);
    } else if (input instanceof BigInteger) {
      // Input is a private key value
      this.priv = input;
    } else if (Bitcoin.Util.isArray(input)) {
      // Prepend zero byte to prevent interpretation as negative integer
      this.priv = BigInteger.fromByteArrayUnsigned(input);
    } else if ("string" == typeof input) {
      // Prepend zero byte to prevent interpretation as negative integer
      this.priv = BigInteger.fromByteArrayUnsigned(Crypto.util.base64ToBytes(input));
    }
  };

  ECKey.prototype.getPub = function () {
    if (this.pub) return this.pub;

    return this.pub = ecparams.getG().multiply(this.priv).getEncoded();
  };

  /**
   * Get the pubKeyHash for this key.
   *
   * This is calculated as RIPE160(SHA256([encoded pubkey])) and returned as
   * a byte array.
   */
  ECKey.prototype.getPubKeyHash = function () {
    if (this.pubKeyHash) return this.pubKeyHash;

    return this.pubKeyHash = Bitcoin.Util.sha256ripe160(this.getPub());
  };

  ECKey.prototype.getBitcoinAddress = function () {
    var hash = this.getPubKeyHash();
    var addr = new Bitcoin.Address(hash);
    return addr;
  };

  ECKey.prototype.setPub = function (pub) {
    this.pub = pub;
  };

  ECKey.prototype.toString = function (format) {
    if (format === "base64") {
      return Crypto.util.bytesToBase64(this.priv.toByteArrayUnsigned());
    } else {
      return Crypto.util.bytesToHex(this.priv.toByteArrayUnsigned());
    }
  };

  ECKey.prototype.sign = function (hash) {
    return ECDSA.sign(hash, this.priv);
  };

  ECKey.prototype.verify = function (hash, sig) {
    return ECDSA.verify(hash, sig, this.getPub());
  };

  return ECKey;
})();
<commit_msg>Added support for the Base58-encoded private key format<commit_after>Bitcoin.ECKey = (function () {
  var ECDSA = Bitcoin.ECDSA;
  var ecparams = getSECCurveByName("secp256k1");
  var rng = new SecureRandom();

  var ECKey = function (input) {
    if (!input) {
      // Generate new key
      var n = ecparams.getN();
      this.priv = ECDSA.getBigRandom(n);
    } else if (input instanceof BigInteger) {
      // Input is a private key value
      this.priv = input;
    } else if (Bitcoin.Util.isArray(input)) {
      // Prepend zero byte to prevent interpretation as negative integer
      this.priv = BigInteger.fromByteArrayUnsigned(input);
    } else if ("string" == typeof input) {
      if (input.length == 51 && input[0] == '5') {
        // Base58 encoded private key
        this.priv = BigInteger.fromByteArrayUnsigned(ECKey.decodeString(input));
      } else {
        // Prepend zero byte to prevent interpretation as negative integer
        this.priv = BigInteger.fromByteArrayUnsigned(Crypto.util.base64ToBytes(input));
      }
    }
  };

  ECKey.prototype.getPub = function () {
    if (this.pub) return this.pub;

    return this.pub = ecparams.getG().multiply(this.priv).getEncoded();
  };

  /**
   * Get the pubKeyHash for this key.
   *
   * This is calculated as RIPE160(SHA256([encoded pubkey])) and returned as
   * a byte array.
   */
  ECKey.prototype.getPubKeyHash = function () {
    if (this.pubKeyHash) return this.pubKeyHash;

    return this.pubKeyHash = Bitcoin.Util.sha256ripe160(this.getPub());
  };

  ECKey.prototype.getBitcoinAddress = function () {
    var hash = this.getPubKeyHash();
    var addr = new Bitcoin.Address(hash);
    return addr;
  };

  ECKey.prototype.getExportedPrivateKey = function () {
    var hash = this.priv.toByteArrayUnsigned();
    hash.unshift(0x80);
    var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes: true}), {asBytes: true});
    var bytes = hash.concat(checksum.slice(0,4));
    return Bitcoin.Base58.encode(bytes);
  };

  ECKey.prototype.setPub = function (pub) {
    this.pub = pub;
  };

  ECKey.prototype.toString = function (format) {
    if (format === "base64") {
      return Crypto.util.bytesToBase64(this.priv.toByteArrayUnsigned());
    } else {
      return Crypto.util.bytesToHex(this.priv.toByteArrayUnsigned());
    }
  };

  ECKey.prototype.sign = function (hash) {
    return ECDSA.sign(hash, this.priv);
  };

  ECKey.prototype.verify = function (hash, sig) {
    return ECDSA.verify(hash, sig, this.getPub());
  };

  /**
   * Parse an exported private key contained in a string.
   */
  ECKey.decodeString = function (string) {
    var bytes = Bitcoin.Base58.decode(string);

    var hash = bytes.slice(0, 33);

    var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes: true}), {asBytes: true});

    if (checksum[0] != bytes[33] ||
        checksum[1] != bytes[34] ||
        checksum[2] != bytes[35] ||
        checksum[3] != bytes[36]) {
      throw "Checksum validation failed!";
    }

    var version = hash.shift();

    if (version != 0x80) {
      throw "Version "+version+" not supported!";
    }

    return hash;
  };

  return ECKey;
})();
<|endoftext|>


<commit_before>
var UnitCell = UnitCell || require('./unitcell'); // eslint-disable-line

var ElMap = (function () {
'use strict';

function GridArray(dim) {
  this.dim = dim; // dimensions of the grid for the entire unit cell
  this.values = new Float32Array(dim[0] * dim[1] * dim[2]);
}

function modulo(a, b) {
  var reminder = a % b;
  return reminder >= 0 ? reminder : reminder + b;
}

GridArray.prototype.grid2index = function (i, j, k) {
  i = modulo(i, this.dim[0]);
  j = modulo(j, this.dim[1]);
  k = modulo(k, this.dim[2]);
  return this.dim[2] * (this.dim[1] * i + j) + k;
};

GridArray.prototype.grid2frac = function (i, j, k) {
  return [i / this.dim[0], j / this.dim[1], k / this.dim[2]];
};

// return grid coordinates (rounded down) for the given fractional coordinates
GridArray.prototype.frac2grid = function (xyz) {
  // at one point "| 0" here made extract_block() 40% faster on V8 3.14,
  // but I don't see any effect now
  return [Math.floor(xyz[0] * this.dim[0]) | 0,
          Math.floor(xyz[1] * this.dim[1]) | 0,
          Math.floor(xyz[2] * this.dim[2]) | 0];
};

GridArray.prototype.set_grid_value = function (i, j, k, value) {
  var idx = this.grid2index(i, j, k);
  this.values[idx] = value;
};

GridArray.prototype.get_grid_value = function (i, j, k) {
  var idx = this.grid2index(i, j, k);
  return this.values[idx];
};

function calculate_stddev(a) {
  var n = a.length;
  var sum = 0;
  var sq_sum = 0;
  for (var i = 0; i < n; i++) {
    sum += a[i];
    sq_sum += a[i] * a[i];
  }
  var mean = sum / n;
  var variance = sq_sum / n - mean * mean;
  return {mean: mean, dev: Math.sqrt(variance)};
}

function ElMap() {
  this.unit_cell = null;
  this.grid = null;
  this.mean = 0.0;
  this.rms = 1.0;
}

ElMap.prototype.abs_level = function (sigma) {
  return sigma * this.rms + this.mean;
};

// http://www.ccp4.ac.uk/html/maplib.html#description
ElMap.prototype.from_ccp4 = function (buf) {
  //console.log('buf type: ' + Object.prototype.toString.call(buf));
  var iview = new Int32Array(buf);
  var fview = new Float32Array(buf);
  // map has 3 dimensions referred to as columns (fastest changing), rows
  // and sections (c-r-s)
  var n_crs = [iview[0], iview[1], iview[2]];
  this.mode = iview[3];
  if (this.mode !== 2) {
    throw Error('Only Mode 2 (32-bit float) of CCP4 map is supported.');
  }
  var start = [iview[4], iview[5], iview[6]];
  var n_grid = [iview[7], iview[8], iview[9]];
  this.unit_cell = new UnitCell(fview[10], fview[11], fview[12],
                                fview[13], fview[14], fview[15]);
  var c = iview[16] - 1;  // MAPC - axis corresp to cols (1,2,3 for X,Y,Z)
  var r = iview[17] - 1;  // MAPR - axis corresp to rows
  var s = iview[18] - 1;  // MAPS - axis corresp to sections

  var order = [0, 0, 0];
  order[c] = 0;
  order[r] = 1;
  order[s] = 2;
  c = order[0]; r = order[1]; s = order[2];
  /*
  console.log(c, r, s);
  */

  this.min = fview[19];
  this.max = fview[20];
  this.mean = fview[21];  // is it reliable?
  this.sg_number = iview[22];
  this.lskflg = iview[24];
  this.rms = fview[54]; // is it reliable?
  //console.log('map mean: ' + this.mean.toFixed(4) +
  //            '  rms: ' + this.rms.toFixed(4));
  var n_real = [n_crs[c], n_crs[r], n_crs[s]];
  this.grid = new GridArray(n_grid);
  var nsymbt = iview[23]; // size of extended header in bytes
  if (1024 + nsymbt + 4 * n_crs[0] * n_crs[1] * n_crs[2] !== buf.byteLength) {
    throw Error('ccp4 file too short or too long');
  }
  if (nsymbt % 4 !== 0) {
    throw Error('CCP4 map with NSYMBT not divisible by 4 is not supported.');
  }
  var idx = 256 + nsymbt / 4 | 0;
  var end = [start[0] + n_crs[0], start[1] + n_crs[1], start[2] + n_crs[2]];
  var it = [0, 0, 0];
  for (it[2] = start[2]; it[2] < end[2]; it[2]++) {
    for (it[1] = start[1]; it[1] < end[1]; it[1]++) {
      for (it[0] = start[0]; it[0] < end[0]; it[0]++) {
        this.grid.set_grid_value(it[c], it[r], it[s], fview[idx]);
        idx++;
      }
    }
  }
};

// DSN6 MAP FORMAT
// http://www.uoxray.uoregon.edu/tnt/manual/node104.html
// This format is much different from CCP4/MRC maps, and was obviously
// designed for vastly more primitive computers.  Since density values are
// stored as bytes rather than (4-byte) floates, it has the big advantage
// of being significantly more compact than CCP4 maps.
ElMap.prototype.from_dsn6 = function (buf) {
  //console.log('buf type: ' + Object.prototype.toString.call(buf));
  var u8data = new Uint8Array(buf);
  var iview = new Int16Array(u8data.buffer);
  if (iview[18] !== 100) {
    var len = iview.length;  // or only header, 256?
    for (var n = 0; n < len; n++) {
      // swapping bytes with Uint8Array like this:
      // var tmp=u8data[n*2]; u8data[n*2]=u8data[n*2+1]; u8data[n*2+1]=tmp;
      // was slowing down this whole function 5x times (!?) on V8.
      var val = iview[n];
      iview[n] = ((val & 0xff) << 8) | ((val >> 8) & 0xff);
    }
  }
  if (iview[18] !== 100) {
    throw Error('Endian swap failed');
  }
  var origin = [iview[0], iview[1], iview[2]];
  var n_real = [iview[3], iview[4], iview[5]];
  var n_grid = [iview[6], iview[7], iview[8]];
  var cell_mult = 1.0 / iview[17];
  this.unit_cell = new UnitCell(cell_mult * iview[9],
                                cell_mult * iview[10],
                                cell_mult * iview[11],
                                cell_mult * iview[12],
                                cell_mult * iview[13],
                                cell_mult * iview[14]);
  this.grid = new GridArray(n_grid);
  var prod = iview[15] / 100;
  var plus = iview[16];
  //var data_scale_factor = iview[15] / iview[18] + iview[16];
  // bricks have 512 (8x8x8) values
  var offset = 512;
  var n_blocks = [Math.ceil(n_real[0] / 8),
                  Math.ceil(n_real[1] / 8),
                  Math.ceil(n_real[2] / 8)];
  for (var zz = 0; zz < n_blocks[2]; zz++) {
    for (var yy = 0; yy < n_blocks[1]; yy++) {
      for (var xx = 0; xx < n_blocks[0]; xx++) { // loop over bricks
        for (var k = 0; k < 8; k++) {
          var z = 8 * zz + k;
          for (var j = 0; j < 8; j++) {
            var y = 8 * yy + j;
            for (var i = 0; i < 8; i++) { // loop inside brick
              var x = 8 * xx + i;
              if (x < n_real[0] && y < n_real[1] && z < n_real[2]) {
                var density = (u8data[offset] - plus) / prod;
                offset++;
                this.grid.set_grid_value(origin[0] + x,
                                         origin[1] + y,
                                         origin[2] + z, density);
              } else {
                offset += 8 - i;
                break;
              }
            }
          }
        }
      }
    }
  }
  var d = calculate_stddev(this.grid.values);
  this.mean = d.mean;
  this.rms = d.dev;
  //this.show_debug_info();
};

ElMap.prototype.show_debug_info = function () {
  console.log('unit cell: ' + this.unit_cell.parameters.join(', '));
  console.log('grid: ' + this.grid.dim);
};

// Extract a block of density for calculating an isosurface using the
// separate marching cubes implementation.
ElMap.prototype.extract_block = function (radius, center) {
  var grid = this.grid;
  var unit_cell = this.unit_cell;
  var xyz_min = [center[0] - radius, center[1] - radius, center[2] - radius];
  var xyz_max = [center[0] + radius, center[1] + radius, center[2] + radius];
  var frac_min = unit_cell.fractionalize(xyz_min);
  var frac_max = unit_cell.fractionalize(xyz_max);
  var grid_min = grid.frac2grid(frac_min);
  var grid_max = grid.frac2grid(frac_max);
  var nx = grid_max[0] - grid_min[0] + 1;
  var ny = grid_max[1] - grid_min[1] + 1;
  var nz = grid_max[2] - grid_min[2] + 1;
  var points = [];
  var values = [];
  for (var i = grid_min[0]; i <= grid_max[0]; i++) {
    for (var j = grid_min[1]; j <= grid_max[1]; j++) {
      for (var k = grid_min[2]; k <= grid_max[2]; k++) {
        var frac = grid.grid2frac(i, j, k);
        var orth = unit_cell.orthogonalize(frac);
        points.push(orth);
        var map_value = grid.get_grid_value(i, j, k);
        values.push(map_value);
      }
    }
  }
  this.block = {points: points, values: values, size: [nx, ny, nz]};
};

return ElMap;
})();

if (typeof module !== 'undefined') { module.exports = ElMap; }
<commit_msg>optimization - probably only for some js engines<commit_after>
var UnitCell = UnitCell || require('./unitcell'); // eslint-disable-line

var ElMap = (function () {
'use strict';

function GridArray(dim) {
  this.dim = dim; // dimensions of the grid for the entire unit cell
  // in some browsers typed array are seriously slow
  //this.values = new Float32Array(dim[0] * dim[1] * dim[2]);
  this.values = [];
  for (var i = 0; i < dim[0] * dim[1] * dim[2]; i++) {
    this.values.push(0.0);
  }
}

function modulo(a, b) {
  var reminder = a % b;
  return reminder >= 0 ? reminder : reminder + b;
}

GridArray.prototype.grid2index = function (i, j, k) {
  i = modulo(i, this.dim[0]);
  j = modulo(j, this.dim[1]);
  k = modulo(k, this.dim[2]);
  return this.dim[2] * (this.dim[1] * i + j) + k;
};

GridArray.prototype.grid2frac = function (i, j, k) {
  return [i / this.dim[0], j / this.dim[1], k / this.dim[2]];
};

// return grid coordinates (rounded down) for the given fractional coordinates
GridArray.prototype.frac2grid = function (xyz) {
  // at one point "| 0" here made extract_block() 40% faster on V8 3.14,
  // but I don't see any effect now
  return [Math.floor(xyz[0] * this.dim[0]) | 0,
          Math.floor(xyz[1] * this.dim[1]) | 0,
          Math.floor(xyz[2] * this.dim[2]) | 0];
};

GridArray.prototype.set_grid_value = function (i, j, k, value) {
  var idx = this.grid2index(i, j, k);
  this.values[idx] = value;
};

GridArray.prototype.get_grid_value = function (i, j, k) {
  var idx = this.grid2index(i, j, k);
  return this.values[idx];
};

function calculate_stddev(a) {
  var n = a.length;
  var sum = 0;
  var sq_sum = 0;
  for (var i = 0; i < n; i++) {
    sum += a[i];
    sq_sum += a[i] * a[i];
  }
  var mean = sum / n;
  var variance = sq_sum / n - mean * mean;
  return {mean: mean, dev: Math.sqrt(variance)};
}

function ElMap() {
  this.unit_cell = null;
  this.grid = null;
  this.mean = 0.0;
  this.rms = 1.0;
}

ElMap.prototype.abs_level = function (sigma) {
  return sigma * this.rms + this.mean;
};

// http://www.ccp4.ac.uk/html/maplib.html#description
ElMap.prototype.from_ccp4 = function (buf) {
  //console.log('buf type: ' + Object.prototype.toString.call(buf));
  var iview = new Int32Array(buf);
  var fview = new Float32Array(buf);
  // map has 3 dimensions referred to as columns (fastest changing), rows
  // and sections (c-r-s)
  var n_crs = [iview[0], iview[1], iview[2]];
  this.mode = iview[3];
  if (this.mode !== 2) {
    throw Error('Only Mode 2 (32-bit float) of CCP4 map is supported.');
  }
  var start = [iview[4], iview[5], iview[6]];
  var n_grid = [iview[7], iview[8], iview[9]];
  this.unit_cell = new UnitCell(fview[10], fview[11], fview[12],
                                fview[13], fview[14], fview[15]);
  var c = iview[16] - 1;  // MAPC - axis corresp to cols (1,2,3 for X,Y,Z)
  var r = iview[17] - 1;  // MAPR - axis corresp to rows
  var s = iview[18] - 1;  // MAPS - axis corresp to sections

  var order = [0, 0, 0];
  order[c] = 0;
  order[r] = 1;
  order[s] = 2;
  c = order[0]; r = order[1]; s = order[2];
  /*
  console.log(c, r, s);
  */

  this.min = fview[19];
  this.max = fview[20];
  this.mean = fview[21];  // is it reliable?
  this.sg_number = iview[22];
  this.lskflg = iview[24];
  this.rms = fview[54]; // is it reliable?
  //console.log('map mean: ' + this.mean.toFixed(4) +
  //            '  rms: ' + this.rms.toFixed(4));
  var n_real = [n_crs[c], n_crs[r], n_crs[s]];
  this.grid = new GridArray(n_grid);
  var nsymbt = iview[23]; // size of extended header in bytes
  if (1024 + nsymbt + 4 * n_crs[0] * n_crs[1] * n_crs[2] !== buf.byteLength) {
    throw Error('ccp4 file too short or too long');
  }
  if (nsymbt % 4 !== 0) {
    throw Error('CCP4 map with NSYMBT not divisible by 4 is not supported.');
  }
  var idx = 256 + nsymbt / 4 | 0;
  var end = [start[0] + n_crs[0], start[1] + n_crs[1], start[2] + n_crs[2]];
  var it = [0, 0, 0];
  for (it[2] = start[2]; it[2] < end[2]; it[2]++) {
    for (it[1] = start[1]; it[1] < end[1]; it[1]++) {
      for (it[0] = start[0]; it[0] < end[0]; it[0]++) {
        this.grid.set_grid_value(it[c], it[r], it[s], fview[idx]);
        idx++;
      }
    }
  }
};

// DSN6 MAP FORMAT
// http://www.uoxray.uoregon.edu/tnt/manual/node104.html
// This format is much different from CCP4/MRC maps, and was obviously
// designed for vastly more primitive computers.  Since density values are
// stored as bytes rather than (4-byte) floates, it has the big advantage
// of being significantly more compact than CCP4 maps.
ElMap.prototype.from_dsn6 = function (buf) {
  //console.log('buf type: ' + Object.prototype.toString.call(buf));
  var u8data = new Uint8Array(buf);
  var iview = new Int16Array(u8data.buffer);
  if (iview[18] !== 100) {
    var len = iview.length;  // or only header, 256?
    for (var n = 0; n < len; n++) {
      // swapping bytes with Uint8Array like this:
      // var tmp=u8data[n*2]; u8data[n*2]=u8data[n*2+1]; u8data[n*2+1]=tmp;
      // was slowing down this whole function 5x times (!?) on V8.
      var val = iview[n];
      iview[n] = ((val & 0xff) << 8) | ((val >> 8) & 0xff);
    }
  }
  if (iview[18] !== 100) {
    throw Error('Endian swap failed');
  }
  var origin = [iview[0], iview[1], iview[2]];
  var n_real = [iview[3], iview[4], iview[5]];
  var n_grid = [iview[6], iview[7], iview[8]];
  var cell_mult = 1.0 / iview[17];
  this.unit_cell = new UnitCell(cell_mult * iview[9],
                                cell_mult * iview[10],
                                cell_mult * iview[11],
                                cell_mult * iview[12],
                                cell_mult * iview[13],
                                cell_mult * iview[14]);
  this.grid = new GridArray(n_grid);
  var prod = iview[15] / 100;
  var plus = iview[16];
  //var data_scale_factor = iview[15] / iview[18] + iview[16];
  // bricks have 512 (8x8x8) values
  var offset = 512;
  var n_blocks = [Math.ceil(n_real[0] / 8),
                  Math.ceil(n_real[1] / 8),
                  Math.ceil(n_real[2] / 8)];
  for (var zz = 0; zz < n_blocks[2]; zz++) {
    for (var yy = 0; yy < n_blocks[1]; yy++) {
      for (var xx = 0; xx < n_blocks[0]; xx++) { // loop over bricks
        for (var k = 0; k < 8; k++) {
          var z = 8 * zz + k;
          for (var j = 0; j < 8; j++) {
            var y = 8 * yy + j;
            for (var i = 0; i < 8; i++) { // loop inside brick
              var x = 8 * xx + i;
              if (x < n_real[0] && y < n_real[1] && z < n_real[2]) {
                var density = (u8data[offset] - plus) / prod;
                offset++;
                this.grid.set_grid_value(origin[0] + x,
                                         origin[1] + y,
                                         origin[2] + z, density);
              } else {
                offset += 8 - i;
                break;
              }
            }
          }
        }
      }
    }
  }
  var d = calculate_stddev(this.grid.values);
  this.mean = d.mean;
  this.rms = d.dev;
  //this.show_debug_info();
};

ElMap.prototype.show_debug_info = function () {
  console.log('unit cell: ' + this.unit_cell.parameters.join(', '));
  console.log('grid: ' + this.grid.dim);
};

// Extract a block of density for calculating an isosurface using the
// separate marching cubes implementation.
ElMap.prototype.extract_block = function (radius, center) {
  var grid = this.grid;
  var unit_cell = this.unit_cell;
  var xyz_min = [center[0] - radius, center[1] - radius, center[2] - radius];
  var xyz_max = [center[0] + radius, center[1] + radius, center[2] + radius];
  var frac_min = unit_cell.fractionalize(xyz_min);
  var frac_max = unit_cell.fractionalize(xyz_max);
  var grid_min = grid.frac2grid(frac_min);
  var grid_max = grid.frac2grid(frac_max);
  var nx = grid_max[0] - grid_min[0] + 1;
  var ny = grid_max[1] - grid_min[1] + 1;
  var nz = grid_max[2] - grid_min[2] + 1;
  var points = [];
  var values = [];
  for (var i = grid_min[0]; i <= grid_max[0]; i++) {
    for (var j = grid_min[1]; j <= grid_max[1]; j++) {
      for (var k = grid_min[2]; k <= grid_max[2]; k++) {
        var frac = grid.grid2frac(i, j, k);
        var orth = unit_cell.orthogonalize(frac);
        points.push(orth);
        var map_value = grid.get_grid_value(i, j, k);
        values.push(map_value);
      }
    }
  }
  this.block = {points: points, values: values, size: [nx, ny, nz]};
};

return ElMap;
})();

if (typeof module !== 'undefined') { module.exports = ElMap; }
<|endoftext|>


<commit_before>function insertAtPosition(position,node)
{
    if (position.node.nodeType == Node.ELEMENT_NODE) {
        if (position.offset == position.node.childNodes.length)
            DOM.appendChild(position.node,node);
        else
            DOM.insertBefore(position.node,node,position.node.childNodes[position.offset]);
    }
    else if (position.node.nodeType == Node.TEXT_NODE) {
        var newText = DOM.createTextNode(document,position.node.nodeValue.slice(position.offset));
        position.node.nodeValue = position.node.nodeValue.slice(0,position.offset);
        DOM.insertBefore(position.node.parentNode,newText,position.node.nextSibling);
        DOM.insertBefore(position.node.parentNode,node,position.node.nextSibling);
    }
}

function insertTextAtPosition(position,str)
{
    if (position.node.nodeType == Node.ELEMENT_NODE) {
        var before = position.node.childNodes[position.offset-1];
        var after = position.node.childNodes[position.offset];
        if ((after != null) && (after.nodeType == Node.TEXT_NODE))
            position = new Position(after,0);
        else if ((before != null) && (before.nodeType == Node.TEXT_NODE))
            position = new Position(before,before.nodeValue.length);
    }
    if (position.node.nodeType == Node.ELEMENT_NODE) {
        insertAtPosition(position,DOM.createTextNode(document,str));
    }
    else if (position.node.nodeType == Node.TEXT_NODE) {
        position.node.nodeValue = position.node.nodeValue.slice(0,position.offset) + str +
                                  position.node.nodeValue.slice(position.offset);
    }
}

function showRangeAsBrackets(range)
{
    if (range.isEmpty()) {
        insertTextAtPosition(range.end,"[]",true);
    }
    else {
        insertTextAtPosition(range.end,"]",true);
        insertTextAtPosition(range.start,"[",true);
    }
}

function removeIds()
{
    recurse(document.body);

    function recurse(node)
    {
        if (node.nodeType == Node.ELEMENT_NODE) {
            node.removeAttribute("id");
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                recurse(child);
        }
    }
}

function selectNode(node)
{
    var offset = DOM.nodeOffset(node);
    Selection.setSelectionRange(new Range(node.parentNode,offset,node.parentNode,offset+1));
}

function removeWhitespaceAndCommentNodes(node)
{
    if (isWhitespaceTextNode(node) || (node.nodeType == Node.COMMENT_NODE)) {
        DOM.deleteNode(node);
    }
    else {
        var next;
        for (var child = node.firstChild; child != null; child = next) {
            next = child.nextSibling;
            removeWhitespaceAndCommentNodes(child);
        }
    }
}

// selectionWrapElement() and selectionUnwrapElement() used to be in formatting.js but have
// now been made obselete by the addition of applyFormattingChanges(). However there are still
// a few tests which use them.
function selectionWrapElement(elementName)
{
    if (elementName == "B")
        Formatting.applyFormattingChanges(null,{"font-weight": "bold"});
    else if (elementName == "I")
        Formatting.applyFormattingChanges(null,{"font-style": "italic"});
    else if (elementName == "U")
        Formatting.applyFormattingChanges(null,{"text-decoration": "underline"});
}

function selectionUnwrapElement(elementName)
{
    if (elementName == "B")
        Formatting.applyFormattingChanges(null,{"font-weight": null});
    else if (elementName == "I")
        Formatting.applyFormattingChanges(null,{"font-style": null});
    else if (elementName == "U")
        Formatting.applyFormattingChanges(null,{"text-decoration": null});
}

function showEmptyTextNodes()
{
    recurse(document);

    function recurse(node)
    {
        if ((node.nodeType == Node.TEXT_NODE) && (node.nodeValue.length == 0))
            node.nodeValue = "*";
        for (var child = node.firstChild; child != null; child = child.nextSibling)
            recurse(child);
    }
}

function showClipboard(clipboard)
{
    var html = clipboard["text/html"];
    var text = clipboard["text/plain"];

    if ((html.length == 0) || (html.charAt(html.length-1) != "\n"))
        html += "\n";
    if ((text.length == 0) || (text.charAt(text.length-1) != "\n"))
        text += "\n";

    return "text/html\n"+
           "---------\n"+
           "\n"+
           html+
           "\n"+
           "text/plain\n"+
           "----------\n"+
           "\n"+
           text;
}

function setNumbering(enabled)
{
    recurse(document.body,enabled);
    PostponedActions.perform();

    function recurse(node,enabled)
    {
        if (isHeadingNode(node)) {
            Outline.setNumbered(node.getAttribute("id"),enabled);
        }
        else {
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                recurse(child,enabled);
        }
    }
}
<commit_msg>Changed setNumbering() to apply to figures and tables, as well as headings<commit_after>function insertAtPosition(position,node)
{
    if (position.node.nodeType == Node.ELEMENT_NODE) {
        if (position.offset == position.node.childNodes.length)
            DOM.appendChild(position.node,node);
        else
            DOM.insertBefore(position.node,node,position.node.childNodes[position.offset]);
    }
    else if (position.node.nodeType == Node.TEXT_NODE) {
        var newText = DOM.createTextNode(document,position.node.nodeValue.slice(position.offset));
        position.node.nodeValue = position.node.nodeValue.slice(0,position.offset);
        DOM.insertBefore(position.node.parentNode,newText,position.node.nextSibling);
        DOM.insertBefore(position.node.parentNode,node,position.node.nextSibling);
    }
}

function insertTextAtPosition(position,str)
{
    if (position.node.nodeType == Node.ELEMENT_NODE) {
        var before = position.node.childNodes[position.offset-1];
        var after = position.node.childNodes[position.offset];
        if ((after != null) && (after.nodeType == Node.TEXT_NODE))
            position = new Position(after,0);
        else if ((before != null) && (before.nodeType == Node.TEXT_NODE))
            position = new Position(before,before.nodeValue.length);
    }
    if (position.node.nodeType == Node.ELEMENT_NODE) {
        insertAtPosition(position,DOM.createTextNode(document,str));
    }
    else if (position.node.nodeType == Node.TEXT_NODE) {
        position.node.nodeValue = position.node.nodeValue.slice(0,position.offset) + str +
                                  position.node.nodeValue.slice(position.offset);
    }
}

function showRangeAsBrackets(range)
{
    if (range.isEmpty()) {
        insertTextAtPosition(range.end,"[]",true);
    }
    else {
        insertTextAtPosition(range.end,"]",true);
        insertTextAtPosition(range.start,"[",true);
    }
}

function removeIds()
{
    recurse(document.body);

    function recurse(node)
    {
        if (node.nodeType == Node.ELEMENT_NODE) {
            node.removeAttribute("id");
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                recurse(child);
        }
    }
}

function selectNode(node)
{
    var offset = DOM.nodeOffset(node);
    Selection.setSelectionRange(new Range(node.parentNode,offset,node.parentNode,offset+1));
}

function removeWhitespaceAndCommentNodes(node)
{
    if (isWhitespaceTextNode(node) || (node.nodeType == Node.COMMENT_NODE)) {
        DOM.deleteNode(node);
    }
    else {
        var next;
        for (var child = node.firstChild; child != null; child = next) {
            next = child.nextSibling;
            removeWhitespaceAndCommentNodes(child);
        }
    }
}

// selectionWrapElement() and selectionUnwrapElement() used to be in formatting.js but have
// now been made obselete by the addition of applyFormattingChanges(). However there are still
// a few tests which use them.
function selectionWrapElement(elementName)
{
    if (elementName == "B")
        Formatting.applyFormattingChanges(null,{"font-weight": "bold"});
    else if (elementName == "I")
        Formatting.applyFormattingChanges(null,{"font-style": "italic"});
    else if (elementName == "U")
        Formatting.applyFormattingChanges(null,{"text-decoration": "underline"});
}

function selectionUnwrapElement(elementName)
{
    if (elementName == "B")
        Formatting.applyFormattingChanges(null,{"font-weight": null});
    else if (elementName == "I")
        Formatting.applyFormattingChanges(null,{"font-style": null});
    else if (elementName == "U")
        Formatting.applyFormattingChanges(null,{"text-decoration": null});
}

function showEmptyTextNodes()
{
    recurse(document);

    function recurse(node)
    {
        if ((node.nodeType == Node.TEXT_NODE) && (node.nodeValue.length == 0))
            node.nodeValue = "*";
        for (var child = node.firstChild; child != null; child = child.nextSibling)
            recurse(child);
    }
}

function showClipboard(clipboard)
{
    var html = clipboard["text/html"];
    var text = clipboard["text/plain"];

    if ((html.length == 0) || (html.charAt(html.length-1) != "\n"))
        html += "\n";
    if ((text.length == 0) || (text.charAt(text.length-1) != "\n"))
        text += "\n";

    return "text/html\n"+
           "---------\n"+
           "\n"+
           html+
           "\n"+
           "text/plain\n"+
           "----------\n"+
           "\n"+
           text;
}

function setNumbering(enabled)
{
    recurse(document.body,enabled);
    PostponedActions.perform();

    function recurse(node,enabled)
    {
        if (isHeadingNode(node) || isFigureNode(node) || isTableNode(node)) {
            Outline.setNumbered(node.getAttribute("id"),enabled);
        }
        else {
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                recurse(child,enabled);
        }
    }
}
<|endoftext|>


<commit_before>"use strict";

var Entry = {};

module.exports = Entry;
global.Entry = Entry;

require("./class/container.js")
require("./class/dialog.js")
require("./class/doneProject.js")
require("./class/engine.js")
require("./class/entity.js")
require("./class/function.js")
require("./class/helper.js")
require("./class/hw.js")
require("./class/hw_monitor.js")
require("./class/object.js")
require("./class/painter.js")
require("./class/pdf.js")
require("./class/playground.js")
require("./class/popup.js")
require("./class/popup_helper.js")
require("./class/popup_list.js")
require("./class/project.js")
require("./class/property_panel.js")
require("./class/reporter.js")
require("./class/scene.js")
require("./class/script.js")
require("./class/stage.js")
require("./class/stamp_entity.js")
require("./class/toast.js")
require("./class/variable.js")
require("./class/variable_container.js")
require("./command/command.js")
require("./command/commander.js")
require("./core/collection.js")
require("./core/db.js")
require("./core/dom.js")
require("./core/event.js")
require("./core/model.js")
require("./core/observer.js")
require("./core/svg.js")
require("./extensions/extension.js")
require("./extensions/target_checker.js")
require("./log/activity.js")
require("./log/activityReporter.js")
require("./log/recorder.js")
require("./log/state.js")
require("./log/state_manager.js")
require("./model/block_model.js")
require("./model/block_render_model.js")
require("./model/box_model.js")
require("./model/drag_instance.js")
require("./model/thread_model.js")
require("./parser-no/block.js")
require("./parser-no/js.js")
require("./parser-no/parser.js")
require("./playground/block.js")
require("./playground/block_entry.js")
require("./playground/basic_block.js")
require("./playground/block_entry_mini.js")
require("./playground/block_menu.js")
require("./playground/block_menu_scroll.js")
require("./playground/block_view.js")
require("./playground/board.js")
require("./playground/code.js")
require("./playground/code_view.js")
require("./playground/connection_ripple.js")
require("./playground/executors.js")
require("./playground/globalSvg.js")
require("./playground/mutator.js")
require("./playground/renderView.js")
require("./playground/scroll.js")
require("./playground/skeleton.js")
require("./playground/skinner.js")
require("./playground/thread.js")
require("./playground/thread_view.js")
require("./playground/trashcan.js")
require("./playground/vim.js")
require("./playground/workspace.js")
require("./textcoding/parser.js")
require("./util/block_driver.js")
require("./util/contextmenu.js")
require("./util/curtain.js")
require("./util/fuzzy.js")
require("./util/init.js")
require("./util/loader.js")
require("./util/popup.js")
require("./util/restrictor.js")
require("./util/static.js")
require("./util/toast.js")
require("./util/tooltip.js")
require("./util/tvCast.js")
require("./util/utils.js")
require("./util/youtube.js")
require("./command/commands/block.js")
require("./command/commands/container.js")
require("./command/commands/engine.js")
require("./command/commands/object.js")
require("./command/commands/painter.js")
require("./command/commands/playground.js")
require("./command/commands/textbox.js")
require("./command/commands/variableContainer.js")
require("./playground/blocks/block_albert.js")
require("./playground/blocks/block_altino.js")
require("./playground/blocks/block_arduino.js")
require("./playground/blocks/block_bitbrick.js")
require("./playground/blocks/block_blacksmith.js")
require("./playground/blocks/block_byrobot_dronefighter_controller.js")
require("./playground/blocks/block_byrobot_dronefighter_drive.js")
require("./playground/blocks/block_byrobot_dronefighter_flight.js")
require("./playground/blocks/block_byrobot_petrone_v2_controller.js")
require("./playground/blocks/block_byrobot_petrone_v2_drive.js")
require("./playground/blocks/block_byrobot_petrone_v2_flight.js")
require("./playground/blocks/block_chocopi.js")
require("./playground/blocks/block_cobl.js")
require("./playground/blocks/block_coconut.js")
require("./playground/blocks/block_codeino.js")
require("./playground/blocks/block_codestar.js")
require("./playground/blocks/block_dadublock.js")
require("./playground/blocks/block_edumaker.js")
require("./playground/blocks/block_ev3.js")
require("./playground/blocks/block_hamster.js")
require("./playground/blocks/block_hummingbird.js")
require("./playground/blocks/block_iboard.js")
require("./playground/blocks/block_jdkit.js")
require("./playground/blocks/block_mechatronics_4d.js")
require("./playground/blocks/block_modi.js")
require("./playground/blocks/block_neobot.js")
require("./playground/blocks/block_neobot_sensor_theme.js")
require("./playground/blocks/block_roborobo.js")
require("./playground/blocks/block_robotis.js")
require("./playground/blocks/block_robotori.js")
require("./playground/blocks/block_truerobot.js")
require("./playground/blocks/block_turtle.js")
require("./playground/blocks/block_xbot.js")
require("./playground/extension/extension.js")
require("./playground/extension/guide.js")
require("./playground/extension/side_tag.js")
require("./playground/field/angle.js")
require("./playground/field/block.js")
require("./playground/field/color.js")
require("./playground/field/dropdown.js")
require("./playground/field/dropdownDynamic.js")
require("./playground/field/field.js")
require("./playground/field/image.js")
require("./playground/field/indicator.js")
require("./playground/field/keyboardInput.js")
require("./playground/field/lineBreak.js")
require("./playground/field/output.js")
require("./playground/field/statement.js")
require("./playground/field/text.js")
require("./playground/field/textInput.js")
require("./textcoding/ast/jsAstGenerator.js")
require("./textcoding/ast/pyAstGenerator.js")
require("./textcoding/data_processing/map.js")
require("./textcoding/data_processing/queue.js")
require("./textcoding/error/textCodingError.js")
require("./textcoding/hint/python.js")
require("./textcoding/static/codeMap.js")
require("./textcoding/static/keyboardCode.js")
require("./textcoding/util/console.js")
require("./textcoding/util/textCodingUtil.js")

window.Entry = Entry;<commit_msg>remove .js extension, add semicolon<commit_after>"use strict";

var Entry = {};

module.exports = Entry;
global.Entry = Entry;

require("./class/container");
require("./class/dialog");
require("./class/doneProject");
require("./class/engine");
require("./class/entity");
require("./class/function");
require("./class/helper");
require("./class/hw");
require("./class/hw_monitor");
require("./class/object");
require("./class/painter");
require("./class/pdf");
require("./class/playground");
require("./class/popup");
require("./class/popup_helper");
require("./class/popup_list");
require("./class/project");
require("./class/property_panel");
require("./class/reporter");
require("./class/scene");
require("./class/script");
require("./class/stage");
require("./class/stamp_entity");
require("./class/toast");
require("./class/variable");
require("./class/variable_container");
require("./command/command");
require("./command/commander");
require("./core/collection");
require("./core/db");
require("./core/dom");
require("./core/event");
require("./core/model");
require("./core/observer");
require("./core/svg");
require("./extensions/extension");
require("./extensions/target_checker");
require("./log/activity");
require("./log/activityReporter");
require("./log/recorder");
require("./log/state");
require("./log/state_manager");
require("./model/block_model");
require("./model/block_render_model");
require("./model/box_model");
require("./model/drag_instance");
require("./model/thread_model");
require("./parser-no/block");
require("./parser-no/js");
require("./parser-no/parser");
require("./playground/block");
require("./playground/block_entry");
require("./playground/basic_block");
require("./playground/block_entry_mini");
require("./playground/block_menu");
require("./playground/block_menu_scroll");
require("./playground/block_view");
require("./playground/board");
require("./playground/code");
require("./playground/code_view");
require("./playground/connection_ripple");
require("./playground/executors");
require("./playground/globalSvg");
require("./playground/mutator");
require("./playground/renderView");
require("./playground/scroll");
require("./playground/skeleton");
require("./playground/skinner");
require("./playground/thread");
require("./playground/thread_view");
require("./playground/trashcan");
require("./playground/vim");
require("./playground/workspace");
require("./textcoding/parser");
require("./util/block_driver");
require("./util/contextmenu");
require("./util/curtain");
require("./util/fuzzy");
require("./util/init");
require("./util/loader");
require("./util/popup");
require("./util/restrictor");
require("./util/static");
require("./util/toast");
require("./util/tooltip");
require("./util/tvCast");
require("./util/utils");
require("./util/youtube");
require("./command/commands/block");
require("./command/commands/container");
require("./command/commands/engine");
require("./command/commands/object");
require("./command/commands/painter");
require("./command/commands/playground");
require("./command/commands/textbox");
require("./command/commands/variableContainer");
require("./playground/blocks/block_albert");
require("./playground/blocks/block_altino");
require("./playground/blocks/block_arduino");
require("./playground/blocks/block_bitbrick");
require("./playground/blocks/block_blacksmith");
require("./playground/blocks/block_byrobot_dronefighter_controller");
require("./playground/blocks/block_byrobot_dronefighter_drive");
require("./playground/blocks/block_byrobot_dronefighter_flight");
require("./playground/blocks/block_byrobot_petrone_v2_controller");
require("./playground/blocks/block_byrobot_petrone_v2_drive");
require("./playground/blocks/block_byrobot_petrone_v2_flight");
require("./playground/blocks/block_chocopi");
require("./playground/blocks/block_cobl");
require("./playground/blocks/block_coconut");
require("./playground/blocks/block_codeino");
require("./playground/blocks/block_codestar");
require("./playground/blocks/block_dadublock");
require("./playground/blocks/block_edumaker");
require("./playground/blocks/block_ev3");
require("./playground/blocks/block_hamster");
require("./playground/blocks/block_hummingbird");
require("./playground/blocks/block_iboard");
require("./playground/blocks/block_jdkit");
require("./playground/blocks/block_mechatronics_4d");
require("./playground/blocks/block_modi");
require("./playground/blocks/block_neobot");
require("./playground/blocks/block_neobot_sensor_theme");
require("./playground/blocks/block_roborobo");
require("./playground/blocks/block_robotis");
require("./playground/blocks/block_robotori");
require("./playground/blocks/block_truerobot");
require("./playground/blocks/block_turtle");
require("./playground/blocks/block_xbot");
require("./playground/extension/extension");
require("./playground/extension/guide");
require("./playground/extension/side_tag");
require("./playground/field/angle");
require("./playground/field/block");
require("./playground/field/color");
require("./playground/field/dropdown");
require("./playground/field/dropdownDynamic");
require("./playground/field/field");
require("./playground/field/image");
require("./playground/field/indicator");
require("./playground/field/keyboardInput");
require("./playground/field/lineBreak");
require("./playground/field/output");
require("./playground/field/statement");
require("./playground/field/text");
require("./playground/field/textInput");
require("./textcoding/ast/jsAstGenerator");
require("./textcoding/ast/pyAstGenerator");
require("./textcoding/data_processing/map");
require("./textcoding/data_processing/queue");
require("./textcoding/error/textCodingError");
require("./textcoding/hint/python");
require("./textcoding/static/codeMap");
require("./textcoding/static/keyboardCode");
require("./textcoding/util/console");
require("./textcoding/util/textCodingUtil");

window.Entry = Entry;
<|endoftext|>


<commit_before>import Document from './Document';
import Outline from './Outline';
import Page from './Page';

const pdfjs = require('pdfjs-dist');
require('pdfjs-dist/web/compatibility');

pdfjs.PDFJS.workerSrc = 'pdf.worker.js';

export {
  Document,
  Outline,
  Page,
};
<commit_msg>Add local file system warning on default entry file<commit_after>import Document from './Document';
import Outline from './Outline';
import Page from './Page';

import { isLocalFileSystem, warnOnDev } from './shared/util';

if (isLocalFileSystem) {
  // eslint-disable-next-line no-console
  warnOnDev('You are running React-PDF from your local file system. PDF.js Worker may fail to load due to browser\'s security policies. If you\'re on Google Chrome, you can use --allow-file-access-from-files flag for debugging purposes.');
}

const pdfjs = require('pdfjs-dist');
require('pdfjs-dist/web/compatibility');

pdfjs.PDFJS.workerSrc = 'pdf.worker.js';

export {
  Document,
  Outline,
  Page,
};
<|endoftext|>


<commit_before>import Duration from 'duration'
import shortid from 'shortid'
import moment from 'moment'
import parser from './parser'

export const hashPattern = /(#\w+[\w-]*)/g
export const version = 5
export default class Entry {
  constructor(user, originalMessage, opts = {}, timezoneOffset) {
    let { date } = opts
    if (timezoneOffset && !date) {
      //  ensure reference date is in users time and zone
      date = moment().utcOffset(timezoneOffset)
    } else if (!date) {
      date = new Date()
    }

    if (typeof originalMessage === 'object')
      return this._fromObject(originalMessage)

    this.version = version
    this.user = user
    this._id = shortid.generate()
    this.original= originalMessage
    //  ensure ref is a date and not a moment
    this.ref = new Date(date)
    this.parse(originalMessage, date, timezoneOffset)
    this.parseTags(originalMessage)
  }

  _fromObject(doc) {
    Object.assign(this, doc)
    const start = new Date(this.start)
    const end = new Date(this.end)
    const text = this.time
    const message = this.message
    this.setDates({start, end, text, message})
    this.tags = new Set(doc.tags)
    return this
  }

  parse(msg, date, timezoneOffset) {
    let d = parser(msg, date, timezoneOffset)
    if (d.isRange) this.setDates(d)
  }

  parseTags(message) {
    // Set makes things unique
    this.tags = new Set(message.match(hashPattern))
  }

  setDates(opts) {
    this.hasDates = true
    this.start = opts.start
    this.startArr = moment(this.start).utc().toArray()
    this.end = opts.end
    this.endArr = moment(this.end).utc().toArray()
    this.time = opts.text
    this.message = opts.message
    this.duration = new Duration(this.start, this.end)
  }

  getDates() {
    let start = this.start
    let end = this.end
    return { start, end }
  }

  toObject() {
    return {
      _id: this._id,
      version: this.version,
      ref: this.ref,
      user: this.user,
      original: this.original,
      message: this.message,
      hasDates: this.hasDates,
      start: this.start,
      startArr: this.startArr,
      end: this.end,
      endArr: this.endArr,
      time: this.time,
      tags: [...this.tags],
      duration: this.duration ? {
        seconds: this.duration.seconds,
      } : null
    }
  }

  static fromObject(doc) {
    let e = new Entry(doc.user, doc)

    return e
  }
}
<commit_msg>Rename function to be more inclusive<commit_after>import Duration from 'duration'
import shortid from 'shortid'
import moment from 'moment'
import parser from './parser'

export const hashPattern = /(#\w+[\w-]*)/g
export const version = 5
export default class Entry {
  constructor(user, originalMessage, opts = {}, timezoneOffset) {
    let { date } = opts
    if (timezoneOffset && !date) {
      //  ensure reference date is in users time and zone
      date = moment().utcOffset(timezoneOffset)
    } else if (!date) {
      date = new Date()
    }

    if (typeof originalMessage === 'object')
      return this._fromObject(originalMessage)

    this.version = version
    this.user = user
    this._id = shortid.generate()
    this.original= originalMessage
    //  ensure ref is a date and not a moment
    this.ref = new Date(date)
    this.parse(originalMessage, date, timezoneOffset)
    this.parseTags(originalMessage)
  }

  _fromObject(doc) {
    Object.assign(this, doc)
    const start = new Date(this.start)
    const end = new Date(this.end)
    const text = this.time
    const message = this.message
    this.setParsedFields({start, end, text, message})
    this.tags = new Set(doc.tags)
    return this
  }

  parse(msg, date, timezoneOffset) {
    let d = parser(msg, date, timezoneOffset)
    if (d.isRange) this.setParsedFields(d)
  }

  parseTags(message) {
    // Set makes things unique
    this.tags = new Set(message.match(hashPattern))
  }

  setParsedFields(opts) {
    this.hasDates = true
    this.start = opts.start
    this.startArr = moment(this.start).utc().toArray()
    this.end = opts.end
    this.endArr = moment(this.end).utc().toArray()
    this.time = opts.text
    this.message = opts.message
    this.duration = new Duration(this.start, this.end)
  }

  getDates() {
    let start = this.start
    let end = this.end
    return { start, end }
  }

  toObject() {
    return {
      _id: this._id,
      version: this.version,
      ref: this.ref,
      user: this.user,
      original: this.original,
      message: this.message,
      hasDates: this.hasDates,
      start: this.start,
      startArr: this.startArr,
      end: this.end,
      endArr: this.endArr,
      time: this.time,
      tags: [...this.tags],
      duration: this.duration ? {
        seconds: this.duration.seconds,
      } : null
    }
  }

  static fromObject(doc) {
    let e = new Entry(doc.user, doc)

    return e
  }
}
<|endoftext|>


<commit_before>import moment from 'moment';
import {HttpClient} from 'aurelia-http-client';

var getFood = 'http://sugars.herokuapp.com/api/food',
    postEntry = '/api/entry';

export class Entry{
  static inject() { return [HttpClient]; }
  constructor(http){
    this.heading = 'New Entry';
    this.glucose = 0;
    this.quantity = 0;
    this.exercise = 0;
    this.chosenFood =
      {
        name : 'Default',
        unit : 'unit',
        amount : 0,
        carbs : 0
      };
    this.food = [];
    this.images = [];
    this.http = http;
    // this.food = [
    //   {
    //     name : 'Pizza',
    //     unit : 'slice',
    //     amount : 1,
    //     carbs : 30
    //   },
    //   {
    //     name : 'Rice',
    //     unit : 'cup',
    //     amount : 1,
    //     carbs : 45
    //   },
    //   {
    //     name : 'Bread',
    //     unit : 'slice',
    //     amount : 1,
    //     carbs : 20
    //   }
    // ];
  }

  activate(){
    return this.http.get(getFood).then(response => {
      this.food = response.content;
    });
  }

  entry(){
    var data = {
        name : 'Bread',
        unit : 'slice',
        amount : 1,
        carbs : 20
    };

    return this.http.post(postEntry, JSON.stringify(data)).then(response => {

      if (response.statusCode === 201) {
        console.log('Success');
      } else {
        console.log('Response', response);
        alert('Something went wrong');
      }
    });
  }

  get time(){
    return moment().format("dddd, Do MMMM YYYY, h:mm a");
  }

  get totalCarbs(){
    var calculation = parseInt(this.quantity) * parseInt(this.chosenFood.carbs);
    return `${calculation}`;
  }

  get plural(){
    if (this.quantity > 1 || this.quantity === 0) {
      return 's';
    }
  }

  get short(){
    var normalAdjust = (parseInt(this.glucose) - 7) / 3,
        foodAdjust = (isNaN(parseInt(this.totalCarbs) / 10)) ? 0 : parseInt(this.totalCarbs) / 10,
        exerciseAdjust = parseInt(this.exercise),
        calculation = Math.round(((normalAdjust + foodAdjust - exerciseAdjust) * 10) / 10);

        calculation = (calculation < 0) ? 0 : calculation;

    return `${calculation}`;
  }

  addFood(){
    return alert('adding some foods');
  }

}

//1. user inputs data, new entry record is saved on submit.
//2. user inputs new food name, number of carbs per unit and quantity, new food record is saved on submit ("unit" can be default unit name)
//3. api returns food list

<commit_msg>Post entry to api<commit_after>import moment from 'moment';
import {HttpClient} from 'aurelia-http-client';

var getFood = 'http://sugars.herokuapp.com/api/food',
    postEntry = 'http://sugars.herokuapp.com/api/entry';

export class Entry{
  static inject() { return [HttpClient]; }
  constructor(http){
    this.heading = 'New Entry';
    this.glucose = 0;
    this.quantity = 0;
    this.exercise = 0;
    this.chosenFood =
      {
        name : 'Default',
        unit : 'unit',
        defaultAmount : 0,
        carbs : 0
      };
    this.food = [];
    this.images = [];
    this.http = http;
    // this.food = [
    //   {
    //     name : 'Pizza',
    //     unit : 'slice',
    //     amount : 1,
    //     carbs : 30
    //   },
    //   {
    //     name : 'Rice',
    //     unit : 'cup',
    //     amount : 1,
    //     carbs : 45
    //   },
    //   {
    //     name : 'Bread',
    //     unit : 'slice',
    //     amount : 1,
    //     carbs : 20
    //   }
    // ];
  }

  activate(){
    return this.http.get(getFood).then(response => {
      this.food = response.content;
    });
  }

  entry(){
    var data = {
      glucoseLevel : this.glucose,
      exerciseCarbs : this.exercise,
      insulinShort : this.short, //not getting the final version of this value :/
      foodItems : [
        {
          id : null,
          quantity : this.quantity,
          carbs : this.chosenFood.carbs,
          name : this.chosenFood.name,
          unit : this.chosenFood.unit,
          defaultAmount : this.chosenFood.defaultAmount
        }]
    };

    return this.http.post(postEntry, JSON.stringify(data)).then(response => {

      if (response.statusCode === 201) {
        console.log('Success');
      } else {
        console.log('Response', response);
        alert('Something went wrong');
      }
    });
  }

  get time(){
    return moment().format("dddd, Do MMMM YYYY, h:mm a");
  }

  get totalCarbs(){
    var calculation = parseInt(this.quantity) * parseInt(this.chosenFood.carbs);
    return `${calculation}`;
  }

  get plural(){
    if (this.quantity > 1 || this.quantity === 0) {
      return 's';
    }
  }

  get short(){
    var normalAdjust = (parseInt(this.glucose) - 7) / 3,
        foodAdjust = (isNaN(parseInt(this.totalCarbs) / 10)) ? 0 : parseInt(this.totalCarbs) / 10,
        exerciseAdjust = parseInt(this.exercise),
        calculation = Math.round(((normalAdjust + foodAdjust - exerciseAdjust) * 10) / 10);

        calculation = (calculation < 0) ? 0 : calculation;

    return `${calculation}`;
  }

  addFood(){
    return alert('adding some foods');
  }

}

//1. user inputs data, new entry record is saved on submit.
//2. user inputs new food name, number of carbs per unit and quantity, new food record is saved on submit ("unit" can be default unit name)
//3. api returns food list

<|endoftext|>


<commit_before>import fetch from 'node-fetch';
import querystring from 'querystring';
import handleErrorMessage from './utils';

export default async function (url, opts = { method: 'GET' }) {
    const res = await fetch(url, {
        method: opts.method,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: (typeof opts.body !== 'undefined' && opts.body.constructor.name === 'Buffer') ? opts.body : querystring.stringify(opts.body),
    });

    let data = await res.text();

    if (!data) return null;

    data = JSON.parse(data);

    if (![200, 201].includes(res.status)) {
        return handleErrorMessage(data);
    }

    return data;
}
<commit_msg>Fix parsing<commit_after>import fetch from 'node-fetch';
import querystring from 'querystring';
import handleErrorMessage from './utils';

const IsJsonString = (str) => {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
};

export default async function (url, opts = { method: 'GET' }) {
    const res = await fetch(url, {
        method: opts.method,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: (typeof opts.body !== 'undefined' && opts.body.constructor.name === 'Buffer') ? opts.body : querystring.stringify(opts.body),
    });

    const data = await res.text();

    if (!data) return null;

    if (![200, 201].includes(res.status)) {
        if (!IsJsonString(data)) {
            throw new Error('Internal error');
        }
        return handleErrorMessage(JSON.parse(data));
    }

    return JSON.parse(data);
}
<|endoftext|>


<commit_before>var stats = new Stats();

var ROOT_LENGTH = 100;
var TIME_BETWEEN_GROWTHS = 0;

var width, height, quadTree;
var stop = false;

var Thorn = {
  bounds: function () {
    // memoize
    if (this._bounds) {
      return this._bounds;
    }
    var endX   = this.x + this.dirX;
    var endY   = this.y + this.dirY;
    var x      = Math.min(this.x, endX);
    var y      = Math.min(this.y, endY);
    var right  = Math.max(this.x, endX, 1);
    var bottom = Math.max(this.y, endY, 1);
    return this._bounds = {
      x:      x,
      y:      y,
      width:  right  - x,
      height: bottom - y,
      right:  right,
      bottom: bottom,
      dirX:   this.dirX,
      dirY:   this.dirY
    };
  }
};

var root = Object.assign({}, Thorn);
var leaves = [root];
var thornList = [root];

var randomInt = function (max) {
  return Math.round(Math.random() * max);
};

var pointOutside = function (x, y) {
  return (x > width)  ||
         (x < 0)      ||
         (y > height) ||
         (y < 0);
};

var plantRoot = function () {
  if (Math.random() < 0.5) {
    root.x = (Math.random() < 0.5) ? 0 : width;
    root.y = Math.round(Math.random() * height);
    root.dirX = (root.x === 0) ? ROOT_LENGTH : -ROOT_LENGTH;
    root.dirY = 0;
  } else {
    root.x = Math.round(Math.random() * width);
    root.y = (Math.random() < 0.5) ? 0 : height;
    root.dirX = 0;
    root.dirY = (root.y === 0) ? ROOT_LENGTH : -ROOT_LENGTH;
  }
  root.length = ROOT_LENGTH;
  quadTree.insert(root.bounds());
};

var render = function () {
  stats.begin();
  context.clearRect(0, 0, width, height);

  for (var i = 0; i < thornList.length; i++) {
    var thorn = thornList[i];
    context.moveTo(thorn.x, thorn.y);
    context.lineTo(thorn.x + thorn.dirX, thorn.y + thorn.dirY);
  }
  context.stroke();

  stats.end();
};

var lastFrame, elapsed;
lastFrame = 0;

var tick = function (timestamp) {
  elapsed = timestamp - lastFrame;
  lastFrame = timestamp;
  step(elapsed);
  render();

  if (!stop) {
    requestAnimationFrame(tick);
  }
};

var timeSinceLastGrowth = 0;

var step = function (delta) {
  timeSinceLastGrowth += delta;
  if (timeSinceLastGrowth > TIME_BETWEEN_GROWTHS) {
    if (leaves.length === 0) {
      return;
    }
    var leafChoice = randomInt(leaves.length-1);
    var node = leaves[leafChoice];
    var candidates = ['left', 'right'];
    var choice = randomInt(1);
    if (node[candidates[choice]]) {
      // already have that one choose the other
      choice = (choice + 1) % 2;
    }
    var dirX =  node.dirY + (Math.random() * 10 - 5);
    var dirY = -node.dirX + (Math.random() * 10 - 5);
    var unitNodeX = node.dirX/node.length;
    var unitNodeY = node.dirY/node.length;
    // flip for the 'right' node
    if (candidates[choice] === 'right') {
      var dot = dirX * unitNodeX + dirY * unitNodeY;
      dirX = 2 * dot * unitNodeX - dirX;
      dirY = 2 * dot * unitNodeY - dirY;
    }
    var newNode = Object.assign({
      x:      node.x + unitNodeX * (0.25 + Math.random() * node.length/2),
      y:      node.y + unitNodeY * (0.25 + Math.random() * node.length/2),
      dirX:   dirX,
      dirY:   dirY,
      length: Math.sqrt(dirX*dirX + dirY*dirY)
    }, Thorn);

    var currentNodeBounds = node.bounds();
    var possibleCollisions = quadTree.retrieve(newNode.bounds());
    var bounds = newNode.bounds();
    var newNodeVecX = newNode.x + newNode.dirX;
    var newNodeVecY = newNode.y + newNode.dirY;
    for (var i = 0; i < possibleCollisions.length; i++) {
      var thorn = possibleCollisions[i];
      if (thorn === currentNodeBounds) {
        // ignore the thorn we're branching off of, we're definitely going to
        // collide with that
        continue;
      }
      var thornVecX = thorn.x + thorn.dirX;
      var thornVecY = thorn.x + thorn.dirY;
      var firstX = thorn.x - newNode.x;
      var firstY = thorn.y - newNode.y;
      // cross product
      // this.x * other.y - this.y * other.x;
      var denom = newNodeVecX * thornVecY - newNodeVecY * thornVecX;
      if (denom !== 0) {
        var t = (firstX * thornVecY - firstY * thornVecX) / denom;
        var u = (firstX * newNodeVecY - firstY * newNodeVecX) / denom;
        // all between 0 and 1
        if (t < 1 && t > 0 && u < 1 && u > 0) {
          // collision!
          node[candidates[choice]] = -1; // mark as not available
          // if this node is full, remove it from the leaf list
          if (node.left && node.right) {
            leaves.splice(leafChoice, 1);
          }
          return; // skip this node
        }
      }
    }

    quadTree.insert(bounds);
    node[candidates[choice]] = newNode;
    thornList.push(newNode);

    // only put this node in the leaves list if its end is in the window
    if (!pointOutside(newNode.x + newNode.dirX, newNode.y + newNode.dirY)) {
      leaves.push(newNode);
    }
    // if this node is full, remove it from the leaf list
    if (node.left && node.right) {
      leaves.splice(leafChoice, 1);
    }
    // we have a new growth, reset the timer
    timeSinceLastGrowth = 0;
  }
};

window.onload = function() {
  var canvas = document.getElementById('canvas');

  if (document.location.search === "?fps=1") {
    stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    document.body.appendChild(stats.dom);
  }

  context = canvas.getContext('2d');
  context.canvas.width  = window.innerWidth;
  context.canvas.height = window.innerHeight;
  width  = context.canvas.width;
  height = context.canvas.height;

  quadTree = new Quadtree({
    x: 0,
    y: 0,
    width:  width,
    height: height
  });

  plantRoot();

  requestAnimationFrame(tick);
};
<commit_msg>thorn points<commit_after>var stats = new Stats();

var ROOT_LENGTH = 100;
var TIME_BETWEEN_GROWTHS = 0;

var width, height, quadTree;
var stop = false;

var Thorn = {
  bounds: function () {
    // memoize
    if (this._bounds) {
      return this._bounds;
    }
    var endX   = this.x + this.dirX;
    var endY   = this.y + this.dirY;
    var x      = Math.min(this.x, endX);
    var y      = Math.min(this.y, endY);
    var right  = Math.max(this.x, endX, 1);
    var bottom = Math.max(this.y, endY, 1);
    return this._bounds = {
      x:      x,
      y:      y,
      width:  right  - x,
      height: bottom - y,
      right:  right,
      bottom: bottom,
      dirX:   this.dirX,
      dirY:   this.dirY
    };
  }
};

var root = Object.assign({}, Thorn);
var leaves = [root];
var thornList = [root];

var randomInt = function (max) {
  return Math.round(Math.random() * max);
};

var pointOutside = function (x, y) {
  return (x > width)  ||
         (x < 0)      ||
         (y > height) ||
         (y < 0);
};

var plantRoot = function () {
  var startX, startY, endX, endY;
  if (Math.random() < 0.5) {
    startY = Math.round(Math.random() * height);
    if (Math.random() < 0.5) {
      startX = 0;
      endY = startY - (ROOT_LENGTH / 10);
    } else {
      startX = width;
      endY = startY + (ROOT_LENGTH / 10);
    }
    endX = startX;
    root.dirX = (startX === 0) ? ROOT_LENGTH : -ROOT_LENGTH;
    root.dirY = 0;
  } else {
    startX = Math.round(Math.random() * width);
    if (Math.random() < 0.5) {
      startY = 0;
      endX = startX + (ROOT_LENGTH / 10);
    } else {
      startY = height;
      endX = startX - (ROOT_LENGTH / 10);
    }
    endY = startY;
    root.dirX = 0;
    root.dirY = (startY === 0) ? ROOT_LENGTH : -ROOT_LENGTH;
  }
  var points = [
    startX,
    startY,
    endX,
    endY,
    startX + root.dirX,
    startY + root.dirY
  ];
  root.centerX = (points[0] + points[2] + points[4]) / 3;
  root.centerY = (points[1] + points[3] + points[5]) / 3;
  root.points = points;
  root.length = ROOT_LENGTH;
  quadTree.insert(root.bounds());
};

var render = function () {
  stats.begin();
  context.clearRect(0, 0, width, height);

  for (var i = 0; i < thornList.length; i++) {
    var thorn = thornList[i];
    context.beginPath();
    context.moveTo(thorn.points[0], thorn.points[1]);
    for (var j = 2; j < thorn.points.length; j = j + 2) {
      context.lineTo(thorn.points[j], thorn.points[j + 1]);
    }
    context.closePath();
    context.fill();
  }

  stats.end();
};

var lastFrame, elapsed;
lastFrame = 0;

var tick = function (timestamp) {
  elapsed = timestamp - lastFrame;
  lastFrame = timestamp;
  step(elapsed);
  render();

  if (!stop) {
    requestAnimationFrame(tick);
  }
};

var timeSinceLastGrowth = 0;

var step = function (delta) {
  timeSinceLastGrowth += delta;
  if (timeSinceLastGrowth > TIME_BETWEEN_GROWTHS) {
    if (leaves.length === 0) {
      return;
    }
    var leafChoice = randomInt(leaves.length-1);
    var node = leaves[leafChoice];
    var candidates = ['left', 'right'];
    var choice = randomInt(1);
    if (node[candidates[choice]]) {
      // already have that one choose the other
      choice = (choice + 1) % 2;
    }
    var dirX =  node.dirY + (Math.random() * 10 - 5);
    var dirY = -node.dirX + (Math.random() * 10 - 5);
    var unitNodeX = node.dirX/node.length;
    var unitNodeY = node.dirY/node.length;
    // flip for the 'right' node
    if (candidates[choice] === 'right') {
      var dot = dirX * unitNodeX + dirY * unitNodeY;
      dirX = 2 * dot * unitNodeX - dirX;
      dirY = 2 * dot * unitNodeY - dirY;
    }
    var startX = node.centerX; // + unitNodeX * (0.25 + Math.random() * node.length/2);
    var startY = node.centerY; // + unitNodeY * (0.25 + Math.random() * node.length/2);
    var points = [
      startX,
      startY,
      startX + unitNodeX * node.length * 0.10,
      startY + unitNodeY * node.length * 0.10,
      startX + dirX,
      startY + dirY
    ];
    var centerX = (points[0] + points[2] + points[4]) / 3;
    var centerY = (points[1] + points[3] + points[5]) / 3;
    var newNode = Object.assign({
      points:  points,
      centerX: centerX,
      centerY: centerY,
      dirX:   dirX,
      dirY:   dirY,
      length: Math.sqrt(dirX*dirX + dirY*dirY)
    }, Thorn);

    var currentNodeBounds = node.bounds();
    var possibleCollisions = quadTree.retrieve(newNode.bounds());
    var bounds = newNode.bounds();
    var newNodeVecX = newNode.x + newNode.dirX;
    var newNodeVecY = newNode.y + newNode.dirY;
    for (var i = 0; i < possibleCollisions.length; i++) {
      var thorn = possibleCollisions[i];
      if (thorn === currentNodeBounds) {
        // ignore the thorn from where we're branching, we're definitely going to
        // collide with that
        continue;
      }
      var thornVecX = thorn.x + thorn.dirX;
      var thornVecY = thorn.x + thorn.dirY;
      var firstX = thorn.x - newNode.x;
      var firstY = thorn.y - newNode.y;
      // cross product
      // this.x * other.y - this.y * other.x;
      var denom = newNodeVecX * thornVecY - newNodeVecY * thornVecX;
      if (denom !== 0) {
        var t = (firstX * thornVecY - firstY * thornVecX) / denom;
        var u = (firstX * newNodeVecY - firstY * newNodeVecX) / denom;
        // all between 0 and 1
        if (t < 1 && t > 0 && u < 1 && u > 0) {
          // collision!
          node[candidates[choice]] = -1; // mark as not available
          // if this node is full, remove it from the leaf list
          if (node.left && node.right) {
            leaves.splice(leafChoice, 1);
          }
          return; // skip this node
        }
      }
    }

    quadTree.insert(bounds);
    node[candidates[choice]] = newNode;
    thornList.push(newNode);

    // only put this node in the leaves list if its end is in the window
    if (!pointOutside(newNode.x + newNode.dirX, newNode.y + newNode.dirY)) {
      leaves.push(newNode);
    }
    // if this node is full, remove it from the leaf list
    if (node.left && node.right) {
      leaves.splice(leafChoice, 1);
    }
    // we have a new growth, reset the timer
    timeSinceLastGrowth = 0;
  }
};

window.onload = function() {
  var canvas = document.getElementById('canvas');

  if (document.location.search === "?fps=1") {
    stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    document.body.appendChild(stats.dom);
  }

  context = canvas.getContext('2d');
  context.canvas.width  = window.innerWidth;
  context.canvas.height = window.innerHeight;
  width  = context.canvas.width;
  height = context.canvas.height;

  quadTree = new Quadtree({
    x: 0,
    y: 0,
    width:  width,
    height: height
  });

  plantRoot();

  requestAnimationFrame(tick);
};
<|endoftext|>