<commit_before>/**
 * Copyright 2015-present Tuan Le.
 *
 * Licensed under the MIT License.
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/mit-license.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *------------------------------------------------------------------------
 *
 * @module AppFactory
 * @description - An app factory.
 *
 * @author Tuan Le (tuan.t.lei@gmail.com)
 */
'use strict'; // eslint-disable-line

/* load Composer */
import Composer from '../composer';

/* load Hflow */
import { Hflow } from 'hyperflow';

/* factory Ids */
import {
    DOMAIN_FACTORY_CODE
} from './factory-code';

/**
 * @description - An app factory module.
 *
 * @module AppFactory
 */
export default Composer({
    state: {
        name: {
            value: `unnamed`,
            stronglyTyped: true,
            required: true
        }
    },
    AppFactory: function AppFactory () {
        /* ----- Private Variables ------------- */
        let _componentLib;
        let _componentRenderer;
        let _domain;
        /* ----- Public Functions -------------- */
        /**
         * @description - Initialize app before running.
         *
         * @method $init
         * @return void
         */
        this.$init = function $init () {
            Hflow.log(`warn0`, `AppFactory.$init - Method is not implemented by default.`);
        };
        /**
         * @description - Render app top level component to the target env.
         *
         * @method renderToTarget
         * @return {void|string}
         */
        this.renderToTarget = function renderToTarget () {
            Hflow.log(`warn0`, `AppFactory.renderToTarget - Method is not implemented by default.`);
        };
        /**
         * @description - Get the composed app top interface component from top level domain.
         *
         * @method getTopComponent
         * @return {object|function}
         */
        this.getTopComponent = function getTopComponent () {
            Hflow.log(`warn0`, `AppFactory.getTopComponent - Method is not implemented by default.`);
        };
        /**
         * @description - Get app top level domain.
         *
         * @method getTopDomain
         * @return {object}
         */
        this.getTopDomain = function getTopDomain () {
            const app = this;
            if (!Hflow.isObject(_domain)) {
                Hflow.log(`error`, `AppFactory.getTopDomain - App:${app.name} is not registered with a domain.`);
            } else {
                return _domain;
            }
        };
        /**
         * @description - Get app component renderer.
         *
         * @method getComponentRenderer
         * @return {object}
         */
        this.getComponentRenderer = function getComponentRenderer () {
            const app = this;
            if (!Hflow.isObject(_componentRenderer)) {
                Hflow.log(`error`, `AppFactory.getComponentRenderer - App:${app.name} is not registered with a component renderer.`);
            } else {
                return _componentRenderer;
            }
        };
        /**
         * @description - Get app component toolkit or library for building & rendering interfaces.
         *
         * @method getComponentLib
         * @return {object}
         */
        this.getComponentLib = function getComponentLib () {
            const app = this;
            if (!Hflow.isObject(_componentLib)) {
                Hflow.log(`error`, `AppFactory.getComponentLib - App:${app.name} is not registered with a component library.`);
            } else {
                return _componentLib;
            }
        };
        /**
         * @description - Register app domain, renderer, and app environment target.
         *
         * @method register
         * @param {object} definition - App registration definition for domain, renderer, and target.
         * @return void
         */
        this.register = function register (definition) {
            const app = this;
            if (!Hflow.isSchema({
                domain: `object`,
                component: {
                    library: `object`,
                    renderer: `object`
                }
            }).of(definition)) {
                Hflow.log(`error`, `AppFactory.register - Input definition is invalid.`);
            } else {
                const {
                    domain,
                    component
                } = definition;
                _componentLib = component.library;
                _componentRenderer = component.renderer;
                if (!Hflow.isSchema({
                    fId: `string`,
                    name: `string`,
                    hasStarted: `function`,
                    start: `function`,
                    restart: `function`
                }).of(domain) || domain.fId.substr(0, DOMAIN_FACTORY_CODE.length) !== DOMAIN_FACTORY_CODE) {
                    Hflow.log(`error`, `AppFactory.register - Input domain is invalid.`);
                } else if (Hflow.isObject(_domain)) {
                    Hflow.log(`warn1`, `AppFactory.register - App:${app.name} registered domain:${domain.name}.`);
                } else {
                    _domain = domain;
                    Hflow.log(`info`, `App:${app.name} registered domain:${domain.name}.`);
                }
            }
        };
        /**
         * @description - Run the app.
         *
         * @method run
         * @param {object} option
         * @return void
         */
        this.run = function run (option = {}) {
            const app = this;

            // TODO: Implement use case for app run option.
            option = Hflow.isObject(option) ? option : {};

            if (!Hflow.isObject(_domain)) {
                Hflow.log(`error`, `AppFactory.run - App:${app.name} is not registered with a domain.`);
            } else {
                if (!_domain.hasStarted()) {
                    _domain.start(option, () => {
                        app.renderToTarget();
                        Hflow.log(`info`, `Domain:${_domain.name} has started.`);
                        Hflow.log(`info`, `Running app:${app.name}...`);
                    });
                } else {
                    _domain.restart(option, () => {
                        app.renderToTarget();
                        Hflow.log(`info`, `Domain:${_domain.name} has restarted.`);
                        Hflow.log(`warn1`, `AppFactory.run - App:${app.name} is already running. Restarting...`);
                    });
                }
            }
        };
    }
});
<commit_msg>Rename method getTopComponentRenderer to getRenderer and removed getComponentLib method. Interface will register component library during app registration.<commit_after>/**
 * Copyright 2015-present Tuan Le.
 *
 * Licensed under the MIT License.
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/mit-license.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *------------------------------------------------------------------------
 *
 * @module AppFactory
 * @description - An app factory.
 *
 * @author Tuan Le (tuan.t.lei@gmail.com)
 */
'use strict'; // eslint-disable-line

/* load Composer */
import Composer from '../composer';

/* load Hflow */
import { Hflow } from 'hyperflow';

/* factory Ids */
import {
    DOMAIN_FACTORY_CODE
} from './factory-code';

/**
 * @description - An app factory module.
 *
 * @module AppFactory
 */
export default Composer({
    state: {
        name: {
            value: `unnamed`,
            stronglyTyped: true,
            required: true
        }
    },
    AppFactory: function AppFactory () {
        /* ----- Private Variables ------------- */
        let _renderer;
        let _domain;
        /* ----- Public Functions -------------- */
        /**
         * @description - Initialize app before running.
         *
         * @method $init
         * @return void
         */
        this.$init = function $init () {
            Hflow.log(`warn0`, `AppFactory.$init - Method is not implemented by default.`);
        };
        /**
         * @description - Render app top level component to the target env.
         *
         * @method renderToTarget
         * @return {void|string}
         */
        this.renderToTarget = function renderToTarget () {
            Hflow.log(`warn0`, `AppFactory.renderToTarget - Method is not implemented by default.`);
        };
        /**
         * @description - Get app renderer.
         *
         * @method getRenderer
         * @return {object}
         */
        this.getRenderer = function getRenderer () {
            const app = this;
            if (!Hflow.isObject(_renderer)) {
                Hflow.log(`error`, `AppFactory.getRenderer - App:${app.name} is not registered with a component renderer.`);
            } else {
                return _renderer;
            }
        };
        /**
         * @description - Get the composed app top interface component from top level domain.
         *
         * @method getTopComponent
         * @return {object|function}
         */
        this.getTopComponent = function getTopComponent () {
            Hflow.log(`warn0`, `AppFactory.getTopComponent - Method is not implemented by default.`);
        };
        /**
         * @description - Get app top level domain.
         *
         * @method getTopDomain
         * @return {object}
         */
        this.getTopDomain = function getTopDomain () {
            const app = this;
            if (!Hflow.isObject(_domain)) {
                Hflow.log(`error`, `AppFactory.getTopDomain - App:${app.name} is not registered with a domain.`);
            } else {
                return _domain;
            }
        };
        /**
         * @description - Register app domain, renderer, and app environment target.
         *
         * @method register
         * @param {object} definition - App registration definition for domain, renderer, and target.
         * @return void
         */
        this.register = function register (definition) {
            const app = this;
            if (!Hflow.isSchema({
                domain: `object`,
                component: {
                    library: `object`,
                    renderer: `object`
                }
            }).of(definition)) {
                Hflow.log(`error`, `AppFactory.register - Input definition is invalid.`);
            } else {
                const {
                    domain,
                    component
                } = definition;
                if (!Hflow.isSchema({
                    fId: `string`,
                    name: `string`,
                    hasStarted: `function`,
                    getInterface: `function`,
                    start: `function`,
                    restart: `function`
                }).of(domain) || domain.fId.substr(0, DOMAIN_FACTORY_CODE.length) !== DOMAIN_FACTORY_CODE) {
                    Hflow.log(`error`, `AppFactory.register - Input domain is invalid.`);
                } else if (Hflow.isObject(_domain)) {
                    Hflow.log(`warn1`, `AppFactory.register - App:${app.name} registered domain:${domain.name}.`);
                } else {
                    _domain = domain;
                    _renderer = component.renderer;

                    const intf = domain.getInterface();
                    if (!Hflow.isSchema({
                        registerComponentLib: `function`
                    }).of(intf)) {
                        Hflow.log(`error`, `AppFactory.register - App top domain:${domain.name} interface is invalid.`);
                    } else {
                        intf.registerComponentLib(component.library);
                    }

                    Hflow.log(`info`, `App:${app.name} registered domain:${domain.name}.`);
                }
            }
        };
        /**
         * @description - Run the app.
         *
         * @method run
         * @param {object} option
         * @return void
         */
        this.run = function run (option = {}) {
            const app = this;

            // TODO: Implement use case for app run option.
            option = Hflow.isObject(option) ? option : {};

            if (!Hflow.isObject(_domain)) {
                Hflow.log(`error`, `AppFactory.run - App:${app.name} is not registered with a domain.`);
            } else {
                if (!_domain.hasStarted()) {
                    _domain.start(option, () => {
                        app.renderToTarget();
                        Hflow.log(`info`, `Domain:${_domain.name} has started.`);
                        Hflow.log(`info`, `Running app:${app.name}...`);
                    });
                } else {
                    _domain.restart(option, () => {
                        app.renderToTarget();
                        Hflow.log(`info`, `Domain:${_domain.name} has restarted.`);
                        Hflow.log(`warn1`, `AppFactory.run - App:${app.name} is already running. Restarting...`);
                    });
                }
            }
        };
    }
});
<|endoftext|>


<commit_before>/**
 * Created by kelvinzhang on 5/29/17.
 */

var canvas;
var bgCanvas;

var robotX;
var robotY;

var senseRadius = 150;

var nLasers = 36;

var robotDir = 0;
var dirOffset = 0;

var sensorNoise = 0.1;

//Results of laser scan
var z = new Array(nLasers);

function update()
{
    //Only scan if location changed
    scan(robotX, robotY, senseRadius, map, z);
}

function drawLaserLines(ctx)
{
    //Angle between each laser, in radians
    var rad = Math.PI*2/nLasers;

    //index of corresponding entry in z
    var i = (dirOffset - nLasers/4);
    i = (i+nLasers+nLasers);

    for(var index = 0; index <= nLasers/2; index ++, i++)
    {
        //dirOffset is the direction the user's mouse
        //is point at, -nLasers/4 to offset it by 90 degrees,
        //so that laser scan is centered at where the user
        //points to

        //get i stay in bound
        i %= nLasers;

        var dir = i * rad;
        var laserLen = senseRadius;

        //Grey color for a miss
        if(z[i] > senseRadius)
        {
            ctx.strokeStyle = 'grey';
        }else
        {
            //distance reported by the laser sensor
            var dist = z[i] + gaussian()*z[i]*sensorNoise;
            laserLen = min(laserLen, dist);

            //red for a hit
            ctx.strokeStyle = 'red';
            ctx.fillStyle = 'red';
            ctx.beginPath();
            ctx.circle(robotX + cos(dir)*dist, robotY + sin(dir)*dist, 5);
            ctx.fill();
        }
        ctx.strokeLine(robotX, robotY, robotX + cos(dir)*laserLen, robotY + sin(dir)*laserLen)
    }
}

function drawRobot(ctx)
{
    ctx.strokeStyle = 'black';
    ctx.drawRobot(robotX, robotY, robotDir, 20);
}

function parameterChanged(event)
{
    var target = event.target || event.srcElement;

    if(target.id === 'sensorRadius')
    {
        senseRadius = Number(target.value) / 0.02;
    }
    else if(target.id === 'sensorNoise')
    {
        sensorNoise = Number(target.value) / 100.0;
    }
    else if(target.id === 'nLasers')
    {
        nLasers = Number(target.value) * 2;
        z = new Array(nLasers);
    }
}

function mouseMotion(event)
{
    var coor = getClickLoc(event);
    var x = coor.x;
    var y = coor.y;

    robotDir = atan2(y-robotY, x-robotX);
    dirOffset = round(robotDir/Math.PI/2 * nLasers);
    clearCanvas(canvas);
    canvas.getContext('2d').drawRobot(robotX, robotY, robotDir, 20);
}

function mouseDown(event)
{
	//Do nothing if it is not a left button event
    if(event.button !== 0)
    	return;

    var coor = getClickLoc(event);
    var x = coor.x;
    var y = coor.y;

    robotX = x;
    robotY = y;
    clearCanvas(canvas);
    drawRobot(canvas.getContext('2d'));
    bgCanvas.onmousemove = mouseMotion;
    bgCanvas.onmouseout = mouseUp;
}

function mouseUp()
{
    bgCanvas.onmousemove = undefined;
    bgCanvas.onmouseout = undefined;
    update();
    drawLaserLines(canvas.getContext('2d'));
}

function init()
{
    canvas = document.getElementById('canvas');
    bgCanvas = document.getElementById('background');

    //Draw the map
    var map = getMapForCanvas(canvas);
    bgCanvas.getContext('2d').drawMap(map);
    robotX = floor(random()*canvas.width);
    robotY = floor(random()*canvas.height);

    Particle.size = 5;

    //Listen to mouse click events
    bgCanvas.onmousedown = mouseDown;
    bgCanvas.onmouseup = mouseUp;
    senseRadius = getValue('sensorRadius')/0.02;
}<commit_msg>refactoring<commit_after>/**
 * Created by kelvinzhang on 5/29/17.
 */

var canvas;
var bgCanvas;

var robotX;
var robotY;

var senseRadius = 150;

var nLasers = 36;

var robotDir = 0;
var dirOffset = 0;

var sensorNoise = 0.1;

//Results of laser scan
var z = new Array(nLasers);

function update()
{
    //Only scan if location changed
    scan(robotX, robotY, senseRadius, map, z);
}

function drawLaserLines(ctx)
{
    //Angle between each laser, in radians
    var rad = Math.PI*2/nLasers;

    //index of corresponding entry in z
    var i = (dirOffset - nLasers/4);
    i = (i+nLasers+nLasers);

    for(var index = 0; index <= nLasers/2; index ++, i++)
    {
        //dirOffset is the direction the user's mouse
        //is point at, -nLasers/4 to offset it by 90 degrees,
        //so that laser scan is centered at where the user
        //points to

        //get i stay in bound
        i %= nLasers;

        var dir = i * rad;
        var laserLen = senseRadius;

        //Grey color for a miss
        if(z[i] > senseRadius)
        {
            ctx.strokeStyle = 'grey';
        }else
        {
            //distance reported by the laser sensor
            var dist = z[i] + gaussian()*z[i]*sensorNoise;
            laserLen = min(laserLen, dist);

            //red for a hit
            ctx.strokeStyle = 'red';
            ctx.fillStyle = 'red';
            ctx.beginPath();
            ctx.circle(robotX + cos(dir)*dist, robotY + sin(dir)*dist, 5);
            ctx.fill();
        }
        ctx.strokeLine(robotX, robotY, robotX + cos(dir)*laserLen, robotY + sin(dir)*laserLen)
    }
}

function drawRobot(ctx)
{
    ctx.strokeStyle = 'black';
    ctx.drawRobot(robotX, robotY, robotDir, 20);
}

function parameterChanged(event)
{
    var target = event.target || event.srcElement;

    if(target.id === 'sensorRadius')
    {
        senseRadius = Number(target.value) / 0.02;
    }
    else if(target.id === 'sensorNoise')
    {
        sensorNoise = Number(target.value) / 100.0;
    }
    else if(target.id === 'nLasers')
    {
        nLasers = Number(target.value) * 2;
        z = new Array(nLasers);
    }
}

function trackRobotDir(event)
{
    var coor = getClickLoc(event);
    var x = coor.x;
    var y = coor.y;

    robotDir = atan2(y-robotY, x-robotX);
    dirOffset = round(robotDir/Math.PI/2 * nLasers);
    clearCanvas(canvas);
    canvas.getContext('2d').drawRobot(robotX, robotY, robotDir, 20);
}

function mouseDown(event)
{
	//Do nothing if it is not a left button event
    if(event.button !== 0)
    	return;

    var coor = getClickLoc(event);
    var x = coor.x;
    var y = coor.y;

    robotX = x;
    robotY = y;
    clearCanvas(canvas);
    drawRobot(canvas.getContext('2d'));
    bgCanvas.onmousemove = trackRobotDir;
    bgCanvas.onmouseout = mouseUp;
	bgCanvas.onmouseup = mouseUp;
}

function mouseUp()
{
    bgCanvas.onmousemove = undefined;
    bgCanvas.onmouseout = undefined;
    bgCanvas.onmouseup = undefined;
    update();
    drawLaserLines(canvas.getContext('2d'));
}

function init()
{
    canvas = document.getElementById('canvas');
    bgCanvas = document.getElementById('background');

    //Draw the map
    var map = getMapForCanvas(canvas);
    bgCanvas.getContext('2d').drawMap(map);
    robotX = floor(random()*canvas.width);
    robotY = floor(random()*canvas.height);

    Particle.size = 5;

    //Listen to mouse click events
    bgCanvas.onmousedown = mouseDown;
    senseRadius = getValue('sensorRadius')/0.02;
}<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at http://www.mozillapopcorn.org/butter-license.txt */

define( [ "core/logger", "core/eventmanager" ], function( Logger, EventManager ){

  var __guid = 0;

  return function( trackEvent, type, inputOptions ){

    var _id = "TrackEventView" + __guid++,
        _eventManager = new EventManager( this ),
        _element,
        _zoom = 1,
        _duration = 1,
        _type = type,
        _start = inputOptions.start || 0,
        _end = inputOptions.end || _start + 1,
        _selected = false,
        _parent,
        _handles,
        _this = this;

    function resetContainer(){
      _element.style.left = ( _start / _duration * _zoom ) + "px";
      _element.style.width = ( ( _end - _start ) / _duration * _zoom ) + "px";
    } //resetContainer

    this.update = function( options ){
      options = options || {};
      _element.style.top = "0px";
      _start = options.start || _start;
      _end = options.end || _end;
      resetContainer();
    }; //update

    Object.defineProperties( this, {
      trackEvent: {
        enumerable: true,
        get: function(){
          return trackEvent;
        }
      },
      element: {
        enumerable: true,
        get: function(){ return _element; }
      },
      duration: {
        enumerable: true,
        get: function(){ return _duration; },
        set: function( val ){
          _duration = val;
          resetContainer();
        }
      },
      start: {
        enumerable: true,
        get: function(){ return _start; },
        set: function( val ){
          _start = val;
          resetContainer();
        }
      },
      end: {
        enumerable: true,
        get: function(){ return _end; },
        set: function( val ){
          _end = val;
          resetContainer();
        }
      },
      text: {
        enumerable: true,
        get: function(){ return _element.innerHTML; },
        set: function( val ){
          _element.innerHTML = text;
        }
      },
      selected: {
        enumerable: true,
        get: function(){ return _selected; },
        set: function( val ){
          if( val ){
            select();
          }
          else {
            deselect();
          } //if
        }
      },
      zoom: {
        enumerable: true,
        get: function(){
          return _zoom;
        },
        set: function( val ){
          _zoom = val;
          resetContainer();
        }
      },
      duration: {
        enumerable: true,
        get: function(){
          return _element.getBoundingClientRect().width / _zoom;
        },
        set: function( val ){
          resetContainer();
        }
      },
      id: {
        enumerable: true,
        configurable: false,
        get: function(){
          return _id;
        }
      },
      parent: {
        enumerabled: true,
        get: function(){
          return _parent;
        },
        set: function( val ){
          _parent = val;
          if( _parent && !_handles ){

            $( _element ).draggable({
              containment: _parent.element.parentNode,
              // highest possible zIndex inside of 32 bits
              zIndex: 2147483647,
              scroll: true,
              // this is when an event stops being dragged
              start: function ( event, ui ) {
              },
              stop: movedCallback
            }).resizable({
              autoHide: false,
              containment: "parent",
              handles: "e, w",
              scroll: false,
              stop: movedCallback
            })
            .data( "draggable-type", "trackevent" )
            .data( "trackevent-id", trackEvent.id );

            _handles = _element.querySelectorAll( ".ui-resizable-handle" );
            function toggleHandles( state ){
              _handles[ 0 ].style.visibility = state ? "visible" : "hidden";
              _handles[ 1 ].style.visibility = state ? "visible" : "hidden";
            } //toggleHandles
            _element.addEventListener( "mouseover", function( e ){
              toggleHandles( true );
            }, false );
            _element.addEventListener( "mouseout", function( e ){
              toggleHandles( false );
            }, false );
            toggleHandles( false );

            resetContainer();
          } //if
        } //set
      }
    });

    function movedCallback( event, ui ) {
      _element.style.top = "0px";
      var rect = _element.getClientRects()[ 0 ];
      _start = _element.offsetLeft / _zoom;
      _end = _start + rect.width / _zoom;
      _eventManager.dispatch( "trackeventviewupdated", ui );
    } //movedCallback

    _element = document.createElement( "div" );
    _element.className = "butter-track-event";
    _element.appendChild( document.createTextNode( _type ) );
    _element.setAttribute( "data-butter-trackevent-type", _type );

    _element.id = _id;
    _this.update( inputOptions );

    _element.addEventListener( "mousedown", function ( e ) {
      _eventManager.dispatch( "trackeventmousedown", { originalEvent: e, trackEvent: trackEvent } );
    }, false);
    _element.addEventListener( "mouseover", function ( e ) {
      _eventManager.dispatch( "trackeventmouseover", { originalEvent: e, trackEvent: trackEvent } );
    }, false );
    _element.addEventListener( "mouseout", function ( e ) {
      _eventManager.dispatch( "trackeventmouseout", { originalEvent: e, trackEvent: trackEvent } );
    }, false );

    _element.addEventListener( "dblclick", function ( e ) {
      _eventManager.dispatch( "trackeventdoubleclicked", { originalEvent: e, trackEvent: trackEvent } );
    }, false);

    function select( e ){
      _selected = true;
      _element.setAttribute( "selected", true );
    } //select

    function deselect( e ) {
      _selected = false;
      _element.removeAttribute( "selected" );
    } //deselect

  };

});
<commit_msg>[t477] - View ignored 0 as possible value<commit_after>/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at http://www.mozillapopcorn.org/butter-license.txt */

define( [ "core/logger", "core/eventmanager" ], function( Logger, EventManager ){

  var __guid = 0;

  return function( trackEvent, type, inputOptions ){

    var _id = "TrackEventView" + __guid++,
        _eventManager = new EventManager( this ),
        _element,
        _zoom = 1,
        _duration = 1,
        _type = type,
        _start = inputOptions.start || 0,
        _end = inputOptions.end || _start + 1,
        _selected = false,
        _parent,
        _handles,
        _this = this;

    function resetContainer(){
      _element.style.left = ( _start / _duration * _zoom ) + "px";
      _element.style.width = ( ( _end - _start ) / _duration * _zoom ) + "px";
    } //resetContainer

    this.update = function( options ){
      options = options || {};
      _element.style.top = "0px";
      if( !isNaN( Number( options.start ) ) ){
        _start = options.start;
      }
      if( !isNaN( Number( options.end ) ) ){
        _end = options.end;
      }
      resetContainer();
    }; //update

    Object.defineProperties( this, {
      trackEvent: {
        enumerable: true,
        get: function(){
          return trackEvent;
        }
      },
      element: {
        enumerable: true,
        get: function(){ return _element; }
      },
      duration: {
        enumerable: true,
        get: function(){ return _duration; },
        set: function( val ){
          _duration = val;
          resetContainer();
        }
      },
      start: {
        enumerable: true,
        get: function(){ return _start; },
        set: function( val ){
          _start = val;
          resetContainer();
        }
      },
      end: {
        enumerable: true,
        get: function(){ return _end; },
        set: function( val ){
          _end = val;
          resetContainer();
        }
      },
      text: {
        enumerable: true,
        get: function(){ return _element.innerHTML; },
        set: function( val ){
          _element.innerHTML = text;
        }
      },
      selected: {
        enumerable: true,
        get: function(){ return _selected; },
        set: function( val ){
          if( val ){
            select();
          }
          else {
            deselect();
          } //if
        }
      },
      zoom: {
        enumerable: true,
        get: function(){
          return _zoom;
        },
        set: function( val ){
          _zoom = val;
          resetContainer();
        }
      },
      duration: {
        enumerable: true,
        get: function(){
          return _element.getBoundingClientRect().width / _zoom;
        },
        set: function( val ){
          resetContainer();
        }
      },
      id: {
        enumerable: true,
        configurable: false,
        get: function(){
          return _id;
        }
      },
      parent: {
        enumerabled: true,
        get: function(){
          return _parent;
        },
        set: function( val ){
          _parent = val;
          if( _parent && !_handles ){

            $( _element ).draggable({
              containment: _parent.element.parentNode,
              // highest possible zIndex inside of 32 bits
              zIndex: 2147483647,
              scroll: true,
              // this is when an event stops being dragged
              start: function ( event, ui ) {
              },
              stop: movedCallback
            }).resizable({
              autoHide: false,
              containment: "parent",
              handles: "e, w",
              scroll: false,
              stop: movedCallback
            })
            .data( "draggable-type", "trackevent" )
            .data( "trackevent-id", trackEvent.id );

            _handles = _element.querySelectorAll( ".ui-resizable-handle" );
            function toggleHandles( state ){
              _handles[ 0 ].style.visibility = state ? "visible" : "hidden";
              _handles[ 1 ].style.visibility = state ? "visible" : "hidden";
            } //toggleHandles
            _element.addEventListener( "mouseover", function( e ){
              toggleHandles( true );
            }, false );
            _element.addEventListener( "mouseout", function( e ){
              toggleHandles( false );
            }, false );
            toggleHandles( false );

            resetContainer();
          } //if
        } //set
      }
    });

    function movedCallback( event, ui ) {
      _element.style.top = "0px";
      var rect = _element.getClientRects()[ 0 ];
      _start = _element.offsetLeft / _zoom;
      _end = _start + rect.width / _zoom;
      _eventManager.dispatch( "trackeventviewupdated", ui );
    } //movedCallback

    _element = document.createElement( "div" );
    _element.className = "butter-track-event";
    _element.appendChild( document.createTextNode( _type ) );
    _element.setAttribute( "data-butter-trackevent-type", _type );

    _element.id = _id;
    _this.update( inputOptions );

    _element.addEventListener( "mousedown", function ( e ) {
      _eventManager.dispatch( "trackeventmousedown", { originalEvent: e, trackEvent: trackEvent } );
    }, false);
    _element.addEventListener( "mouseover", function ( e ) {
      _eventManager.dispatch( "trackeventmouseover", { originalEvent: e, trackEvent: trackEvent } );
    }, false );
    _element.addEventListener( "mouseout", function ( e ) {
      _eventManager.dispatch( "trackeventmouseout", { originalEvent: e, trackEvent: trackEvent } );
    }, false );

    _element.addEventListener( "dblclick", function ( e ) {
      _eventManager.dispatch( "trackeventdoubleclicked", { originalEvent: e, trackEvent: trackEvent } );
    }, false);

    function select( e ){
      _selected = true;
      _element.setAttribute( "selected", true );
    } //select

    function deselect( e ) {
      _selected = false;
      _element.removeAttribute( "selected" );
    } //deselect

  };

});
<|endoftext|>


<commit_before>#!/usr/bin/env node
/* eslint-disable no-console */

import path from 'path';
import program from 'commander';
import shelljs from 'shelljs';
import Server from '../server';

program
  .option('-h, --host <host>', 'host to listen on')
  .option('-p, --port <port>', 'port to listen on')
  .option('--haul <configFile>', 'use haul with config file')
  .option('--platform <ios|android|all>', 'build platform-specific build')
  .option('-s, --secured', 'whether server is running on https')
  .option('-c, --config-dir [dir-name]', 'storybook config directory')
  .option('-e, --environment [environment]', 'DEVELOPMENT/PRODUCTION environment for webpack')
  .option('-r, --reset-cache', 'reset react native packager')
  .option('--skip-packager', 'run only storybook server')
  .option('-i, --manual-id', 'allow multiple users to work with same storybook')
  .option('--smoke-test', 'Exit after successful start')
  .option('--packager-port <packagerPort>', 'Custom packager port')
  .option('--root [root]', 'Add additional root(s) to be used by the packager in this project')
  .option('--projectRoots [projectRoots]', 'Override the root(s) to be used by the packager')
  .parse(process.argv);

const projectDir = path.resolve();
const configDir = path.resolve(program.configDir || './storybook');
const listenAddr = [program.port];
if (program.host) {
  listenAddr.push(program.host);
}

const server = new Server({
  projectDir,
  configDir,
  environment: program.environment,
  manualId: program.manualId,
  secured: program.secured,
});

server.listen(...listenAddr, err => {
  if (err) {
    throw err;
  }
  const address = `http://${program.host || 'localhost'}:${program.port}/`;
  console.info(`\nReact Native Storybook started on => ${address}\n`);
  if (program.smokeTest) {
    process.exit(0);
  }
});

if (!program.skipPackager) {
  let symlinks = [];

  let roots = [projectDir];

  if (program.root) {
    roots = roots.concat(program.root.split(',').map(root => path.resolve(root)));
  }

  try {
    const findSymlinksPaths = require('react-native/local-cli/util/findSymlinksPaths'); // eslint-disable-line global-require
    symlinks = findSymlinksPaths(path.join(projectDir, 'node_modules'), [projectDir]);
  } catch (e) {
    console.warn(`Unable to load findSymlinksPaths: ${e.message}`);
  }

  let projectRoots = (configDir === projectDir ? [configDir] : [configDir, projectDir]).concat(
    symlinks
  );

  if (program.projectRoots) {
    projectRoots = projectRoots.concat(
      program.projectRoots.split(',').map(root => path.resolve(root))
    );
  }

  let cliCommand = 'node node_modules/react-native/local-cli/cli.js start';
  if (program.haul) {
    const platform = program.platform || 'all';
    cliCommand = `node node_modules/.bin/haul start --config ${
      program.haul
    } --platform ${platform}`;
  }
  // RN packager
  shelljs.exec(
    [
      cliCommand,
      `--projectRoots ${projectRoots.join(',')}`,
      `--root ${roots.join(',')}`,
      program.resetCache && '--reset-cache',
      program.packagerPort && `--port=${program.packagerPort}`,
    ]
      .filter(x => x)
      .join(' '),
    { async: true }
  );
}
<commit_msg>Use haul/bin/cli.js for cross-platform support<commit_after>#!/usr/bin/env node
/* eslint-disable no-console */

import path from 'path';
import program from 'commander';
import shelljs from 'shelljs';
import Server from '../server';

program
  .option('-h, --host <host>', 'host to listen on')
  .option('-p, --port <port>', 'port to listen on')
  .option('--haul <configFile>', 'use haul with config file')
  .option('--platform <ios|android|all>', 'build platform-specific build')
  .option('-s, --secured', 'whether server is running on https')
  .option('-c, --config-dir [dir-name]', 'storybook config directory')
  .option('-e, --environment [environment]', 'DEVELOPMENT/PRODUCTION environment for webpack')
  .option('-r, --reset-cache', 'reset react native packager')
  .option('--skip-packager', 'run only storybook server')
  .option('-i, --manual-id', 'allow multiple users to work with same storybook')
  .option('--smoke-test', 'Exit after successful start')
  .option('--packager-port <packagerPort>', 'Custom packager port')
  .option('--root [root]', 'Add additional root(s) to be used by the packager in this project')
  .option('--projectRoots [projectRoots]', 'Override the root(s) to be used by the packager')
  .parse(process.argv);

const projectDir = path.resolve();
const configDir = path.resolve(program.configDir || './storybook');
const listenAddr = [program.port];
if (program.host) {
  listenAddr.push(program.host);
}

const server = new Server({
  projectDir,
  configDir,
  environment: program.environment,
  manualId: program.manualId,
  secured: program.secured,
});

server.listen(...listenAddr, err => {
  if (err) {
    throw err;
  }
  const address = `http://${program.host || 'localhost'}:${program.port}/`;
  console.info(`\nReact Native Storybook started on => ${address}\n`);
  if (program.smokeTest) {
    process.exit(0);
  }
});

if (!program.skipPackager) {
  let symlinks = [];

  let roots = [projectDir];

  if (program.root) {
    roots = roots.concat(program.root.split(',').map(root => path.resolve(root)));
  }

  try {
    const findSymlinksPaths = require('react-native/local-cli/util/findSymlinksPaths'); // eslint-disable-line global-require
    symlinks = findSymlinksPaths(path.join(projectDir, 'node_modules'), [projectDir]);
  } catch (e) {
    console.warn(`Unable to load findSymlinksPaths: ${e.message}`);
  }

  let projectRoots = (configDir === projectDir ? [configDir] : [configDir, projectDir]).concat(
    symlinks
  );

  if (program.projectRoots) {
    projectRoots = projectRoots.concat(
      program.projectRoots.split(',').map(root => path.resolve(root))
    );
  }

  let cliCommand = 'node node_modules/react-native/local-cli/cli.js start';
  if (program.haul) {
    const platform = program.platform || 'all';
    cliCommand = `node node_modules/haul/bin/cli.js start --config ${
      program.haul
    } --platform ${platform}`;
  }
  // RN packager
  shelljs.exec(
    [
      cliCommand,
      `--projectRoots ${projectRoots.join(',')}`,
      `--root ${roots.join(',')}`,
      program.resetCache && '--reset-cache',
      program.packagerPort && `--port=${program.packagerPort}`,
    ]
      .filter(x => x)
      .join(' '),
    { async: true }
  );
}
<|endoftext|>


<commit_before>import {inject} from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';
import {Router} from 'aurelia-router';

@inject(HttpClient, Router, FileReader)
export class LibrarianDashboard {
  constructor(httpClient, router, reader){
    this.httpClient = httpClient;
    this.router = router;
    this.reader = reader;
    this.newBook = {
      'title': '',
      'type': 'hardback',
      'author': '',
      'numberPages': 0,
      'dateOfPub': 0,
      'url': '',
      'isbn': '',
      'siteLocation': '',
      'numberOfCopies': 1,
      'access': '',
      'comments': '',
      'checkedOutBy': '',
      'checkedOutByName': ''
    };
  }
  types = ['hardback', 'paperback', 'pdf', 'webpage', 'audiobook', 'gdoc'];
  accessArray = ['GE Internal', 'Public'];
  newBook = null;
  CSVFilePath = {files: ['']};
  fileList = '';

  createBook(){
    if (this.newBook.type !== 0){
      this.newBook.type = this.types[this.newBook.type - 1];
    } else {
      this.newBook.type = 'book';
    }
    if (this.newBook.access !== 0){
      this.newBook.access = this.accessArray[this.newBook.access - 1];
    } else {
      this.newBook.access = 'Public';
    }
    this.httpClient.fetch(process.env.BackendUrl + '/book/', {
      method: 'post',
      body: json(this.newBook)
    })
    //.then(response=>response.json())
    //.then(savedRecord => record = savedRecord)
    .then(data=>{
      this.router.navigate('/bookshelf');
    });
  }

  createBooksFromCSV(){
    let jsonObj;
    const httpClient = this.httpClient;
    const router = this.router;
    function loaded (evt) {
      const fileString = evt.target.result;
      const csvjson = require('csvjson');
      jsonObj = csvjson.toObject(fileString);
      makeLotaBooks(jsonObj);
    }
    function errorHandler(evt) {
      //TODO no file attached
      //TODO wrong file type attached
      alert('The file could not be read');
    }

    function makeLotaBooks (jsonObject) {
      httpClient.fetch(process.env.BackendUrl + '/book/', {
        method: 'post',
        body: json(jsonObject)
      })
      .then(response=>response.json())
      .then(data=>{
        router.navigate('/bookshelf');
      });
    }
    // if (CSVFilePath.files[0] !== null){
    // TODO: Parse all csv files
    // TODO: add check for browser support of FileReader
    //TODO: do not run file reader if no csv file in the form
    this.reader.onload = loaded;
    this.reader.onerror = errorHandler;
    this.reader.readAsText(CSVFilePath.files[0]);
  }
}
<commit_msg>Update librarian.js<commit_after>import {inject} from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';
import {Router} from 'aurelia-router';

@inject(HttpClient, Router, FileReader)
export class LibrarianDashboard {
  constructor(httpClient, router, reader){
    this.httpClient = httpClient;
    this.router = router;
    this.reader = reader;
    this.newBook = {
      'title': '',
      'type': 'hardback',
      'author': '',
      'numberPages': 0,
      'dateOfPub': 0,
      'url': '',
      'isbn': '',
      'siteLocation': '',
      'numberOfCopies': 1,
      'access': '',
      'comments': '',
      'checkedOutBy': '',
      'checkedOutByName': ''
    };
  }
  types = ['hardback', 'paperback', 'pdf', 'webpage', 'video', 'audiobook', 'gdoc'];
  accessArray = ['GE Internal', 'Public'];
  newBook = null;
  CSVFilePath = {files: ['']};
  fileList = '';

  createBook(){
    if (this.newBook.type !== 0){
      this.newBook.type = this.types[this.newBook.type - 1];
    } else {
      this.newBook.type = 'book';
    }
    if (this.newBook.access !== 0){
      this.newBook.access = this.accessArray[this.newBook.access - 1];
    } else {
      this.newBook.access = 'Public';
    }
    this.httpClient.fetch(process.env.BackendUrl + '/book/', {
      method: 'post',
      body: json(this.newBook)
    })
    //.then(response=>response.json())
    //.then(savedRecord => record = savedRecord)
    .then(data=>{
      this.router.navigate('/bookshelf');
    });
  }

  createBooksFromCSV(){
    let jsonObj;
    const httpClient = this.httpClient;
    const router = this.router;
    function loaded (evt) {
      const fileString = evt.target.result;
      const csvjson = require('csvjson');
      jsonObj = csvjson.toObject(fileString);
      makeLotaBooks(jsonObj);
    }
    function errorHandler(evt) {
      //TODO no file attached
      //TODO wrong file type attached
      alert('The file could not be read');
    }

    function makeLotaBooks (jsonObject) {
      httpClient.fetch(process.env.BackendUrl + '/book/', {
        method: 'post',
        body: json(jsonObject)
      })
      .then(response=>response.json())
      .then(data=>{
        router.navigate('/bookshelf');
      });
    }
    // if (CSVFilePath.files[0] !== null){
    // TODO: Parse all csv files
    // TODO: add check for browser support of FileReader
    //TODO: do not run file reader if no csv file in the form
    this.reader.onload = loaded;
    this.reader.onerror = errorHandler;
    this.reader.readAsText(CSVFilePath.files[0]);
  }
}
<|endoftext|>


<commit_before>/*global navigator*/
var dom = require('shipyard/dom'),
    Request = require('shipyard/http/Request'),
    URI = require('shipyard/utils/URI');

// for minifier to include flightdeck app, since it's currently always
// initiated in base.html
var flightdeck = require('flightdeck');

exports.init = function(fd) {
	dom.$('UI_BrowserID_Img').addListener('click',function(){
		navigator.id.getVerifiedEmail(function(assertion) {
			if (assertion) {

				new Request({
				url: '/user/browserid-login/',
				method: 'POST',
				data: {
                    assertion: assertion
                },
				onSuccess: function(res){
					var next = new URI(String(dom.window.get('location'))).getData('next');
                    dom.window.getNode().location = next || '/usr/dashboard';
				},
				onFailure: function(res){
					if(this.xhr.status === 401){
						fd.error.alert("BrowserID login failed",
							"Is this e-mail registered at addons.mozilla.org?");
					} else if(this.xhr.status === 403 ){
						fd.error.alert("BrowserID",
							"Not enabled");
					}
				}
				}).send();
			} else {
				fd.error.alert("BrowserID Login Failed",
					"Please try again");
			}
		});
	});

    var old_auth = dom.$('old_auth');
    if (old_auth) {
        old_auth.addListener('click', function(e) {
            e.stop();
            dom.$('login_form').setStyle('display', 'block');
        });
    }
};
<commit_msg>add csrftoken header back to browserid request<commit_after>/*global navigator*/
var dom = require('shipyard/dom'),
    Request = require('shipyard/http/Request'),
    URI = require('shipyard/utils/URI');

// for minifier to include flightdeck app, since it's currently always
// initiated in base.html
var flightdeck = require('flightdeck');

exports.init = function(fd) {
	dom.$('UI_BrowserID_Img').addListener('click',function(){
		navigator.id.getVerifiedEmail(function(assertion) {
			if (assertion) {

				new Request({
					url: '/user/browserid-login/',
					headers: {
						'X-CSRFToken': dom.$$('input[name=csrfmiddlewaretoken]').get('value')
					},
					method: 'POST',
					data: {
						assertion: assertion
					},
					onSuccess: function(res){
						var next = new URI(String(dom.window.get('location'))).getData('next');
						dom.window.getNode().location = next || '/usr/dashboard';
					},
					onFailure: function(res){
						if(this.xhr.status === 401){
							fd.error.alert("BrowserID login failed",
								"Is this e-mail registered at addons.mozilla.org?");
						} else if(this.xhr.status === 403 ){
							fd.error.alert("BrowserID",
								"Not enabled");
						}
					}
				}).send();
			} else {
				fd.error.alert("BrowserID Login Failed",
					"Please try again");
			}
		});
	});

    var old_auth = dom.$('old_auth');
    if (old_auth) {
        old_auth.addListener('click', function(e) {
            e.stop();
            dom.$('login_form').setStyle('display', 'block');
        });
    }
};
<|endoftext|>


<commit_before>// copyright1.js
//
// This is a simple test script that does the following:
//  open a website
//  validate title
//  verify copyright text
//

// required libraries
var webdriverio = require('webdriverio'),
  should = require('should');

// a test script block or suite
describe('Copyright Test for Web Driver IO - Tutorial Test Page Website', function() {

  // set timeout to 10 seconds
	this.timeout(10000);
  var driver = {};

  // hook to run before tests
  before( function (done) {
    // load the driver for browser
    driver = webdriverio.remote({ desiredCapabilities: {browserName: 'firefox'} });
    driver.init(done);
  });

  // a test spec - "specification"
  it('should be load correct page and title', function () {
    // load page, then call function()
    return driver
      .url('http://www.tlkeith.com/WebDriverIOTutorialTest.html')
      // get title, then pass title to function()
      .getTitle().then(function (title) {
        // verify title
        (title).should.be.equal("Web Driver IO - Tutorial Test Page");
        // uncomment for console debug
        // console.log('Current Page Title: ' + title);
      });
  });

  // Verify Copyright text using id as element selector
  it('should contain Copyright text', function () {
    return driver
      .getText("#copyright").then(function (link) {
        console.log('Copyright found: ' + link);
        (link).should.equal("Tony Keith - tlkeith.com @ 2015 - All rights reserved.");
      });
  });

  // Verify Copyright text using xpath as element selector
  it('should contain Copyright text', function () {
    return driver
      // use p[1] since there more than on <p> tag
      .getText("//footer/center/p[1]").then(function (link) {
        console.log('Copyright found: ' + link);
        (link).should.equal("Tony Keith - tlkeith.com @ 2015 - All rights reserved.");
      });
  });

  // a "hook" to run after all tests in this block
	after(function(done) {
    driver.end(done);
  });
});<commit_msg>Added grunt-webdriver detection<commit_after>// copyright1.js
//
// This is a simple test script that does the following:
//  open a website
//  validate title
//  verify copyright text
//

// required libraries
var webdriverio = require('webdriverio'),
  should = require('should');

// a test script block or suite
describe('Copyright Test for Web Driver IO - Tutorial Test Page Website', function() {

  // set timeout to 10 seconds
	this.timeout(10000);
  var driver = {};

  // hook to run before tests
  before( function (done) {
    // check for global browser (grunt + grunt-webdriver)
    if(typeof browser === "undefined") {
      // load the driver for browser
      driver = webdriverio.remote({ desiredCapabilities: {browserName: 'firefox'} });
      driver.init(done);
    } else {
      // grunt will load the browser driver
      driver = browser;
      done();
    }
  });

  // a test spec - "specification"
  it('should be load correct page and title', function () {
    // load page, then call function()
    return driver
      .url('http://www.tlkeith.com/WebDriverIOTutorialTest.html')
      // get title, then pass title to function()
      .getTitle().then(function (title) {
        // verify title
        (title).should.be.equal("Web Driver IO - Tutorial Test Page");
        // uncomment for console debug
        // console.log('Current Page Title: ' + title);
      });
  });

  // Verify Copyright text using id as element selector
  it('should contain Copyright text', function () {
    return driver
      .getText("#copyright").then(function (link) {
        console.log('Copyright found: ' + link);
        (link).should.equal("Tony Keith - tlkeith.com @ 2015 - All rights reserved.");
      });
  });

  // Verify Copyright text using xpath as element selector
  it('should contain Copyright text', function () {
    return driver
      // use p[1] since there more than on <p> tag
      .getText("//footer/center/p[1]").then(function (link) {
        console.log('Copyright found: ' + link);
        (link).should.equal("Tony Keith - tlkeith.com @ 2015 - All rights reserved.");
      });
  });

  // a "hook" to run after all tests in this block
	after(function(done) {
    driver.end(done);
  });
});<|endoftext|>


<commit_before>lingcod.rest.kmlEditor = function(options){

    if(!options || !options.url || !options.appendTo || !options.gex || !options.ge || !options.div || !options.client){
        throw('kmlEditor needs url, appendTo, ge, gex, client, and div options');
    }

    var kmlLoaded = function(kml){
        var configs = options.client.parseDocument(kml.getKml());
        while(create_menu.getItemCount() > 0){
            create_menu.removeItemAt(0);
        }
        for(var key in configs){
            var config = configs[key];
            var item = new goog.ui.MenuItem(config.title);
            create_menu.addItem(item);
            item.mm_data = config;
        }
        that.kmlEl.addClass('kmlEditor');
        var a = that.kmlEl.find('> .marinemap-tree-category > a');
        that.kmlEl.find('> .marinemap-tree-category > span.badges').remove();
        that.el.find('h1').text(a.text());
        a.hide();
    }

    var that = {};

    that.el = $('

');

    that.kmlEl = that.el.find('.kmllist');

    // var create_menu_children = function(){
    //     var children = [];
    //     var attr = new goog.ui.MenuItem('View Attributes');
    //     children.push(attr);
    //     var edit = new goog.ui.MenuItem('Edit');
    //     children.push(edit);
    //     var copy = new goog.ui.MenuItem('Copy');
    //     children.push(copy);
    //     var share = new goog.ui.MenuItem('Share');
    //     children.push(share);
    //     children.push(new goog.ui.MenuSeparator());
    //     return children;
    // }

    var setSelectionMenuItemEnabled = function(enabled){
        for(var i=0;i<enableWhenSelected.length;i++){
            enableWhenSelected[i].setEnabled(enabled);
        }
    }

    var tbar = new goog.ui.Toolbar();
    var create_menu = new goog.ui.Menu();
    var create_button = new goog.ui.ToolbarMenuButton('Create New', create_menu);
    tbar.addChild(create_button, true);
    goog.events.listen(create_menu, 'action', function(e) {
        options.client.create(e.target.mm_data, {
            success: function(location){
                // possible memory leak!!!!!!!
                forest.refresh(options.url, {
                    cachebust: true,
                    callback: kmlLoaded
                });
                setSelectionMenuItemEnabled(false);
            },
            error: function(){
                alert('An error occured while saving your data. If the problem persists, please contact an administrator at help@marinemap.org.');
            }
        });
    });
    tbar.addChild(new goog.ui.ToolbarSeparator(), true);

    var attr = new goog.ui.ToolbarButton('Attributes');
    attr.setEnabled(false);
    attr.setTooltip("Show the selected feature's attributes");
    goog.events.listen(attr, 'action', function(e) {
        options.client.show(that.selected.data('kml'));
    });
    tbar.addChild(attr, true);

    var edit = new goog.ui.ToolbarButton('Edit');
    edit.setEnabled(false);
    goog.events.listen(edit, 'action', function(e) {
        var kmlObject = that.selected.data('kml');
        options.gex.dom.removeObject(kmlObject);
        options.client.update(kmlObject, {
            success: function(location){
                forest.refresh(options.url, {
                    cachebust: true,
                    callback: kmlLoaded
                });
                setSelectionMenuItemEnabled(false);
            },
            cancel: function(){
                options.ge.getFeatures().appendChild(kmlObject);
            },
            error: function(){
                alert('An error occured while saving your data. If the problem persists, please contact an administrator at help@marinemap.org.');
                options.ge.getFeatures().appendChild(kmlObject);
            }
        });
    });
    tbar.addChild(edit, true);

    var del = new goog.ui.ToolbarButton('Delete');
    del.setEnabled(false);
    goog.events.listen(del, 'action', function(e) {
        var kmlObject = that.selected.data('kml');
        options.client.destroy(kmlObject, {
            success: function(location){
                options.gex.dom.removeObject(kmlObject);
                that.selected.remove();
            },
            error: function(){
                alert('An error occured while trying to delete this feature.');
            }
        });
    });
    tbar.addChild(del, true);

    var export_menu = new goog.ui.Menu();
    // export_menu.addItem(new goog.ui.MenuItem('to kml (Google Earth)'));
    // export_menu.addItem(new goog.ui.MenuItem('to shapefile'));
    var export_button = new goog.ui.ToolbarMenuButton('Export', export_menu);
    export_button.setEnabled(false);
    tbar.addChild(export_button, true);

    var copy = new goog.ui.ToolbarButton('Copy');
    copy.setEnabled(false);
    tbar.addChild(copy, true);

    var share = new goog.ui.ToolbarButton('Share');
    share.setEnabled(false);
    tbar.addChild(share, true);

    var enableWhenSelected = [attr, edit, del, export_button, copy, share];

    tbar.render(that.el.find('.toolbar')[0]);

    $(options.appendTo).append(that.el);

    // var pm = new goog.ui.PopupMenu();
    // var items = create_menu_children();
    // for(var i=0;i<items.length; i++){
    //     pm.addItem(items[i]);
    // }

    var forest = lingcod.kmlForest({
        ge: options.ge,
        gex: options.gex,
        div: options.div,
        element: that.kmlEl
        // contextMenu: pm
    });

    $(forest.tree).bind('itemSelect', function(e, selected, previously){
        that.selected = selected;
        setSelectionMenuItemEnabled(!!selected);
        // clear export menu
        while(export_menu.getItemCount() > 0){
            var item = export_menu.getItemAt(0);
            export_menu.removeItemAt(0);
            item.dispose();
        }
        if(that.selected){
            var kmlObject = that.selected.data('kml');
            addExportItems(export_menu, kmlObject);
        }
    });

    var addExportItems = function(menu, kmlObject){
        $(kmlObject.getKml()).find('atom\\:link[rel=alt]').each(function(){
            var title = $(this).attr('title');
            var href = $(this).attr('href');
            var item = new goog.ui.MenuItem(title);
            menu.addItem(item);
            goog.events.listen(item, 'action', function(e) {
                window.location = href;
            });
        });
    }

    $(forest.tree).bind('itemDoubleClick', function(e, item){
        var kmlObject = item.data('kml');
        if(kmlObject && $(kmlObject.getKml()).find('atom\\:link[rel=self]').length === 1){
            options.client.show(item.data('kml'));
        }
    });

    // $(forest.tree).bind('itemContext', function(e, d, item){
    //     var kmlObject = item.data('kml');
    //     if(kmlObject && $(kmlObject.getKml()).find('atom\\:link[rel=self]').length === 1){
    //         var pm = new goog.ui.PopupMenu();
    //         var items = create_menu_children();
    //         for(var i=0;i<items.length; i++){
    //             pm.addItem(items[i]);
    //         }
    //         pm.render(document.body);
    //
    //         pm.attach(
    //             item[0],
    //             goog.positioning.Corner.TOP_LEFT,
    //             goog.positioning.Corner.BOTTOM_LEFT);
    //
    //         // pm.attach(item[0]);
    //     }
    // });

    forest.add(options.url, {
        cachebust: true,
        callback: kmlLoaded
    });

    return that;
}<commit_msg>realized I should be refreshing the kml, rather than manually removing items from the list and map after deleting a feature.<commit_after>lingcod.rest.kmlEditor = function(options){

    if(!options || !options.url || !options.appendTo || !options.gex || !options.ge || !options.div || !options.client){
        throw('kmlEditor needs url, appendTo, ge, gex, client, and div options');
    }

    var kmlLoaded = function(kml){
        var configs = options.client.parseDocument(kml.getKml());
        while(create_menu.getItemCount() > 0){
            create_menu.removeItemAt(0);
        }
        for(var key in configs){
            var config = configs[key];
            var item = new goog.ui.MenuItem(config.title);
            create_menu.addItem(item);
            item.mm_data = config;
        }
        that.kmlEl.addClass('kmlEditor');
        var a = that.kmlEl.find('> .marinemap-tree-category > a');
        that.kmlEl.find('> .marinemap-tree-category > span.badges').remove();
        that.el.find('h1').text(a.text());
        a.hide();
    }

    var that = {};

    that.el = $('

');

    that.kmlEl = that.el.find('.kmllist');

    // var create_menu_children = function(){
    //     var children = [];
    //     var attr = new goog.ui.MenuItem('View Attributes');
    //     children.push(attr);
    //     var edit = new goog.ui.MenuItem('Edit');
    //     children.push(edit);
    //     var copy = new goog.ui.MenuItem('Copy');
    //     children.push(copy);
    //     var share = new goog.ui.MenuItem('Share');
    //     children.push(share);
    //     children.push(new goog.ui.MenuSeparator());
    //     return children;
    // }

    var refresh = function(){
        forest.refresh(options.url, {
            cachebust: true,
            callback: kmlLoaded
        });
        setSelectionMenuItemEnabled(false);
    }

    var setSelectionMenuItemEnabled = function(enabled){
        for(var i=0;i<enableWhenSelected.length;i++){
            enableWhenSelected[i].setEnabled(enabled);
        }
    }

    var tbar = new goog.ui.Toolbar();
    var create_menu = new goog.ui.Menu();
    var create_button = new goog.ui.ToolbarMenuButton('Create New', create_menu);
    tbar.addChild(create_button, true);
    goog.events.listen(create_menu, 'action', function(e) {
        options.client.create(e.target.mm_data, {
            success: function(location){
                // possible memory leak!!!!!!!
                forest.refresh(options.url, {
                    cachebust: true,
                    callback: kmlLoaded
                });
                setSelectionMenuItemEnabled(false);
            },
            error: function(){
                alert('An error occured while saving your data. If the problem persists, please contact an administrator at help@marinemap.org.');
            }
        });
    });
    tbar.addChild(new goog.ui.ToolbarSeparator(), true);

    var attr = new goog.ui.ToolbarButton('Attributes');
    attr.setEnabled(false);
    attr.setTooltip("Show the selected feature's attributes");
    goog.events.listen(attr, 'action', function(e) {
        options.client.show(that.selected.data('kml'));
    });
    tbar.addChild(attr, true);

    var edit = new goog.ui.ToolbarButton('Edit');
    edit.setEnabled(false);
    goog.events.listen(edit, 'action', function(e) {
        var kmlObject = that.selected.data('kml');
        options.gex.dom.removeObject(kmlObject);
        options.client.update(kmlObject, {
            success: function(location){
                refresh();
            },
            cancel: function(){
                options.ge.getFeatures().appendChild(kmlObject);
            },
            error: function(){
                alert('An error occured while saving your data. If the problem persists, please contact an administrator at help@marinemap.org.');
                options.ge.getFeatures().appendChild(kmlObject);
            }
        });
    });
    tbar.addChild(edit, true);

    var del = new goog.ui.ToolbarButton('Delete');
    del.setEnabled(false);
    goog.events.listen(del, 'action', function(e) {
        var kmlObject = that.selected.data('kml');
        options.client.destroy(kmlObject, {
            success: function(location){
                refresh();
            },
            error: function(){
                alert('An error occured while trying to delete this feature.');
            }
        });
    });
    tbar.addChild(del, true);

    var export_menu = new goog.ui.Menu();
    // export_menu.addItem(new goog.ui.MenuItem('to kml (Google Earth)'));
    // export_menu.addItem(new goog.ui.MenuItem('to shapefile'));
    var export_button = new goog.ui.ToolbarMenuButton('Export', export_menu);
    export_button.setEnabled(false);
    tbar.addChild(export_button, true);

    var copy = new goog.ui.ToolbarButton('Copy');
    copy.setEnabled(false);
    tbar.addChild(copy, true);

    var share = new goog.ui.ToolbarButton('Share');
    share.setEnabled(false);
    tbar.addChild(share, true);

    var enableWhenSelected = [attr, edit, del, export_button, copy, share];

    tbar.render(that.el.find('.toolbar')[0]);

    $(options.appendTo).append(that.el);

    // var pm = new goog.ui.PopupMenu();
    // var items = create_menu_children();
    // for(var i=0;i<items.length; i++){
    //     pm.addItem(items[i]);
    // }

    var forest = lingcod.kmlForest({
        ge: options.ge,
        gex: options.gex,
        div: options.div,
        element: that.kmlEl
        // contextMenu: pm
    });

    $(forest.tree).bind('itemSelect', function(e, selected, previously){
        that.selected = selected;
        setSelectionMenuItemEnabled(!!selected);
        // clear export menu
        while(export_menu.getItemCount() > 0){
            var item = export_menu.getItemAt(0);
            export_menu.removeItemAt(0);
            item.dispose();
        }
        if(that.selected){
            var kmlObject = that.selected.data('kml');
            addExportItems(export_menu, kmlObject);
        }
    });

    var addExportItems = function(menu, kmlObject){
        $(kmlObject.getKml()).find('atom\\:link[rel=alt]').each(function(){
            var title = $(this).attr('title');
            var href = $(this).attr('href');
            var item = new goog.ui.MenuItem(title);
            menu.addItem(item);
            goog.events.listen(item, 'action', function(e) {
                window.location = href;
            });
        });
    }

    $(forest.tree).bind('itemDoubleClick', function(e, item){
        var kmlObject = item.data('kml');
        if(kmlObject && $(kmlObject.getKml()).find('atom\\:link[rel=self]').length === 1){
            options.client.show(item.data('kml'));
        }
    });

    // $(forest.tree).bind('itemContext', function(e, d, item){
    //     var kmlObject = item.data('kml');
    //     if(kmlObject && $(kmlObject.getKml()).find('atom\\:link[rel=self]').length === 1){
    //         var pm = new goog.ui.PopupMenu();
    //         var items = create_menu_children();
    //         for(var i=0;i<items.length; i++){
    //             pm.addItem(items[i]);
    //         }
    //         pm.render(document.body);
    //
    //         pm.attach(
    //             item[0],
    //             goog.positioning.Corner.TOP_LEFT,
    //             goog.positioning.Corner.BOTTOM_LEFT);
    //
    //         // pm.attach(item[0]);
    //     }
    // });

    forest.add(options.url, {
        cachebust: true,
        callback: kmlLoaded
    });

    return that;
}<|endoftext|>


<commit_before>/**
 * Check the dimensions of the given element
 * @param  {String}   elem         Element selector
 * @param  {String}   falseCase    Whether to check if the dimensions match or
 *                                 not
 * @param  {String}   expectedSize Expected size
 * @param  {String}   dimension    Dimension to check (broad or tall)
 */
module.exports = (elem, falseCase, expectedSize, dimension) => {
    /**
     * The size of the given element
     * @type {Object}
     */
    const elementSize = browser.getElementSize(elem);

    /**
     * Parsed size to check for
     * @type {Int}
     */
    const intExpectedSize = parseInt(expectedSize, 10);

    /**
     * The size property to check against
     * @type {Int}
     */
    let origionalSize = elementSize.height;

    /**
     * The label of the checked property
     * @type {String}
     */
    let label = 'height';

    if (dimension === 'broad') {
        origionalSize = elementSize.width;
        label = 'width';
    }

    if (falseCase) {
        expect(origionalSize).to.not
            .equal(
                intExpectedSize,
                `Element "${elem}" should not have a ${label} of ` +
                `${intExpectedSize}px`
            );
    } else {
        expect(origionalSize).to
            .equal(
                intExpectedSize,
                `Element "${elem}" should have a ${label} of ` +
                `${intExpectedSize}px, but is ${origionalSize}px`
            );
    }
};
<commit_msg>Corrected a typo<commit_after>/**
 * Check the dimensions of the given element
 * @param  {String}   elem         Element selector
 * @param  {String}   falseCase    Whether to check if the dimensions match or
 *                                 not
 * @param  {String}   expectedSize Expected size
 * @param  {String}   dimension    Dimension to check (broad or tall)
 */
module.exports = (elem, falseCase, expectedSize, dimension) => {
    /**
     * The size of the given element
     * @type {Object}
     */
    const elementSize = browser.getElementSize(elem);

    /**
     * Parsed size to check for
     * @type {Int}
     */
    const intExpectedSize = parseInt(expectedSize, 10);

    /**
     * The size property to check against
     * @type {Int}
     */
    let originalSize = elementSize.height;

    /**
     * The label of the checked property
     * @type {String}
     */
    let label = 'height';

    if (dimension === 'broad') {
        originalSize = elementSize.width;
        label = 'width';
    }

    if (falseCase) {
        expect(originalSize).to.not
            .equal(
                intExpectedSize,
                `Element "${elem}" should not have a ${label} of ` +
                `${intExpectedSize}px`
            );
    } else {
        expect(originalSize).to
            .equal(
                intExpectedSize,
                `Element "${elem}" should have a ${label} of ` +
                `${intExpectedSize}px, but is ${originalSize}px`
            );
    }
};
<|endoftext|>


<commit_before>import {getMathGenLex} from '../../lib/genlex/genlex';
import {F} from '../../lib/parsec/index';
import stream from '../../lib/stream/index';

/*
 Implementing general solution :
 E -> T E'
 E' -> + TE'  |  eps
 T -> F T'
 T' -> * FT'  |  eps
 F -> NUMBER | ( E )   (https://en.wikipedia.org/wiki/Operator-precedence_parser)

 * Expr -> SubExpr then OptYieldExpr
 * OptYieldExpr -> YieldExpr.opt()
 * YieldExpr ->  + then SubExpr then YieldExpr
 * PriorExpr -> Terminal then OptPriorExpr
 * OptPriorExpr -> PriorExpr.opt()
 * PriorExpr ->  * then Terminal then OptPriorExpr
 * Terminal -> (Expr)| Number | -Terminal | Expr  // care of priority !

 */

// tokens
const genlex = getMathGenLex();
const {number, plus, minus, mult, div, open, close} = genlex.tokens();

const priorToken = () => mult.or(div);
const yieldToken = () => plus.or(minus);

function terminal() {
    return parenthesis()
        .or(number)
        .or(negative())
        .or(F.lazy(expression))
}

function negative() {
    return minus.drop().then(F.lazy(terminal)).map(x => -x);
}

function parenthesis() {
    return open.drop().then(F.lazy(expression)).then(close.drop())
}

function expression() {
    return priorExpr().flatMap(optYieldExpr);
}

function optYieldExpr(left) {

    return yieldExpr(left).opt()
        .map(opt => opt.isPresent() ? opt.get() : left)
}

function yieldExpr(left) {
    return yieldToken()
        .then(priorExpr())
        .map(([token, right]) =>
            token === '+' ? left + right : left - right)
        .flatMap(optYieldExpr);
}

function priorExpr() {
    return terminal().flatMap(optSubPriorExp);
}

function optSubPriorExp(priorValue) {
    return subPriorExpr(priorValue).opt()
        .map(opt => opt.isPresent() ? opt.get() : priorValue);
}

function subPriorExpr(priorValue) {

    return priorToken().then(terminal())
        .map(([token, left]) => token === '*' ? priorValue * left : priorValue / left)
        .flatMap(optSubPriorExp)
}

function multParser() {

    const parser = expression();

    return genlex.use(parser.then(F.eos().drop()));
}

export default {
    setUp: function (done) {
        done();
    },

    'expect multExpr to make mults': function (test) {
        let parsing = multParser().parse(stream.ofString('3 * 4'));
        test.equal(parsing.value, 12, 'simple multiplication');

        parsing = multParser().parse(stream.ofString('14 / 4'));

        test.equal(parsing.value, 3.5, 'simple division');

        parsing = multParser().parse(stream.ofString('14 / 4*3 '));

        test.equal(parsing.value, 10.5, 'combine mult and div');

        parsing = multParser().parse(stream.ofString('14 / 4*3 /2*  2 '));

        test.equal(parsing.value, 10.5, 'combine more mult and div');

        test.done();
    },
    'expect multExpr to make negative priorities': function (test) {
        let parsing = multParser().parse(stream.ofString('3 * -4'));
        test.equal(parsing.value, -12, 'negative multiplication');

        test.done();
    },
    'expect Expr to be inside parenthesis': function (test) {

        let parsing = multParser().parse(stream.ofString('3 * (4)'));
        test.equal(parsing.value, 12, 'simple parenthesis expr');

        parsing = multParser().parse(stream.ofString('3 * (2*4)'));
        test.equal(parsing.value, 24, 'more complexe parenthesis expr');

        parsing = multParser().parse(stream.ofString('3 * (2*(4))'));
        test.equal(parsing.value, 24, 'deep parenthesis expr');

        test.done();
    },
    'expect + and * to respect priorities': function (test) {

        let parsing = multParser().parse(stream.ofString('3 +2*4 '));
        test.equal(parsing.value, 11, 'simple multiplication');

        test.done();
    },
    'expect complex calcul to true and lightening fast': function (test) {

        const calculus = '3 +2*4 -((2*45-78)*2*(6*(9-8)+3*(2-5)  ))';

        let time = new Date().getTime();
        let parsing = multParser().parse(stream.ofString(calculus));
        time = new Date().getTime() - time;

        test.equal(parsing.value, 83, 'complex multiplication');
        test.ok(time < 50, 'parsing is too slow');

        test.done();
    },
    'expect - and / to respect priorities': function (test) {

        let parsing = multParser().parse(stream.ofString('3 + -4/2*5 '));
        test.equal(parsing.value, -7, 'bad priorities');

        test.done();
    },

}<commit_msg>v0.8 - Removing speed test because of cover<commit_after>import {getMathGenLex} from '../../lib/genlex/genlex';
import {F} from '../../lib/parsec/index';
import stream from '../../lib/stream/index';

/*
 Implementing general solution :
 E -> T E'
 E' -> + TE'  |  eps
 T -> F T'
 T' -> * FT'  |  eps
 F -> NUMBER | ( E )   (https://en.wikipedia.org/wiki/Operator-precedence_parser)

 * Expr -> SubExpr then OptYieldExpr
 * OptYieldExpr -> YieldExpr.opt()
 * YieldExpr ->  + then SubExpr then YieldExpr
 * PriorExpr -> Terminal then OptPriorExpr
 * OptPriorExpr -> PriorExpr.opt()
 * PriorExpr ->  * then Terminal then OptPriorExpr
 * Terminal -> (Expr)| Number | -Terminal | Expr  // care of priority !

 */

// tokens
const genlex = getMathGenLex();
const {number, plus, minus, mult, div, open, close} = genlex.tokens();

const priorToken = () => mult.or(div);
const yieldToken = () => plus.or(minus);

function terminal() {
    return parenthesis()
        .or(number)
        .or(negative())
        .or(F.lazy(expression))
}

function negative() {
    return minus.drop().then(F.lazy(terminal)).map(x => -x);
}

function parenthesis() {
    return open.drop().then(F.lazy(expression)).then(close.drop())
}

function expression() {
    return priorExpr().flatMap(optYieldExpr);
}

function optYieldExpr(left) {

    return yieldExpr(left).opt()
        .map(opt => opt.isPresent() ? opt.get() : left)
}

function yieldExpr(left) {
    return yieldToken()
        .then(priorExpr())
        .map(([token, right]) =>
            token === '+' ? left + right : left - right)
        .flatMap(optYieldExpr);
}

function priorExpr() {
    return terminal().flatMap(optSubPriorExp);
}

function optSubPriorExp(priorValue) {
    return subPriorExpr(priorValue).opt()
        .map(opt => opt.isPresent() ? opt.get() : priorValue);
}

function subPriorExpr(priorValue) {

    return priorToken().then(terminal())
        .map(([token, left]) => token === '*' ? priorValue * left : priorValue / left)
        .flatMap(optSubPriorExp)
}

function multParser() {

    const parser = expression();

    return genlex.use(parser.then(F.eos().drop()));
}

export default {
    setUp: function (done) {
        done();
    },

    'expect multExpr to make mults': function (test) {
        let parsing = multParser().parse(stream.ofString('3 * 4'));
        test.equal(parsing.value, 12, 'simple multiplication');

        parsing = multParser().parse(stream.ofString('14 / 4'));

        test.equal(parsing.value, 3.5, 'simple division');

        parsing = multParser().parse(stream.ofString('14 / 4*3 '));

        test.equal(parsing.value, 10.5, 'combine mult and div');

        parsing = multParser().parse(stream.ofString('14 / 4*3 /2*  2 '));

        test.equal(parsing.value, 10.5, 'combine more mult and div');

        test.done();
    },
    'expect multExpr to make negative priorities': function (test) {
        let parsing = multParser().parse(stream.ofString('3 * -4'));
        test.equal(parsing.value, -12, 'negative multiplication');

        test.done();
    },
    'expect Expr to be inside parenthesis': function (test) {

        let parsing = multParser().parse(stream.ofString('3 * (4)'));
        test.equal(parsing.value, 12, 'simple parenthesis expr');

        parsing = multParser().parse(stream.ofString('3 * (2*4)'));
        test.equal(parsing.value, 24, 'more complexe parenthesis expr');

        parsing = multParser().parse(stream.ofString('3 * (2*(4))'));
        test.equal(parsing.value, 24, 'deep parenthesis expr');

        test.done();
    },
    'expect + and * to respect priorities': function (test) {

        let parsing = multParser().parse(stream.ofString('3 +2*4 '));
        test.equal(parsing.value, 11, 'simple multiplication');

        test.done();
    },

    'expect - and / to respect priorities': function (test) {

        let parsing = multParser().parse(stream.ofString('3 + -4/2*5 '));
        test.equal(parsing.value, -7, 'bad priorities');

        test.done();
    },

}<|endoftext|>


<commit_before>// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('/__/firebase/7.11.0/firebase-app.js');
importScripts('/__/firebase/7.11.0/firebase-messaging.js');
importScripts('/__/firebase/init.js');

const messaging = firebase.messaging();

/**
 * Here is is the code snippet to initialize Firebase Messaging in the Service
 * Worker when your app is not hosted on Firebase Hosting.

 // [START initialize_firebase_in_sw]
 // Give the service worker access to Firebase Messaging.
 // Note that you can only use Firebase Messaging here, other Firebase libraries
 // are not available in the service worker.
 importScripts('https://www.gstatic.com/firebasejs/7.11.0/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/7.11.0/firebase-messaging.js');

 // Initialize the Firebase app in the service worker by passing in the
 // messagingSenderId.
 firebase.initializeApp({
   'messagingSenderId': 'YOUR-SENDER-ID'
 });

 // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 const messaging = firebase.messaging();
 // [END initialize_firebase_in_sw]
 **/

// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
// [END background_handler]
<commit_msg>Fix FCM service worker setup code for >= 7.0.0. (#422)<commit_after>// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('/__/firebase/7.11.0/firebase-app.js');
importScripts('/__/firebase/7.11.0/firebase-messaging.js');
importScripts('/__/firebase/init.js');

const messaging = firebase.messaging();

/**
 * Here is is the code snippet to initialize Firebase Messaging in the Service
 * Worker when your app is not hosted on Firebase Hosting.

 // [START initialize_firebase_in_sw]
 // Give the service worker access to Firebase Messaging.
 // Note that you can only use Firebase Messaging here, other Firebase libraries
 // are not available in the service worker.
 importScripts('https://www.gstatic.com/firebasejs/7.11.0/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/7.11.0/firebase-messaging.js');

 // Initialize the Firebase app in the service worker by passing in
 // your app's Firebase config object.
 // https://firebase.google.com/docs/web/setup#config-object
 firebase.initializeApp({
   apiKey: 'api-key',
   authDomain: 'project-id.firebaseapp.com',
   databaseURL: 'https://project-id.firebaseio.com',
   projectId: 'project-id',
   storageBucket: 'project-id.appspot.com',
   messagingSenderId: 'sender-id',
   appId: 'app-id',
   measurementId: 'G-measurement-id',
 });

 // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 const messaging = firebase.messaging();
 // [END initialize_firebase_in_sw]
 **/

// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
// [END background_handler]
<|endoftext|>


<commit_before>const debug = require("debug")("compile");
const path = require("path");
const expect = require("@truffle/expect");
const findContracts = require("@truffle/contract-sources");
const Config = require("@truffle/config");
const Profiler = require("./profiler");
const CompilerSupplier = require("./compilerSupplier");
const { run } = require("./run");

const normalizeOptions = options => {
  if (options.logger === undefined) options.logger = console;

  expect.options(options, ["contracts_directory", "compilers"]);
  expect.options(options.compilers, ["solc"]);

  options.compilers.solc.settings.evmVersion =
    options.compilers.solc.settings.evmVersion ||
    options.compilers.solc.evmVersion;
  options.compilers.solc.settings.optimizer =
    options.compilers.solc.settings.optimizer ||
    options.compilers.solc.optimizer ||
    {};

  // Grandfather in old solc config
  if (options.solc) {
    options.compilers.solc.settings.evmVersion = options.solc.evmVersion;
    options.compilers.solc.settings.optimizer = options.solc.optimizer;
  }

  // Certain situations result in `{}` as a value for compilationTargets
  // Previous implementations treated any value lacking `.length` as equivalent
  // to `[]`
  if (!options.compilationTargets || !options.compilationTargets.length) {
    options.compilationTargets = [];
  }

  return options;
};

const Compile = {
  // this takes an object with keys being the name and values being source
  // material as well as an options object
  async sources({ sources, options }) {
    options = Config.default().merge(options);
    const compilation = await run(sources, normalizeOptions(options));
    return compilation.contracts.length > 0
      ? { compilations: [compilation] }
      : { compilations: [] };
  },

  async all(options) {
    const paths = [
      ...new Set([
        ...(await findContracts(options.contracts_directory)),
        ...(options.files || [])
      ])
    ];

    return await Compile.sourcesWithDependencies({
      paths,
      options
    });
  },

  async necessary(options) {
    options.logger = options.logger || console;

    const paths = await Profiler.updated(options);

    return await Compile.sourcesWithDependencies({
      paths,
      options
    });
  },

  // this takes an array of paths and options
  async sourcesWithDependencies({ paths, options }) {
    options.logger = options.logger || console;
    options.contracts_directory = options.contracts_directory || process.cwd();

    expect.options(options, [
      "working_directory",
      "contracts_directory",
      "resolver"
    ]);

    options = Config.default().merge(options);
    const { allSources, compilationTargets } = await Profiler.requiredSources(
      options.with({
        paths,
        base_path: options.contracts_directory,
        resolver: options.resolver
      })
    );

    const hasTargets = compilationTargets.length;

    hasTargets
      ? Compile.display(compilationTargets, options)
      : Compile.display(allSources, options);

    // when there are no sources, don't call run
    if (Object.keys(allSources).length === 0) {
      return { compilations: [] };
    }

    options.compilationTargets = compilationTargets;
    const { sourceIndexes, sources, contracts, compiler } = await run(
      allSources,
      normalizeOptions(options)
    );
    const { name, version } = compiler;
    // returns CompilerResult - see @truffle/compile-common
    return contracts.length > 0
      ? {
          compilations: [
            {
              sourceIndexes,
              sources,
              contracts,
              compiler: { name, version }
            }
          ]
        }
      : { compilations: [] };
  },

  display(paths, options) {
    if (options.quiet !== true) {
      if (!Array.isArray(paths)) {
        paths = Object.keys(paths);
      }

      const blacklistRegex = /^truffle\//;

      const sources = paths
        .sort()
        .map(contract => {
          if (path.isAbsolute(contract)) {
            contract =
              "." +
              path.sep +
              path.relative(options.working_directory, contract);
          }
          if (contract.match(blacklistRegex)) return;
          return contract;
        })
        .filter(contract => contract);
      options.events.emit("compile:sourcesToCompile", {
        sourceFileNames: sources
      });
    }
  }
};

module.exports = {
  Compile,
  CompilerSupplier
};
<commit_msg>Filter out JSON files in sourcesWithDependencies<commit_after>const debug = require("debug")("compile");
const path = require("path");
const expect = require("@truffle/expect");
const findContracts = require("@truffle/contract-sources");
const Config = require("@truffle/config");
const Profiler = require("./profiler");
const CompilerSupplier = require("./compilerSupplier");
const { run } = require("./run");

const normalizeOptions = options => {
  if (options.logger === undefined) options.logger = console;

  expect.options(options, ["contracts_directory", "compilers"]);
  expect.options(options.compilers, ["solc"]);

  options.compilers.solc.settings.evmVersion =
    options.compilers.solc.settings.evmVersion ||
    options.compilers.solc.evmVersion;
  options.compilers.solc.settings.optimizer =
    options.compilers.solc.settings.optimizer ||
    options.compilers.solc.optimizer ||
    {};

  // Grandfather in old solc config
  if (options.solc) {
    options.compilers.solc.settings.evmVersion = options.solc.evmVersion;
    options.compilers.solc.settings.optimizer = options.solc.optimizer;
  }

  // Certain situations result in `{}` as a value for compilationTargets
  // Previous implementations treated any value lacking `.length` as equivalent
  // to `[]`
  if (!options.compilationTargets || !options.compilationTargets.length) {
    options.compilationTargets = [];
  }

  return options;
};

const Compile = {
  // this takes an object with keys being the name and values being source
  // material as well as an options object
  async sources({ sources, options }) {
    options = Config.default().merge(options);
    const compilation = await run(sources, normalizeOptions(options));
    return compilation.contracts.length > 0
      ? { compilations: [compilation] }
      : { compilations: [] };
  },

  async all(options) {
    const paths = [
      ...new Set([
        ...(await findContracts(options.contracts_directory)),
        ...(options.files || [])
      ])
    ];

    return await Compile.sourcesWithDependencies({
      paths,
      options
    });
  },

  async necessary(options) {
    options.logger = options.logger || console;

    const paths = await Profiler.updated(options);

    return await Compile.sourcesWithDependencies({
      paths,
      options
    });
  },

  // this takes an array of paths and options
  async sourcesWithDependencies({ paths, options }) {
    options.logger = options.logger || console;
    options.contracts_directory = options.contracts_directory || process.cwd();

    expect.options(options, [
      "working_directory",
      "contracts_directory",
      "resolver"
    ]);

    // we need to remove all JSON files so Vyper-related stuff doesn't get
    // sent to the compiler - the Profiler will find JSON imports
    const filteredPaths = paths.filter(path => path.extname !== ".json");

    options = Config.default().merge(options);
    const { allSources, compilationTargets } = await Profiler.requiredSources(
      options.with({
        paths: filteredPaths,
        base_path: options.contracts_directory,
        resolver: options.resolver
      })
    );

    const hasTargets = compilationTargets.length;

    hasTargets
      ? Compile.display(compilationTargets, options)
      : Compile.display(allSources, options);

    // when there are no sources, don't call run
    if (Object.keys(allSources).length === 0) {
      return { compilations: [] };
    }

    options.compilationTargets = compilationTargets;
    const { sourceIndexes, sources, contracts, compiler } = await run(
      allSources,
      normalizeOptions(options)
    );
    const { name, version } = compiler;
    // returns CompilerResult - see @truffle/compile-common
    return contracts.length > 0
      ? {
          compilations: [
            {
              sourceIndexes,
              sources,
              contracts,
              compiler: { name, version }
            }
          ]
        }
      : { compilations: [] };
  },

  display(paths, options) {
    if (options.quiet !== true) {
      if (!Array.isArray(paths)) {
        paths = Object.keys(paths);
      }

      const blacklistRegex = /^truffle\//;

      const sources = paths
        .sort()
        .map(contract => {
          if (path.isAbsolute(contract)) {
            contract =
              "." +
              path.sep +
              path.relative(options.working_directory, contract);
          }
          if (contract.match(blacklistRegex)) return;
          return contract;
        })
        .filter(contract => contract);
      options.events.emit("compile:sourcesToCompile", {
        sourceFileNames: sources
      });
    }
  }
};

module.exports = {
  Compile,
  CompilerSupplier
};
<|endoftext|>


<commit_before>const directoryTree = require('directory-tree');

const imageUtil = require('./image-utility');
const pathIdPairs = require('./path-id-pairs/path-id-pairs');
const pathIdPairsHandlerForTreeView = require('./path-id-pairs/path-id-pairs-handler-for-tree-view');
const exifManager = require('./exif-manager');

let directoryTreeRoot;

/**
 * Update selected directory to be managed in selected-directory-manager.
 * @param {string} selectedPath
 */
exports.update = async function(selectedPath) {
  directoryTreeRoot = directoryTree(selectedPath);
  updatePathIdPairs();
  await exifManager.update(directoryTreeRoot);
}

function updatePathIdPairs() {
  pathIdPairs.reset();
  return updatePathIdPairsRecursively([directoryTreeRoot]);
}

function updatePathIdPairsRecursively(directoryTreeElementArray) {
  directoryTreeElementArray.forEach(
    (directoryTreeElement) => {
      pathIdPairs.registerPath(directoryTreeElement.path);
      if(directoryTreeElement.hasOwnProperty("children")) {
        updatePathIdPairsRecursively(directoryTreeElement.children);
      }
    }
  )
}

/**
 * Generate data for jsTree.
 */
exports.generateDataForJsTree = function() {
  return generateDataForJsTreeRecursively([directoryTreeRoot]);
}

function generateDataForJsTreeRecursively(directoryTreeElementArray) {
  var jstreeElementArray = [];
  directoryTreeElementArray.forEach(
    (directoryTreeElement) => {
      var jstreeElement = {
        id: pathIdPairsHandlerForTreeView.getIdForTreeView(directoryTreeElement.path),
        text: directoryTreeElement.name,
        state: { disabled: isDisabled(directoryTreeElement) }
      };
      if(directoryTreeElement.hasOwnProperty("children")) {
        jstreeElement.children = generateDataForJsTreeRecursively(directoryTreeElement.children);
        const isAllChildrenDisabled = jstreeElement.children.every(child => child.state.disabled);
        jstreeElement.state.disabled = isAllChildrenDisabled;
      }
      jstreeElementArray.push(jstreeElement);
    }
  );
  return jstreeElementArray;
}

function isDisabled(directoryTreeElement) {
  const isFile = () => directoryTreeElement.type === "file";
  const gpsCoordinateExists = exifManager.getGpsCoordinates(directoryTreeElement.path) !== null;
  return isFile() && !gpsCoordinateExists;
}<commit_msg>Fix typo.<commit_after>const directoryTree = require('directory-tree');

const imageUtil = require('./image-utility');
const pathIdPairs = require('./path-id-pairs/path-id-pairs');
const pathIdPairsHandlerForTreeView = require('./path-id-pairs/path-id-pairs-handler-for-tree-view');
const exifManager = require('./exif-manager');

let directoryTreeRoot;

/**
 * Update selected directory to be managed in selected-directory-manager.
 * @param {string} selectedPath
 */
exports.update = async function(selectedPath) {
  directoryTreeRoot = directoryTree(selectedPath);
  updatePathIdPairs();
  await exifManager.update(directoryTreeRoot);
}

function updatePathIdPairs() {
  pathIdPairs.reset();
  return updatePathIdPairsRecursively([directoryTreeRoot]);
}

function updatePathIdPairsRecursively(directoryTreeElementArray) {
  directoryTreeElementArray.forEach(
    (directoryTreeElement) => {
      pathIdPairs.registerPath(directoryTreeElement.path);
      if(directoryTreeElement.hasOwnProperty("children")) {
        updatePathIdPairsRecursively(directoryTreeElement.children);
      }
    }
  )
}

/**
 * Generate data for jsTree.
 */
exports.generateDataForJsTree = function() {
  return generateDataForJsTreeRecursively([directoryTreeRoot]);
}

function generateDataForJsTreeRecursively(directoryTreeElementArray) {
  var jstreeElementArray = [];
  directoryTreeElementArray.forEach(
    (directoryTreeElement) => {
      var jstreeElement = {
        id: pathIdPairsHandlerForTreeView.getIdForTreeView(directoryTreeElement.path),
        text: directoryTreeElement.name,
        state: { disabled: isDisabled(directoryTreeElement) }
      };
      if(directoryTreeElement.hasOwnProperty("children")) {
        jstreeElement.children = generateDataForJsTreeRecursively(directoryTreeElement.children);
        const isAllChildrenDisabled = jstreeElement.children.every(child => child.state.disabled);
        jstreeElement.state.disabled = isAllChildrenDisabled;
      }
      jstreeElementArray.push(jstreeElement);
    }
  );
  return jstreeElementArray;
}

function isDisabled(directoryTreeElement) {
  const isFile = () => directoryTreeElement.type === "file";
  const gpsCoordinatesExist = exifManager.getGpsCoordinates(directoryTreeElement.path) !== null;
  return isFile() && !gpsCoordinatesExist;
}<|endoftext|>