<commit_before>// Copyright 2017, University of Colorado Boulder

/**
 * The lattice is a 2D grid with a value in each cell that represents the wave amplitude at that point.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var Emitter = require( 'AXON/Emitter' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Matrix = require( 'DOT/Matrix' );
  var waveInterference = require( 'WAVE_INTERFERENCE/waveInterference' );

  // constants

  // The wave speed in the coordinate frame of the lattice, see http://www.mtnmath.com/whatth/node47.html. We tried
  // different values, but they do not have the properer emergent behavior.  WAVE_SPEED=1 propagates out as a diamond
  // rather than a circle, and WAVE_SPEED=0.1 is too slow and throws off the frequency of light.
  var WAVE_SPEED = 0.5;
  var WAVE_SPEED_SQUARED = WAVE_SPEED * WAVE_SPEED; // precompute to avoid work in the inner loop
  var NUMBER_OF_MATRICES = 3; // The algorithm we use for the discretized wave equation requires current value + 2 history points

  // This is the threshold for the wave value that determines if the light has visited.  If the value is higher,
  // it will track the wavefront of the light more accurately (and hence could be used for more accurate computation of
  // the speed of light), but will generate more artifacts in the initial wave.  If the value is lower, it will generate
  // fewer artifacts in the initial propagation, but will lead the initial wavefront by too far and make it seem like
  // light is faster than it should be measured (based on the propagation of wavefronts).
  var LIGHT_VISIT_THRESHOLD = 0.06;

  /**
   * @param {number} width - width of the lattice
   * @param {number} height - height of the lattice
   * @param {number} dampX - number of cells on the left and again on the right to use for damping
   * @param {number} dampY - number of cells on the top and again on the bottom to use for damping
   * @constructor
   */
  function Lattice( width, height, dampX, dampY ) {

    // @public (read-only) {number} - number of cells on the left and again on the right to use for damping
    this.dampX = dampX;

    // @public (read-only) {number} - number of cells on the top and again on the bottom to use for damping
    this.dampY = dampY;

    // @private {Matrix[]} - matrices for current value, previous value and value before previous
    this.matrices = [];
    for ( var i = 0; i < NUMBER_OF_MATRICES; i++ ) {
      this.matrices.push( new Matrix( width, height ) );
    }

    // @private {Matrix} - keeps track of which cells have been visited by the wave
    this.visitedMatrix = new Matrix( width, height );

    // @private {number} - indicates the current matrix. Previous matrix is one higher (with correct modulus)
    this.currentMatrixIndex = 0;

    // @private {function} - returns true if there is a potential barrier at the given coordinate
    this.potentialFunction = null;

    // @public {Emitter} - sends a notification each time the lattice updates
    this.changedEmitter = new Emitter();

    // @public (read-only) {number} - width of the lattice (includes damping regions)
    this.width = width;

    // @public (read-only) {number} - height of the lattice (includes damping regions)
    this.height = height;
  }

  waveInterference.register( 'Lattice', Lattice );

  return inherit( Object, Lattice, {

    /**
     * Read the values on the center line of the lattice (omits the out-of-bounds damping regions), for display in the
     * WaveAreaGraphNode
     * @param {number[]} array - array to fill with the values for performance/memory, will be resized if necessary
     * @public
     */
    getCenterLineValues: function( array ) {
      var samplingWidth = this.width - this.dampX * 2;

      // Resize array if necessary
      if ( array.length !== samplingWidth ) {
        array.length = 0;
      }
      var samplingVerticalLocation = Math.round( this.height / 2 );
      for ( var i = 0; i < this.width - this.dampX * 2; i++ ) {
        array[ i ] = this.getCurrentValue( i + this.dampX, samplingVerticalLocation );
      }
      return array;
    },

    /**
     * Returns the current value in the given cell
     * @param {number} i - horizontal integer coordinate
     * @param {number} j - vertical integer coordinate
     * @returns {number}
     * @public
     */
    getCurrentValue: function( i, j ) {
      return this.matrices[ this.currentMatrixIndex ].get( i, j );
    },

    /**
     * Sets the current value in the given cell
     * @param {number} i - horizontal integer coordinate
     * @param {number} j - vertical integer coordinate
     * @param {number} value
     * @public
     */
    setCurrentValue: function( i, j, value ) {
      this.matrices[ this.currentMatrixIndex ].set( i, j, value );
    },

    /**
     * Returns the previous value in the given cell
     * @param {number} i - horizontal integer coordinate
     * @param {number} j - vertical integer coordinate
     * @private
     */
    getLastValue: function( i, j ) {
      return this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ].get( i, j );
    },

    /**
     * Sets the previous value in the given cell
     * @param {number} i - horizontal integer coordinate
     * @param {number} j - vertical integer coordinate
     * @param {number} value
     * @private
     */
    setLastValue: function( i, j, value ) {
      this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ].set( i, j, value );
    },

    /**
     * Across a horizontal line, dampen the waveform based on past adjacent values.  Developed in the Java version as
     * one step in preventing artifacts near the edge of the visible part of the lattice.
     * @param {number} j - y coordinate for the lattice
     * @param {number} dj - distance above or below to look
     * @param {Matrix} matrix0 - current matrix
     * @param {Matrix} matrix2 - two time steps ago
     * @private
     */
    dampHorizontalTemporal: function( j, dj, matrix0, matrix2 ) {
      for ( var i = 0; i < this.width; i++ ) {
        matrix0.set( i, j, matrix2.get( i, j + dj ) );
      }
    },

    /**
     * Across a vertical line, dampen the waveform based on past adjacent values.  Developed in the Java version as
     * one step in preventing artifacts near the edge of the visible part of the lattice.
     * @param {number} i - x coordinate for the lattice
     * @param {number} di - distance left or right to look
     * @param {Matrix} matrix0 - current matrix
     * @param {Matrix} matrix2 - two time steps ago
     * @private
     */
    dampVerticalTemporal: function( i, di, matrix0, matrix2 ) {
      for ( var j = 0; j < this.height; j++ ) {
        matrix0.set( i, j, matrix2.get( i + di, j ) );
      }
    },

    /**
     * Exponential decay in a vertical band to prevent reflections or artifacts from the sides of the lattice.
     * @param {number} i0 - x coordinate of the damping region
     * @param {number} sign - +1 or -1 depending on which way the damping moves
     * @param {number} width - width of the damping region
     * @private
     */
    decayVertical: function( i0, sign, width ) {
      for ( var j = 0; j < this.height; j++ ) {
        for ( var step = 0; step < width; step++ ) {
          var distFromDampBoundary = width - step;
          var damp = this.getDamp( distFromDampBoundary );
          var i = i0 + step * sign;
          this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
          this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
        }
      }
    },

    /**
     * Exponential decay in a horizontal band to prevent reflections or artifacts from the sides of the lattice.
     * @param {number} j0 - y coordinate of the damping region
     * @param {number} sign - +1 or -1 depending on which way the damping moves
     * @param {number} height - height of the damping region
     * @private
     */
    decayHorizontal: function( j0, sign, height ) {
      for ( var i = 0; i < this.width; i++ ) {
        for ( var step = 0; step < height; step++ ) {
          var distFromDampBoundary = height - step;
          var damp = this.getDamp( distFromDampBoundary );
          var j = j0 + step * sign;
          this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
          this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
        }
      }
    },

    /**
     * Determines whether the incoming wave has reached the cell.
     * @param {number} i - horizontal coordinate to check
     * @param {number} j - vertical coordinate to check
     * @returns {boolean}
     */
    hasCellBeenVisited: function( i, j ) {
      return this.visitedMatrix.get( i, j ) === 1;
    },

    /**
     * Damp more aggressively further from the edge of the visible lattice
     * @param {number} depthInDampRegion - number of cells into the damping region
     * @returns {number} scale factor for dampening the wave
     * @private
     */
    getDamp: function( depthInDampRegion ) {
      return ( 1 - depthInDampRegion * 0.0001 );
    },

    /**
     * Resets all of the wave values to 0
     * @public
     */
    clear: function() {
      for ( var i = 0; i < this.matrices.length; i++ ) {
        this.matrices[ i ].timesEquals( 0 );
      }

      this.visitedMatrix.timesEquals( 0 );
    },

    /**
     * Gets the values on the right hand side of the wave (before the damping region), for determining intensity.
     * @returns {number[]}
     * @public
     */
    getOutputColumn: function() {

      // TODO(performance): garbage-free form?  Would require preallocating the entire intensitySample matrix
      var column = [];
      for ( var j = this.dampY; j < this.height - this.dampY; j++ ) {
        column.push( this.getCurrentValue( this.width - this.dampX - 1, j ) );
      }
      return column;
    },

    /**
     * @param {Function} potentialFunction (i,j)=>boolean, true if there is a barrier at that cell location
     * @public
     */
    setPotentialFunction: function( potentialFunction ) {
      this.potentialFunction = potentialFunction;
    },

    /**
     * Propagates the wave by one step.  This is a discrete algorithm and cannot use dt.
     * @public
     */
    step: function() {
      this.currentMatrixIndex = ( this.currentMatrixIndex - 1 + this.matrices.length ) % this.matrices.length;

      var matrix0 = this.matrices[ ( this.currentMatrixIndex + 0 ) % this.matrices.length ];
      var matrix1 = this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ];
      var matrix2 = this.matrices[ ( this.currentMatrixIndex + 2 ) % this.matrices.length ];
      var width = matrix0.getRowDimension();
      var height = matrix0.getColumnDimension();

      // Main loop, doesn't update cells on the edges
      for ( var i = 1; i < width - 1; i++ ) {
        for ( var j = 1; j < height - 1; j++ ) {
          if ( this.potentialFunction && this.potentialFunction( i, j ) ) {
            matrix0.set( i, j, 0 );
          }
          else {
            var neighborSum = matrix1.get( i + 1, j ) + matrix1.get( i - 1, j ) + matrix1.get( i, j + 1 ) + matrix1.get( i, j - 1 );
            var m1ij = matrix1.get( i, j );
            var value = m1ij * 2 - matrix2.get( i, j ) + WAVE_SPEED_SQUARED * ( neighborSum + m1ij * -4 );
            matrix0.set( i, j, value );

            if ( Math.abs( value ) > LIGHT_VISIT_THRESHOLD ) {
              this.visitedMatrix.set( i, j, 1 );
            }
          }
        }
      }

      // temporal dampen on the visible region
      this.dampHorizontalTemporal( 0, 1, matrix0, matrix2 );
      this.dampHorizontalTemporal( this.height - 1, -1, matrix0, matrix2 );
      this.dampVerticalTemporal( 0, +1, matrix0, matrix2 );
      this.dampVerticalTemporal( this.width - 1, -1, matrix0, matrix2 );

      // decay the wave outside of the visible part
      this.decayVertical( 0, +1, this.dampY / 2 );
      this.decayVertical( this.width - 1, -1, this.dampY / 2 );
      this.decayHorizontal( 0, +1, this.dampX / 2 );
      this.decayHorizontal( this.height - 1, -1, this.dampX / 2 );

      // TODO: clean this up, was moved to after a incoming source step
      // this.changedEmitter.emit();
    }
  } );
} );<commit_msg>Moved forcingFunction to the Lattice<commit_after>// Copyright 2017, University of Colorado Boulder

/**
 * The lattice is a 2D grid with a value in each cell that represents the wave amplitude at that point.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var Emitter = require( 'AXON/Emitter' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Matrix = require( 'DOT/Matrix' );
  var waveInterference = require( 'WAVE_INTERFERENCE/waveInterference' );

  // constants

  // The wave speed in the coordinate frame of the lattice, see http://www.mtnmath.com/whatth/node47.html. We tried
  // different values, but they do not have the properer emergent behavior.  WAVE_SPEED=1 propagates out as a diamond
  // rather than a circle, and WAVE_SPEED=0.1 is too slow and throws off the frequency of light.
  var WAVE_SPEED = 0.5;
  var WAVE_SPEED_SQUARED = WAVE_SPEED * WAVE_SPEED; // precompute to avoid work in the inner loop
  var NUMBER_OF_MATRICES = 3; // The algorithm we use for the discretized wave equation requires current value + 2 history points

  // This is the threshold for the wave value that determines if the light has visited.  If the value is higher,
  // it will track the wavefront of the light more accurately (and hence could be used for more accurate computation of
  // the speed of light), but will generate more artifacts in the initial wave.  If the value is lower, it will generate
  // fewer artifacts in the initial propagation, but will lead the initial wavefront by too far and make it seem like
  // light is faster than it should be measured (based on the propagation of wavefronts).
  var LIGHT_VISIT_THRESHOLD = 0.06;

  /**
   * @param {number} width - width of the lattice
   * @param {number} height - height of the lattice
   * @param {number} dampX - number of cells on the left and again on the right to use for damping
   * @param {number} dampY - number of cells on the top and again on the bottom to use for damping
   * @constructor
   */
  function Lattice( width, height, dampX, dampY ) {

    // @public (read-only) {number} - number of cells on the left and again on the right to use for damping
    this.dampX = dampX;

    // @public (read-only) {number} - number of cells on the top and again on the bottom to use for damping
    this.dampY = dampY;

    // @private {Matrix[]} - matrices for current value, previous value and value before previous
    this.matrices = [];
    for ( var i = 0; i < NUMBER_OF_MATRICES; i++ ) {
      this.matrices.push( new Matrix( width, height ) );
    }

    // @private {Matrix} - keeps track of which cells have been visited by the wave
    this.visitedMatrix = new Matrix( width, height );

    // @private {number} - indicates the current matrix. Previous matrix is one higher (with correct modulus)
    this.currentMatrixIndex = 0;

    // @private {function} - returns true if there is a potential barrier at the given coordinate
    this.potentialFunction = null;

    // @public {Emitter} - sends a notification each time the lattice updates.
    this.changedEmitter = new Emitter();

    // @public (read-only) {number} - width of the lattice (includes damping regions)
    this.width = width;

    // @public (read-only) {number} - height of the lattice (includes damping regions)
    this.height = height;
  }

  waveInterference.register( 'Lattice', Lattice );

  return inherit( Object, Lattice, {

    /**
     * Read the values on the center line of the lattice (omits the out-of-bounds damping regions), for display in the
     * WaveAreaGraphNode
     * @param {number[]} array - array to fill with the values for performance/memory, will be resized if necessary
     * @public
     */
    getCenterLineValues: function( array ) {
      var samplingWidth = this.width - this.dampX * 2;

      // Resize array if necessary
      if ( array.length !== samplingWidth ) {
        array.length = 0;
      }
      var samplingVerticalLocation = Math.round( this.height / 2 );
      for ( var i = 0; i < this.width - this.dampX * 2; i++ ) {
        array[ i ] = this.getCurrentValue( i + this.dampX, samplingVerticalLocation );
      }
      return array;
    },

    /**
     * Returns the current value in the given cell
     * @param {number} i - horizontal integer coordinate
     * @param {number} j - vertical integer coordinate
     * @returns {number}
     * @public
     */
    getCurrentValue: function( i, j ) {
      return this.matrices[ this.currentMatrixIndex ].get( i, j );
    },

    /**
     * Sets the current value in the given cell
     * @param {number} i - horizontal integer coordinate
     * @param {number} j - vertical integer coordinate
     * @param {number} value
     * @public
     */
    setCurrentValue: function( i, j, value ) {
      this.matrices[ this.currentMatrixIndex ].set( i, j, value );
    },

    /**
     * Returns the previous value in the given cell
     * @param {number} i - horizontal integer coordinate
     * @param {number} j - vertical integer coordinate
     * @private
     */
    getLastValue: function( i, j ) {
      return this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ].get( i, j );
    },

    /**
     * Sets the previous value in the given cell
     * @param {number} i - horizontal integer coordinate
     * @param {number} j - vertical integer coordinate
     * @param {number} value
     * @private
     */
    setLastValue: function( i, j, value ) {
      this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ].set( i, j, value );
    },

    /**
     * Across a horizontal line, dampen the waveform based on past adjacent values.  Developed in the Java version as
     * one step in preventing artifacts near the edge of the visible part of the lattice.
     * @param {number} j - y coordinate for the lattice
     * @param {number} dj - distance above or below to look
     * @param {Matrix} matrix0 - current matrix
     * @param {Matrix} matrix2 - two time steps ago
     * @private
     */
    dampHorizontalTemporal: function( j, dj, matrix0, matrix2 ) {
      for ( var i = 0; i < this.width; i++ ) {
        matrix0.set( i, j, matrix2.get( i, j + dj ) );
      }
    },

    /**
     * Across a vertical line, dampen the waveform based on past adjacent values.  Developed in the Java version as
     * one step in preventing artifacts near the edge of the visible part of the lattice.
     * @param {number} i - x coordinate for the lattice
     * @param {number} di - distance left or right to look
     * @param {Matrix} matrix0 - current matrix
     * @param {Matrix} matrix2 - two time steps ago
     * @private
     */
    dampVerticalTemporal: function( i, di, matrix0, matrix2 ) {
      for ( var j = 0; j < this.height; j++ ) {
        matrix0.set( i, j, matrix2.get( i + di, j ) );
      }
    },

    /**
     * Exponential decay in a vertical band to prevent reflections or artifacts from the sides of the lattice.
     * @param {number} i0 - x coordinate of the damping region
     * @param {number} sign - +1 or -1 depending on which way the damping moves
     * @param {number} width - width of the damping region
     * @private
     */
    decayVertical: function( i0, sign, width ) {
      for ( var j = 0; j < this.height; j++ ) {
        for ( var step = 0; step < width; step++ ) {
          var distFromDampBoundary = width - step;
          var damp = this.getDamp( distFromDampBoundary );
          var i = i0 + step * sign;
          this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
          this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
        }
      }
    },

    /**
     * Exponential decay in a horizontal band to prevent reflections or artifacts from the sides of the lattice.
     * @param {number} j0 - y coordinate of the damping region
     * @param {number} sign - +1 or -1 depending on which way the damping moves
     * @param {number} height - height of the damping region
     * @private
     */
    decayHorizontal: function( j0, sign, height ) {
      for ( var i = 0; i < this.width; i++ ) {
        for ( var step = 0; step < height; step++ ) {
          var distFromDampBoundary = height - step;
          var damp = this.getDamp( distFromDampBoundary );
          var j = j0 + step * sign;
          this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
          this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
        }
      }
    },

    /**
     * Determines whether the incoming wave has reached the cell.
     * @param {number} i - horizontal coordinate to check
     * @param {number} j - vertical coordinate to check
     * @returns {boolean}
     */
    hasCellBeenVisited: function( i, j ) {
      return this.visitedMatrix.get( i, j ) === 1;
    },

    /**
     * Damp more aggressively further from the edge of the visible lattice
     * @param {number} depthInDampRegion - number of cells into the damping region
     * @returns {number} scale factor for dampening the wave
     * @private
     */
    getDamp: function( depthInDampRegion ) {
      return ( 1 - depthInDampRegion * 0.0001 );
    },

    /**
     * Resets all of the wave values to 0
     * @public
     */
    clear: function() {
      for ( var i = 0; i < this.matrices.length; i++ ) {
        this.matrices[ i ].timesEquals( 0 );
      }

      this.visitedMatrix.timesEquals( 0 );
    },

    /**
     * Gets the values on the right hand side of the wave (before the damping region), for determining intensity.
     * @returns {number[]}
     * @public
     */
    getOutputColumn: function() {

      // TODO(performance): garbage-free form?  Would require preallocating the entire intensitySample matrix
      var column = [];
      for ( var j = this.dampY; j < this.height - this.dampY; j++ ) {
        column.push( this.getCurrentValue( this.width - this.dampX - 1, j ) );
      }
      return column;
    },

    /**
     * @param {Function} potentialFunction (i,j)=>boolean, true if there is a barrier at that cell location
     * @public
     */
    setPotentialFunction: function( potentialFunction ) {
      this.potentialFunction = potentialFunction;
    },

    /**
     * Propagates the wave by one step.  This is a discrete algorithm and cannot use dt.
     * @param {function} forcingFunction - sets values before and after the wave equation
     * @public
     */
    step: function( forcingFunction ) {

      // Apply values before lattice step so the values will be used to propagate
      forcingFunction( this );

      this.currentMatrixIndex = ( this.currentMatrixIndex - 1 + this.matrices.length ) % this.matrices.length;

      var matrix0 = this.matrices[ ( this.currentMatrixIndex + 0 ) % this.matrices.length ];
      var matrix1 = this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ];
      var matrix2 = this.matrices[ ( this.currentMatrixIndex + 2 ) % this.matrices.length ];
      var width = matrix0.getRowDimension();
      var height = matrix0.getColumnDimension();

      // Main loop, doesn't update cells on the edges
      for ( var i = 1; i < width - 1; i++ ) {
        for ( var j = 1; j < height - 1; j++ ) {

          // TODO: combine potentialFunction and forcingFunction?
          if ( this.potentialFunction && this.potentialFunction( i, j ) ) {
            matrix0.set( i, j, 0 );
          }
          else {
            var neighborSum = matrix1.get( i + 1, j ) + matrix1.get( i - 1, j ) + matrix1.get( i, j + 1 ) + matrix1.get( i, j - 1 );
            var m1ij = matrix1.get( i, j );
            var value = m1ij * 2 - matrix2.get( i, j ) + WAVE_SPEED_SQUARED * ( neighborSum + m1ij * -4 );
            matrix0.set( i, j, value );

            if ( Math.abs( value ) > LIGHT_VISIT_THRESHOLD ) {
              this.visitedMatrix.set( i, j, 1 );
            }
          }
        }
      }

      // temporal dampen on the visible region
      this.dampHorizontalTemporal( 0, 1, matrix0, matrix2 );
      this.dampHorizontalTemporal( this.height - 1, -1, matrix0, matrix2 );
      this.dampVerticalTemporal( 0, +1, matrix0, matrix2 );
      this.dampVerticalTemporal( this.width - 1, -1, matrix0, matrix2 );

      // decay the wave outside of the visible part
      this.decayVertical( 0, +1, this.dampY / 2 );
      this.decayVertical( this.width - 1, -1, this.dampY / 2 );
      this.decayHorizontal( 0, +1, this.dampX / 2 );
      this.decayHorizontal( this.height - 1, -1, this.dampX / 2 );

      // Apply values on top of the computed lattice values so there is no noise at the point sources
      forcingFunction( this );

      // Notify listeners about changes
      this.changedEmitter.emit();
    }
  } );
} );<|endoftext|>


<commit_before>define(['angular-flex', 'angular-animate', 'angular-sanitize', 'angular-loggly-logger', 'angular-joyride', 'ngMeta'],
    function(angular) { 'use strict';

        var app = angular.module('app', angular.defineModules([
            'ngAnimate', 'ngSanitize', 'ngRoute', 'ngCookies', 'chieffancypants.loadingBar', 'toastr',
            'angular-intro', 'scbdControls', 'ngLocalizer', 'angularTrix', 'cbd-forums',
            'ng-breadcrumbs', 'scbdServices', 'scbdFilters', 'smoothScroll', 'ngMessages', 'ngStorage', 'ngDialog',
            'infinite-scroll', 'logglyLogger', 'angular-joyride', 'ngMeta'
        ]));

        app.config(["LogglyLoggerProvider", 'ngMetaProvider',  function (LogglyLoggerProvider, ngMetaProvider) {

            LogglyLoggerProvider
                .includeUrl(true)
                .includeUserAgent(true)
                .includeTimestamp(true)
                .sendConsoleErrors(true)
                .endpoint('/error-logs');

            ngMetaProvider.useTitleSuffix(true);
            ngMetaProvider.setDefaultTitle(window.scbdApp.title);
            ngMetaProvider.setDefaultTitleSuffix(' | '+window.scbdApp.title);
            ngMetaProvider.setDefaultTag('description', ' | '+(window.scbdApp.description||window.scbdApp.title));
        }])

        app.factory('$exceptionHandler', ['$log', function($log) {
            return function myExceptionHandler(exception, cause) {
                if(typeof(exception) == 'string' && /^Possibly unhandled rejection: /.test(exception)){
                    try{
                        exception = exception.replace(/^Possibly unhandled rejection: /, '');
                        exception = JSON.parse(exception);
                        exception = JSON.stringify(exception.data || exception);
                    }
                    catch(e){}
                }
                $log.warn(exception);
            };
        }])

       app.run(['ngMeta', 'LogglyLogger', 'realm', '$window', function (ngMeta, logglyLogger, realm, $window) {

            var appVersion = $window.scbdAppVersion||'localhost';
            logglyLogger.fields({ realm: realm.value, appVersion: appVersion });

            ngMeta.init();

        }]);

        return app;
    });
<commit_msg>fix variable name<commit_after>define(['angular-flex', 'angular-animate', 'angular-sanitize', 'angular-loggly-logger', 'angular-joyride', 'ngMeta'],
    function(angular) { 'use strict';

        var app = angular.module('app', angular.defineModules([
            'ngAnimate', 'ngSanitize', 'ngRoute', 'ngCookies', 'chieffancypants.loadingBar', 'toastr',
            'angular-intro', 'scbdControls', 'ngLocalizer', 'angularTrix', 'cbd-forums',
            'ng-breadcrumbs', 'scbdServices', 'scbdFilters', 'smoothScroll', 'ngMessages', 'ngStorage', 'ngDialog',
            'infinite-scroll', 'logglyLogger', 'angular-joyride', 'ngMeta'
        ]));

        app.config(["LogglyLoggerProvider", 'ngMetaProvider',  function (LogglyLoggerProvider, ngMetaProvider) {

            LogglyLoggerProvider
                .includeUrl(true)
                .includeUserAgent(true)
                .includeTimestamp(true)
                .sendConsoleErrors(true)
                .endpoint('/error-logs');

            ngMetaProvider.useTitleSuffix(true);
            ngMetaProvider.setDefaultTitle(window.scbdApp.title);
            ngMetaProvider.setDefaultTitleSuffix(' | '+window.scbdApp.title);
            ngMetaProvider.setDefaultTag('description', ' | '+(window.scbdApp.description||window.scbdApp.title));
        }])

        app.factory('$exceptionHandler', ['$log', function($log) {
            return function myExceptionHandler(exception, cause) {
                if(typeof(exception) == 'string' && /^Possibly unhandled rejection: /.test(exception)){
                    try{
                        exception = exception.replace(/^Possibly unhandled rejection: /, '');
                        exception = JSON.parse(exception);
                        exception = JSON.stringify(exception.data || exception);
                    }
                    catch(e){}
                }
                $log.warn(exception);
            };
        }])

       app.run(['ngMeta', 'LogglyLogger', 'realm', '$window', function (ngMeta, logglyLogger, realm, $window) {

            var appVersion = $window.scbdApp.version||'localhost';
            logglyLogger.fields({ realm: realm.value, appVersion: appVersion });

            ngMeta.init();

        }]);

        return app;
    });
<|endoftext|>


<commit_before>/**
 * Created by meathill on 15/11/16.
 */
'use strict';
(function (ns) {
  ns.DateRanger = Backbone.View.extend({
    events: {
      'click .shortcut': 'shortcut_clickHandler',
      'click .range input': 'input_clickHandler',
      'click .range button': 'range_clickHandler'
    },
    initialize: function () {
      this.$('.date input').datetimepicker({format: moment.DATE_FORMAT});
      if (!this.$('script').html()) {
        return;
      }

      this.template = Handlebars.compile(this.$('script').html());
      var date = new Date()
        , month = date.getMonth()
        , months = _.map(_.range(month, month - 3, -1), function (value) {
          return {
            month: value <= 0 ? value + 12 : value,
            start: moment(new Date(date.getFullYear(), value - 1, 1)).format(moment.DATE_FORMAT),
            end: moment(new Date(date.getFullYear(), value, 0)).format(moment.DATE_FORMAT)
          }
        })
        , self = this;
      this.$('script').replaceWith(this.template({ months: months }));
      this.$('.this-month').data('start', moment().startOf('month').format(moment.DATE_FORMAT));
      this.$('.this-season').data('start', moment().startOf('quarter').format(moment.DATE_FORMAT));
      this.$('.shortcut').each(function () {
        var data = $(this).data();
        data.start = self.formatDate(data.start);
        data.end = self.formatDate(data.end, date.getDate());
        $(this).data(data)
          .attr('data-start', data.start)
          .attr('data-end', data.end);
      });
    },
    render: function (options) {
      // 默认显示一个月
      var range = _.defaults(options, {
          start: -31,
          end: 0
        });

      if (!isNaN(range.start)) {
        range.start = moment().add(range.start, 'days').format(range.format || moment.DATE_FORMAT);
      }
      if (!isNaN(range.end)) {
        range.end = moment().add(range.end, 'days').format(range.format || moment.DATE_FORMAT);
      }

      this.$('[name=start]').val(range.start);
      this.$('[name=end]').val(range.end);
      var shortcut = this.$('[data-start="' + range.start + '"][data-end="' + range.end + '"]').eq(0);
      this.$('.label').text(shortcut.length ? shortcut.text() : range.start + ' ~ ' + range.end);
      return range;
    },
    trigger: function (range, options) {
      options = options || {};
      options.reset = true;
      this.model.set(range, options);
    },
    formatDate: function (date, today) {
      if (isNaN(date)) {
        return date;
      }
      if (today && today === 1 && date === -1) {
        date = 0;
      }
      return moment().add(date, 'days').format(moment.DATE_FORMAT);
    },
    use: function (model) {
      this.model = model;
      var range = this.render(model.pick('start', 'end', 'format'));
      if (range.format) {
        this.$('.date input').each(function () {
          $(this).data("DateTimePicker").format(range.format);
        });
        this.$el.addClass('select-month');
      }
      this.model.set(range, {silent: true});
    },
    input_clickHandler: function (event) {
      event.stopPropagation();
    },
    range_clickHandler: function () {
      var start = this.$('[name=start]').val()
        , end = this.$('[name=end]').val();
      this.$('.shortcut').removeClass('active');
      this.$('.label').text(start + ' - ' + end);
      this.trigger({
        start: start,
        end: end
      });
    },
    shortcut_clickHandler: function (event) {
      var item = $(event.currentTarget)
        , start = item.data('start')
        , end = item.data('end');
      item.addClass('active')
        .siblings().removeClass('active');
      this.$('.label').text(item.text());
      var range = this.render({start: start, end: end});
      this.trigger(range);
      event.preventDefault();
    }
  });
}(Nervenet.createNameSpace('tp.component')));<commit_msg>  修改代码<commit_after>/**
 * Created by meathill on 15/11/16.
 */
'use strict';
(function (ns) {
  ns.DateRanger = Backbone.View.extend({
    events: {
      'click .shortcut': 'shortcut_clickHandler',
      'click .range input': 'input_clickHandler',
      'click .range button': 'range_clickHandler'
    },
    initialize: function () {
      this.$('.date input').datetimepicker({format: moment.DATE_FORMAT});
      if (!this.$('script').html()) {
        return;
      }

      this.template = Handlebars.compile(this.$('script').html());
      var date = new Date()
        , month = date.getMonth()
        , months = _.map(_.range(month, month - 3, -1), function (value) {
          return {
            month: value <= 0 ? value + 12 : value,
            start: moment(new Date(date.getFullYear(), value - 1, 1)).format(moment.DATE_FORMAT),
            end: moment(new Date(date.getFullYear(), value, 0)).format(moment.DATE_FORMAT)
          }
        })
        , self = this;
      this.$('script').replaceWith(this.template({ months: months }));
      this.$('.this-month').data('start', moment().startOf('month').format(moment.DATE_FORMAT));
      this.$('.this-season').data('start', moment().startOf('quarter').format(moment.DATE_FORMAT));
      this.$('.shortcut').each(function () {
        var data = $(this).data();
        data.start = self.formatDate(data.start);
        data.end = self.formatDate(data.end, date.getDate());
        $(this).data(data)
          .attr('data-start', data.start)
          .attr('data-end', data.end);
      });
    },
    render: function (options) {
      // 默认显示一个月
      var isMonth = options.format === 'YYYY-MM'
        , unit = isMonth ? 'months' : 'days'
        , range = _.defaults(options, {
          start: isMonth ? -1 : -31,
          end: 0,
          format: moment.DATE_FORMAT
        });
      this.$('.date input').each(function () {
        $(this).data("DateTimePicker").viewMode(unit);
      });
      this.$el.toggleClass('select-month', isMonth);

      if (!isNaN(range.start)) {
        range.start = moment().add(range.start, unit).format(range.format);
      }
      if (!isNaN(range.end)) {
        range.end = moment().add(range.end, unit).format(range.format);
      }

      this.$('[name=start]').val(range.start);
      this.$('[name=end]').val(range.end);
      var shortcut = this.$('[data-start="' + range.start + '"][data-end="' + range.end + '"]').eq(0);
      this.$('.label').text(shortcut.length ? shortcut.text() : range.start + ' ~ ' + range.end);
      return range;
    },
    trigger: function (range, options) {
      options = options || {};
      options.reset = true;
      this.model.set(range, options);
    },
    formatDate: function (date, today) {
      if (isNaN(date)) {
        return date;
      }
      if (today && today === 1 && date === -1) {
        date = 0;
      }
      return moment().add(date, 'days').format(moment.DATE_FORMAT);
    },
    use: function (model) {
      this.model = model;
      var range = this.render(model.pick('start', 'end', 'format'));
      this.model.set(range, {silent: true});
    },
    input_clickHandler: function (event) {
      event.stopPropagation();
    },
    range_clickHandler: function () {
      var start = this.$('[name=start]').val()
        , end = this.$('[name=end]').val();
      this.$('.shortcut').removeClass('active');
      this.$('.label').text(start + ' - ' + end);
      this.trigger({
        start: start,
        end: end
      });
    },
    shortcut_clickHandler: function (event) {
      var item = $(event.currentTarget)
        , start = item.data('start')
        , end = item.data('end');
      item.addClass('active')
        .siblings().removeClass('active');
      this.$('.label').text(item.text());
      var range = this.render({start: start, end: end});
      this.trigger(range);
      event.preventDefault();
    }
  });
}(Nervenet.createNameSpace('tp.component')));<|endoftext|>


<commit_before>'use strict';

var tap = require('tap').test;
var Table = require(__dirname + '/../../lib/table');

// specify dialect classes
var dialects = {
  pg : require('../../lib/dialect/postgres'),
  mysql : require('../../lib/dialect/mysql')
};

module.exports = {
  test:  function(expected) {

    // for each dialect
    Object.keys(dialects).forEach(function(dialect) {
      if(expected[dialect]) {

        var DialectClass = dialects[dialect];

        var title = DialectClass.name+': '+(expected.title || expected[dialect].text || expected[dialect]);
        tap(title, function(t) {

          // check if this query is expected to throw
          if(expected[dialect].throws) {

            t.throws(function() {
              new DialectClass().getQuery(expected.query);
            });

          } else {

            // build query for dialect
            var compiledQuery = new DialectClass().getQuery(expected.query);

            // test result is correct
            var expectedText = expected[dialect].text || expected[dialect];
            t.equal(compiledQuery.text, expectedText,'query result');

            // if params are specified then test these are correct
            var expectedParams = expected[dialect].params || expected.params;
            if(expectedParams) {
              t.equal(expectedParams.length, compiledQuery.values.length, 'params length');
              for(var i = 0; i < expectedParams.length; i++) {
                t.equal(expectedParams[i], compiledQuery.values[i], 'param '+(i+1));
              }
            }

          }
          t.end();
        });

      } // if
    }); // forEach

  },

  defineUserTable: function () {
    return Table.define({
      name: 'user',
      quote: true,
      columns: ['id','name']
    });
  },

  definePostTable: function () {
    return Table.define({
      name: 'post',
      columns: ['id', 'userId', 'content']
    });
  },

  defineCommentTable: function () {
    return Table.define({
      name: 'comment',
      columns: ['postId', 'text']
    });
  }
};

<commit_msg>let the tests say which dialect they are for<commit_after>'use strict';

var tap = require('tap').test;
var Table = require(__dirname + '/../../lib/table');

// specify dialect classes
var dialects = {
  pg : require('../../lib/dialect/postgres'),
  mysql : require('../../lib/dialect/mysql')
};

module.exports = {
  test:  function(expected) {

    // for each dialect
    Object.keys(dialects).forEach(function(dialect) {
      if(expected[dialect]) {

        var DialectClass = dialects[dialect];

        var title = dialect+': '+(expected.title || expected[dialect].text || expected[dialect]);
        tap(title, function(t) {

          // check if this query is expected to throw
          if(expected[dialect].throws) {

            t.throws(function() {
              new DialectClass().getQuery(expected.query);
            });

          } else {

            // build query for dialect
            var compiledQuery = new DialectClass().getQuery(expected.query);

            // test result is correct
            var expectedText = expected[dialect].text || expected[dialect];
            t.equal(compiledQuery.text, expectedText,'query result');

            // if params are specified then test these are correct
            var expectedParams = expected[dialect].params || expected.params;
            if(expectedParams) {
              t.equal(expectedParams.length, compiledQuery.values.length, 'params length');
              for(var i = 0; i < expectedParams.length; i++) {
                t.equal(expectedParams[i], compiledQuery.values[i], 'param '+(i+1));
              }
            }

          }
          t.end();
        });

      } // if
    }); // forEach

  },

  defineUserTable: function () {
    return Table.define({
      name: 'user',
      quote: true,
      columns: ['id','name']
    });
  },

  definePostTable: function () {
    return Table.define({
      name: 'post',
      columns: ['id', 'userId', 'content']
    });
  },

  defineCommentTable: function () {
    return Table.define({
      name: 'comment',
      columns: ['postId', 'text']
    });
  }
};

<|endoftext|>


<commit_before>/*
 creating a Express app initializing it with the HelloWorld message
 */
'use strict';

var PORT_LISTENER = process.env.NODE_PORT || 9000;
console.log('I am listening to this port: http://localhost:%s', PORT_LISTENER);

var express = require('express'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    errorhandler = require('errorhandler'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    http = require('http'),
    path = require('path'),
    RedisSMQ = require('rsmq'),
    dotenv = require('dotenv').config({silent:true}),
    [rs_protocol, rs_host, rs_port] = (process.env.REDIS_PORT || 'tcp://127.0.0.1:6379').split(/\:\/\/|\:/),
    rsmq = new RedisSMQ({host: rs_host, port: rs_port, ns: 'rsmq'});

var appConfig = require('./config/appConfig.json');
var router = require('./routes/index');
var proxy = require('express-http-proxy');
//
var app = express();

// all environments
app.set('port', PORT_LISTENER);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/bootstrap-3.3.1/docs/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser({ keepExtensions: true, uploadDir: path.join(__dirname, appConfig.directories.publicDir) }));
app.use(methodOverride());
app.use(cookieParser('my v3ry s3cr3t C00k1e k3y d0nt y0u th1nk?'));
app.use(session({ resave: true,
                  saveUninitialized: true,
                  secret: 'my l1ttl3 s3cret s3ss10n k3y isnt it?' }));
// FIXME: currently we use 2 proxy libraries express-http-proxy and express-request-proxy
// stick to oneo
var [protocol, host, port] = (process.env.API_PORT || "tcp://localhost:3001").split(/\:/);
host = host.replace(/\/\//, '');
console.log('Host', host, 'Port', port);
app.use('/api', proxy(`http://${host}:${port}`, {
    forwardPath: function(req, res) {
        return '/api' + require('url').parse(req.url).path;
    }
}));

//routes
app.use('/', router);

app.use(express.static(path.join(__dirname, appConfig.directories.publicDir)));

// attempting to create new queue
rsmq.createQueue({qname:"new-scan"},(err, resp) => {
    if(resp === 1) {
        console.log('Queue created');
    }
});

app.use('/scan/new', (req, res, next) => {
    console.log(req.body);
    rsmq.sendMessage({qname:'new-scan', message: JSON.stringify(req.body)}, (err, resp) => {
        if(err){
            res.send({status: 'error', err: err});
        } else {
            res.send({status: 'queued'});
            console.log("Message sent. ID:", resp);
        }
    });
});

// development only
if ('development' === app.get('env')) {
    app.use(errorhandler());
}

http.createServer(app).listen(app.get('port'), '0.0.0.0', function () {
    console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>Added {timestamp: new Date()} to packet sent to Redis (closed #7)<commit_after>/*
 creating a Express app initializing it with the HelloWorld message
 */
'use strict';

var PORT_LISTENER = process.env.NODE_PORT || 9000;
console.log('I am listening to this port: http://localhost:%s', PORT_LISTENER);

var express = require('express'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    errorhandler = require('errorhandler'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    http = require('http'),
    path = require('path'),
    _ = require('lodash'),
    RedisSMQ = require('rsmq'),
    dotenv = require('dotenv').config({silent:true}),
    [rs_protocol, rs_host, rs_port] = (process.env.REDIS_PORT || 'tcp://127.0.0.1:6379').split(/\:\/\/|\:/),
    rsmq = new RedisSMQ({host: rs_host, port: rs_port, ns: 'rsmq'});

var appConfig = require('./config/appConfig.json');
var router = require('./routes/index');
var proxy = require('express-http-proxy');
//
var app = express();

// all environments
app.set('port', PORT_LISTENER);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/bootstrap-3.3.1/docs/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser({ keepExtensions: true, uploadDir: path.join(__dirname, appConfig.directories.publicDir) }));
app.use(methodOverride());
app.use(cookieParser('my v3ry s3cr3t C00k1e k3y d0nt y0u th1nk?'));
app.use(session({ resave: true,
                  saveUninitialized: true,
                  secret: 'my l1ttl3 s3cret s3ss10n k3y isnt it?' }));
// FIXME: currently we use 2 proxy libraries express-http-proxy and express-request-proxy
// stick to oneo
var [protocol, host, port] = (process.env.API_PORT || "tcp://localhost:3001").split(/\:/);
host = host.replace(/\/\//, '');
console.log('Host', host, 'Port', port);
app.use('/api', proxy(`http://${host}:${port}`, {
    forwardPath: function(req, res) {
        return '/api' + require('url').parse(req.url).path;
    }
}));

//routes
app.use('/', router);

app.use(express.static(path.join(__dirname, appConfig.directories.publicDir)));

// attempting to create new queue
rsmq.createQueue({qname:"new-scan"},(err, resp) => {
    if(resp === 1) {
        console.log('Queue created');
    }
});

app.use('/scan/new', (req, res, next) => {
    const data = _.extend(req.body, {timestamp: new Date()});
    console.log(data);
    rsmq.sendMessage({qname:'new-scan', message: JSON.stringify(data)}, (err, resp) => {
        if(err){
            res.send({status: 'error', err: err});
        } else {
            res.send({status: 'queued'});
            console.log("Message sent. ID:", resp);
        }
    });
});

// development only
if ('development' === app.get('env')) {
    app.use(errorhandler());
}

http.createServer(app).listen(app.get('port'), '0.0.0.0', function () {
    console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute',
    'myApp.Home',
    'myApp.Events',
    'myApp.Grounds',
    'myApp.version',
    'myApp.teamProfile',
    'myApp.news',
    'myApp.eventsServices',
    'myApp.groundsServices',
    'myApp.FindGame'

]).
config(['$routeProvider', function($routeProvider) {

     $routeProvider
            .when('/home',{
                templateUrl:'Home/home.html',
                controller: 'HomeCtrl'
            })

            .when('/about',{
                templateUrl:'About/about.html',
                controller: ''
            })

            .when('/sports',{
                templateUrl:'Sports/sports.html',
                controller: ''
            })

            .when('/gallery',{
                templateUrl:'Gallery/gallery.html',
                controller: ''
            })

            .when('/news',{
                templateUrl:'News/news.html',
                controller: ''
            })

            .when('/grounds',{
                templateUrl:'Grounds/grounds.html',
                controller: 'GroundsCtrl'
            })

            .when('/ground/details',{
                templateUrl:'Grounds/ground-details.html',
                controller: ''
            })

            .when('/myGrounds',{
                templateUrl:'Grounds/ground-owner.html',
                controller: ''
            })

            .when('/findGame',{
                templateUrl:'FindGame/findGame.html',
                controller: 'FindGameCtrl'
            })

            .when('/teamProfile',{
                templateUrl:'TeamProfile/teamProfile.html',
                controller: 'teamProfileCtrl'
            })

            .when('/teamProfile/calandar',{
                templateUrl:'TeamProfile/calandar.html'
            })

            .when('/events',{
                templateUrl:'Events/events.html',
                controller: 'EventsCtrl'
            })

            .when('/events/:idEvent',{
                 templateUrl:'Events/eventShow.html',
                 controller: 'EventsCtrl'
             })

             .when('/owner',{
                 templateUrl:'Events/groundOwnerProfile.html',
                 controller: 'EventsCtrl'
             })

            .when('/success',{
                templateUrl:'Events/success.html',
                controller: ''
            })

            .when('/waiting',{
                templateUrl:'Events/waiting.html',
                controller: ''
            })

            //espace arbitre
            .when('/referee',{
                templateUrl:'Referee/referee.html',
                controller: 'RefereeCtrl'
            })
            //espace arbitre---Article Space
            .when('/article',{
                templateUrl:'Referee/article.html',
                controller: 'ArticleCtrl'
            })

            //espace arbitre---TimeLine
            .when('/timeline',{
                templateUrl:'Referee/timeline.html',
                controller: 'TimelineCtrl'
            })

            .when('/stats',{
                templateUrl:'Stats/stats.html',
                controller: 'statsCtrl'
            })

             .when('/communities',{
                templateUrl:'CommunitiesList/communitiesList.html',
                controller: 'communitiesListCtrl'
            })

             .when('/invitations',{
                templateUrl:'Invitations/invitations.html',
                controller: ''
            })

            .when('/teamProfile/news',{
                templateUrl:'TeamProfile/news.html',
                controller: 'newsCtrl'
            })

            .when('/login',{
                templateUrl:'User/login.html'
            })

            .when('/signup',{
                templateUrl:'User/signup.html'
            })

  $routeProvider.otherwise({redirectTo: '/home'});
}]);
<commit_msg>some code<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute',
    'myApp.Home',
    'myApp.Events',
    'myApp.Grounds',
    'myApp.version',
    'myApp.teamProfile',
    'myApp.news',
    'myApp.eventsServices',
    'myApp.groundsServices',
    'myApp.FindGame'

]).
config(['$routeProvider', function($routeProvider) {

     $routeProvider
            .when('/home',{
                templateUrl:'Home/home.html',
                controller: 'HomeCtrl'
            })

            .when('/about',{
                templateUrl:'About/about.html',
                controller: ''
            })

            .when('/sports',{
                templateUrl:'Sports/sports.html',
                controller: ''
            })

            .when('/gallery',{
                templateUrl:'Gallery/gallery.html',
                controller: ''
            })

            .when('/news',{
                templateUrl:'News/news.html',
                controller: ''
            })

            .when('/grounds',{
                templateUrl:'Grounds/grounds.html',
                controller: 'GroundsCtrl'
            })

            .when('/ground/details',{
                templateUrl:'Grounds/ground-details.html',
                controller: ''
            })

            .when('/myGrounds',{
                templateUrl:'Grounds/ground-owner.html',
                controller: ''
            })

            .when('/findGame',{
                templateUrl:'FindGame/findGame.html',
                controller: 'FindGameCtrl'
            })

            .when('/teamProfile',{
                templateUrl:'TeamProfile/teamProfile.html',
                controller: 'teamProfileCtrl'
            })

            .when('/teamProfile/calandar',{
                templateUrl:'TeamProfile/calandar.html'
            })

            .when('/events',{
                templateUrl:'Events/events.html',
                controller: 'EventsCtrl'
            })

            .when('/events/:idEvent',{
                 templateUrl:'Events/eventShow.html',
                 controller: 'EventsCtrl'
             })

             .when('/ownerProfile',{
                 templateUrl:'Events/groundOwnerProfile.html',
                 controller: 'EventsCtrl'
             })

            .when('/success',{
                templateUrl:'Events/success.html',
                controller: ''
            })

            .when('/waiting',{
                templateUrl:'Events/waiting.html',
                controller: ''
            })

            //espace arbitre
            .when('/referee',{
                templateUrl:'Referee/referee.html',
                controller: 'RefereeCtrl'
            })
            //espace arbitre---Article Space
            .when('/article',{
                templateUrl:'Referee/article.html',
                controller: 'ArticleCtrl'
            })

            //espace arbitre---TimeLine
            .when('/timeline',{
                templateUrl:'Referee/timeline.html',
                controller: 'TimelineCtrl'
            })

            .when('/stats',{
                templateUrl:'Stats/stats.html',
                controller: 'statsCtrl'
            })

             .when('/communities',{
                templateUrl:'CommunitiesList/communitiesList.html',
                controller: 'communitiesListCtrl'
            })

             .when('/invitations',{
                templateUrl:'Invitations/invitations.html',
                controller: ''
            })

            .when('/teamProfile/news',{
                templateUrl:'TeamProfile/news.html',
                controller: 'newsCtrl'
            })

            .when('/login',{
                templateUrl:'User/login.html'
            })

            .when('/signup',{
                templateUrl:'User/signup.html'
            })

  $routeProvider.otherwise({redirectTo: '/home'});
}]);
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

module.exports = { "providers" :
  [
    {
      "name" : "Amazon",
      "image" : "http://www.amazon.com/favicon.ico",
      "search" : "http://www.amazon.com/exec/obidos/external-search/?field-keywords={searchTerms}&mode=blended",
      "autocomplete" : "http://completion.amazon.com/search/complete?method=completion&q={searchTerms}&search-alias=aps&client=amazon-search-ui&mkt=1",
      "shortcut" : "a"
    },
    {
      "name" : "Bing",
      "image" : "https://www.bing.com/favicon.ico",
      "search" : "https://www.bing.com/search?q={searchTerms}",
      "autocomplete" : "http://api.bing.com/osjson.aspx?query={searchTerms}&language={language}&form=OSDJAS",
      "shortcut" : "b"
    },
    {
      "name" : "DuckDuckGo",
      "image" : "https://duckduckgo.com/favicon.ico",
      "search" : "https://duckduckgo.com/?q={searchTerms}&t=brave",
      "autocomplete" : "https://ac.duckduckgo.com/ac/?q={searchTerms}&type=list",
      "shortcut" : "d"
    },
    {
      "name" : "Google",
      "image" : "https://www.google.com/favicon.ico",
      "search" : "https://www.google.com/search?q={searchTerms}",
      "autocomplete" : "https://suggestqueries.google.com/complete/search?client=chrome&q={searchTerms}",
      "shortcut" : "g"
    },
    {
      "name" : "Twitter",
      "image" : "https://twitter.com/favicon.ico",
      "search" : "https://twitter.com/search?q={searchTerms}&source=desktop-search",
      "autocomplete" : "https://api.twitter.com/1.1/search/tweets.json?q={searchTerms}",
      "shortcut" : "t"
    },
    {
      "name" : "Wikipedia",
      "image" : "https://en.wikipedia.org/favicon.ico",
      "search" : "http://en.wikipedia.org/wiki/Special:Search?search={searchTerms}",
      "autocomplete": "http://en.wikipedia.org/w/api.php?search={searchTerms}",
      "shortcut" : "w"
    },
    {
      "name" : "Yahoo",
      "image" : "https://search.yahoo.com/favicon.ico",
      "search" : "https://search.yahoo.com/search?p={searchTerms}&fr=opensearch",
      "autocomplete": "https://search.yahoo.com/sugg/os?command={searchTerms}&output=fxjson&fr=opensearch",
      "shortcut" : "y"
    },
    {
      "name" : "Youtube",
      "image" : "https://www.youtube.com/favicon.ico",
      "search" : "https://www.youtube.com/results?search_type=search_videos&search_query={searchTerms}&search_sort=relevance&search_category=0&page=",
      "autocomplete": "http://suggestqueries.google.com/complete/search?output=chrome&client=chrome&hl=it&q={searchTerms}&ds=yt",
      "shortcut" : "yt"
    }
  ]
}

<commit_msg>Use HTTPS URLs for new search engines<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

module.exports = { "providers" :
  [
    {
      "name" : "Amazon",
      "image" : "https://www.amazon.com/favicon.ico",
      "search" : "https://www.amazon.com/exec/obidos/external-search/?field-keywords={searchTerms}&mode=blended",
      "autocomplete" : "https://completion.amazon.com/search/complete?method=completion&q={searchTerms}&search-alias=aps&client=amazon-search-ui&mkt=1",
      "shortcut" : "a"
    },
    {
      "name" : "Bing",
      "image" : "https://www.bing.com/favicon.ico",
      "search" : "https://www.bing.com/search?q={searchTerms}",
      "autocomplete" : "https://api.bing.com/osjson.aspx?query={searchTerms}&language={language}&form=OSDJAS",
      "shortcut" : "b"
    },
    {
      "name" : "DuckDuckGo",
      "image" : "https://duckduckgo.com/favicon.ico",
      "search" : "https://duckduckgo.com/?q={searchTerms}&t=brave",
      "autocomplete" : "https://ac.duckduckgo.com/ac/?q={searchTerms}&type=list",
      "shortcut" : "d"
    },
    {
      "name" : "Google",
      "image" : "https://www.google.com/favicon.ico",
      "search" : "https://www.google.com/search?q={searchTerms}",
      "autocomplete" : "https://suggestqueries.google.com/complete/search?client=chrome&q={searchTerms}",
      "shortcut" : "g"
    },
    {
      "name" : "Twitter",
      "image" : "https://twitter.com/favicon.ico",
      "search" : "https://twitter.com/search?q={searchTerms}&source=desktop-search",
      "autocomplete" : "https://api.twitter.com/1.1/search/tweets.json?q={searchTerms}",
      "shortcut" : "t"
    },
    {
      "name" : "Wikipedia",
      "image" : "https://en.wikipedia.org/favicon.ico",
      "search" : "https://en.wikipedia.org/wiki/Special:Search?search={searchTerms}",
      "autocomplete": "https://en.wikipedia.org/w/api.php?search={searchTerms}",
      "shortcut" : "w"
    },
    {
      "name" : "Yahoo",
      "image" : "https://search.yahoo.com/favicon.ico",
      "search" : "https://search.yahoo.com/search?p={searchTerms}&fr=opensearch",
      "autocomplete": "https://search.yahoo.com/sugg/os?command={searchTerms}&output=fxjson&fr=opensearch",
      "shortcut" : "y"
    },
    {
      "name" : "Youtube",
      "image" : "https://www.youtube.com/favicon.ico",
      "search" : "https://www.youtube.com/results?search_type=search_videos&search_query={searchTerms}&search_sort=relevance&search_category=0&page=",
      "autocomplete": "https://suggestqueries.google.com/complete/search?output=chrome&client=chrome&hl=it&q={searchTerms}&ds=yt",
      "shortcut" : "yt"
    }
  ]
}

<|endoftext|>


<commit_before>"use strict";

var assert = require('chai').assert;
var fs = require('fs');
var s = require('./support');
var Preferences = require('../lib/preferences');

describe('Preferences', function () {

  describe('constructions', function () {
    it('should load from file', function () {
      var prefs = Preferences.loadFromFile(s.fixtures('simple.txt'));
      assert.deepEqual(prefs.toObject(), {
        'alpha': 'Alpha',
        'alpha.some.keys': 'v1',
        'alpha.other.keys': 'v2',
        'beta': 'Beta',
        'beta.some.keys': 'v3'
      })
    });

    it('should load from string', function () {
      var prefs = Preferences.load(fs.readFileSync(s.fixtures('simple.txt')), 'utf8');
      assert.deepEqual(prefs.toObject(), {
        'alpha': 'Alpha',
        'alpha.some.keys': 'v1',
        'alpha.other.keys': 'v2',
        'beta': 'Beta',
        'beta.some.keys': 'v3'
      })
    });
  });

  describe('functions', function () {

    var prefs = Preferences.loadFromFile(s.fixtures('simple.txt'));

    it('topLevel', function () {
      assert.deepEqual(prefs.topLevel().toObject(), {
        'alpha': 'Alpha',
        'beta': 'Beta'
      })
    });

    it('#firslLevel', function () {
      assert.deepEqual(prefs.firstLevel().toObject(), {
        'alpha': {
          'some.keys': 'v1',
          'other.keys': 'v2'
        },
        'beta': {
          'some.keys': 'v3'
        }
      });
    });

    it('#subTree', function () {
      assert.deepEqual(prefs.subTree('alpha').toObject(), {
        'some.keys': 'v1',
        'other.keys': 'v2'
      });
    });

    it('#toString', function () {
      assert.deepEqual(prefs.toString(),
        'alpha = Alpha\n' +
        'alpha.some.keys = v1\n' +
        'alpha.other.keys = v2\n' +
        'beta = Beta\n' +
        'beta.some.keys = v3\n'
      );
    });

    it.only('#firslLevel', function () {
      var prefs = Preferences.loadFromFile(s.fixtures('prefs.txt'));
      console.log(prefs.firstLevel().toObject());
    });

  });

});
<commit_msg>Update<commit_after>"use strict";

var assert = require('chai').assert;
var fs = require('fs');
var s = require('./support');
var Preferences = require('../lib/preferences');

describe('Preferences', function () {

  describe('constructions', function () {
    it('should load from file', function () {
      var prefs = Preferences.loadFromFile(s.fixtures('simple.txt'));
      assert.deepEqual(prefs.toObject(), {
        'alpha': 'Alpha',
        'alpha.some.keys': 'v1',
        'alpha.other.keys': 'v2',
        'beta': 'Beta',
        'beta.some.keys': 'v3'
      })
    });

    it('should load from string', function () {
      var prefs = Preferences.load(fs.readFileSync(s.fixtures('simple.txt')), 'utf8');
      assert.deepEqual(prefs.toObject(), {
        'alpha': 'Alpha',
        'alpha.some.keys': 'v1',
        'alpha.other.keys': 'v2',
        'beta': 'Beta',
        'beta.some.keys': 'v3'
      })
    });
  });

  describe('functions', function () {

    var prefs = Preferences.loadFromFile(s.fixtures('simple.txt'));

    it('topLevel', function () {
      assert.deepEqual(prefs.topLevel().toObject(), {
        'alpha': 'Alpha',
        'beta': 'Beta'
      })
    });

    it('#firslLevel', function () {
      assert.deepEqual(prefs.firstLevel().toObject(), {
        'alpha': {
          'some.keys': 'v1',
          'other.keys': 'v2'
        },
        'beta': {
          'some.keys': 'v3'
        }
      });
    });

    it('#subTree', function () {
      assert.deepEqual(prefs.subTree('alpha').toObject(), {
        'some.keys': 'v1',
        'other.keys': 'v2'
      });
    });

    it('#toString', function () {
      assert.deepEqual(prefs.toString(),
        'alpha = Alpha\n' +
        'alpha.some.keys = v1\n' +
        'alpha.other.keys = v2\n' +
        'beta = Beta\n' +
        'beta.some.keys = v3\n'
      );
    });

    // it('#firslLevel', function () {
    //   // var prefs = Preferences.loadFromFile(s.fixtures('prefs.txt'));
    //   // console.log(prefs.firstLevel().toObject());
    // });

  });

});
<|endoftext|>


<commit_before>'use strict';

import * as _ from 'lodash'
import * as Promise from 'bluebird'
import * as React from 'react'
import * as Reflux from 'fluxxor'
import db from './helpers/db'
import documentReady from './helpers/document-ready'

import Gobbldygook from './models/gobbldygookApp'
import loadData from './helpers/loadData'
import * as demoStudent from '../mockups/demo_student.json'

// Just for use in the browser console, I swear.
window.lodash = _

// Stick React where I (and the Chrome devtools) can see it.
window.React = React

// Handy debugging function
window.log = (thing) => console.log(_.isUndefined(thing) ? arguments : thing)

// Initialize some library options.
Promise.longStackTraces()
React.initializeTouchEvents(true)

function addDemoStudent() {
	return db.store('students').put(demoStudent);
}

// function setupStudents() {
// 	return db.store('students').all()
// 		.then(function(results) {
// 			if (results.length > 0) {
// 				console.log('results!', results)
// 			} else {
// 				console.log('no results!')
// 				addDemoStudent()
// 			}

// 			var students = (results.length > 0) ? results : [demoStudent]
// 			var stores = {StudentStore: new StudentStore({students: students})}
// 			return new Fluxxor.Flux(stores, actions)
// 		})
// }

function blastoff() {
	// Wait for document.ready and the database.
	Promise.all([db, document.ready]).then(function() {
		console.log('3. 2.. 1... Blastoff!')

		// Load data into the database
		// loadData()

		return Promise.resolve(true);
		// Set up Fluxxor
		// return setupStudents()
	}).then(function() {
		// Render the app
		var studentComponent = React.renderComponent(
			Gobbldygook(),
			document.body
		)
	}).done()
}

// run it
blastoff()

export default blastoff
<commit_msg>ES6-ify and de-fluxify app.js<commit_after>'use strict';

import * as _ from 'lodash'
import * as React from 'react'
import * as Promise from 'bluebird'

import {db} from './helpers/db'
import documentReady from './helpers/document-ready'

import Gobbldygook from './models/gobbldygookApp'
import loadData from './helpers/loadData'

// Just for use in the browser console, I swear.
window.lodash = _

// Stick React where I (and the Chrome devtools)
// [ok, mostly for the devtools] can see it.
window.React = React

// Handy debugging function
window.log = (thing) => console.log(_.isUndefined(thing) ? arguments : thing)

React.initializeTouchEvents(true)
Promise.longStackTraces()

let render = () => React.renderComponent(Gobbldygook(), document.body)

let blastoff = () => {
	// Wait for document.ready and the database.
	Promise.all([db, documentReady]).then(function() {
		console.log('3. 2.. 1... Blastoff!')

		 // Load data into the database, then render the app
		loadData().then(render)
	}).done()
}

// run it
blastoff()

export default blastoff
<|endoftext|>


<commit_before>//puts the enemy on  a timer
game.GameTimerManager = Object.extend({
init: function(x, y, settings){
this.now = new Date().getTime();
this.lastCreep = new Date().getTime();
this.paused = false;
this.alwaysUpdate = true;
},
update: function(){
	//keeps track of time
this.now = new Date().getTime();

this.goldTimerCheck();
this.creepTimerCheck();

	return true;
},
goldTimerCheck: function(){
	if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)){
	game.data.gold += (game.data.exp1+1);
	console.log("Current gold:" + game.data.gold);
		}

	},
	creepTimerCheck: function(){
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
	this.lastCreep = this.now;
	var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
	me.game.world.addChild(creepe, 5);
		}
	}
});

game.HeroDeathManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
	},
	update: function(){
		if(game.data.player.dead){
	me.game.world.removeChild(game.data.player);
	//reseting the player
	me.state.current().resetPlayer(10, 0);
		}
		return true;
	}
});

game.ExperienceManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
		game.gameover = false;

	},
	update: function(){
		if(game.data.win === true && !this.gameover){
			this.gameOver(true);
		}else if(game.data.win === false && !this.gameover){
			this.gameOver(false);

		}

		return true;
	},

	gameOver: function(win){
		if(win){
			game.data.exp += 10;
		}else{
			game.data.exp += 1;
		}

			game.gameover = true;
			me.save.exp = game.data.exp;

	}
});

	game.SpendGold = Object.extend({
	init: function(x, y, settings){
	this.now = new Date().getTime();
	this.lastBuy = new Date().getTime();
	this.paused = false;
	this.alwaysUpdate = true;
},
	update: function(){
		return true;
	}
});<commit_msg>video 47 Drawing spendGold image<commit_after>//puts the enemy on  a timer
game.GameTimerManager = Object.extend({
init: function(x, y, settings){
this.now = new Date().getTime();
this.lastCreep = new Date().getTime();
this.paused = false;
this.alwaysUpdate = true;
},
update: function(){
	//keeps track of time
this.now = new Date().getTime();

this.goldTimerCheck();
this.creepTimerCheck();

	return true;
},
goldTimerCheck: function(){
	if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)){
	game.data.gold += (game.data.exp1+1);
	console.log("Current gold:" + game.data.gold);
		}

	},
	creepTimerCheck: function(){
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
	this.lastCreep = this.now;
	var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
	me.game.world.addChild(creepe, 5);
		}
	}
});

game.HeroDeathManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
	},
	update: function(){
		if(game.data.player.dead){
	me.game.world.removeChild(game.data.player);
	//reseting the player
	me.state.current().resetPlayer(10, 0);
		}
		return true;
	}
});

game.ExperienceManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
		game.gameover = false;

	},
	update: function(){
		if(game.data.win === true && !this.gameover){
			this.gameOver(true);
		}else if(game.data.win === false && !this.gameover){
			this.gameOver(false);

		}

		return true;
	},

	gameOver: function(win){
		if(win){
			game.data.exp += 10;
		}else{
			game.data.exp += 1;
		}

			game.gameover = true;
			me.save.exp = game.data.exp;

	}
});

	game.SpendGold = Object.extend({
	init: function(x, y, settings){
	this.now = new Date().getTime();
	this.lastBuy = new Date().getTime();
	this.paused = false;
	this.alwaysUpdate = true;
	this.updateWhenPaused = true;
	this.buying = false;
},
	update: function(){
		this.now=new Date().getTime();
		if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000){
			this.lastBuy = this.now;
			if(!this.buying){
				this.startBuying();
			}else{
				this.stopBuying();
			}

		}
		return true;
	},
	startBuying: function(){
		this.buying = true;
		me.state.pause(me.state.PLAY);
		game.data.pausePos = me.game.viewport.localToWorld(0, 0);
	game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
	game.data.buyscreen.updateWhenPaused = true;
	game.data.buyscreen.setOpacity(0.8);
	me.game.world.addChild(game.data.buyscreen, 34);
	game.data.player.body.setVelocity(0, 0);
	},

	stopBuying: function(){
		this.buying = false;
		me.state.resume(me.state.PLAY);
		game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
		me.game.world.removeChild(game.data.buyscreen);
	}
});<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'ui.router',
  'ngMaterial',
  'myApp.login',
  'myApp.view2',
  'myApp.version'
]).

config(function($stateProvider) {

  var loginState = {
    name: 'login',
    url: '/login',
    template: '
hello world!
'
  };

  var aboutState = {
    name: 'about',
    url: '/about',
    template: '
Its the UI-Router hello world app!
'
  };

  $stateProvider.state(loginState);
  $stateProvider.state(aboutState);

});<commit_msg>this is what i meant to do<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'ui.router',
  'ngMaterial',
  'myApp.login',
  'myApp.view2',
  'myApp.version'
]).

config(function($stateProvider) {

  var loginState = {
    name: 'login',
    url: '/login',
    template: '
hello world!
'
  };

  var aboutState = {
    name: 'about',
    url: '/about',
    template: '
Its the UI-Router hello world app!
'
  };

  $stateProvider.state(loginState);
  $stateProvider.state(aboutState);

}).

config(function($mdThemingProvider) {
  $mdThemingProvider.theme('default')
      .primaryPalette('blue')
      .warnPalette('orange')
      .accentPalette('cyan');

});

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */

CLASS({
  name: 'PopupView',
  package: 'foam.ui.md',
  extendsModel: 'foam.flow.Element',

  requires: [
    'foam.ui.md.ModalOverlayView',
    'foam.ui.md.PositionedPopupAnimation as Animation'
  ],
  exports: [ 'as popup' ],

  constants: { ELEMENT_NAME: 'popup' },

  properties: [
    {
      model_: 'StringProperty',
      name: 'className',
      defaultValue: 'closed'
    },
    {
      model_: 'StringProperty',
      name: 'cssPosition',
      defaultValue: 'fixed',
      postSet: function(old, nu) {
        if ( ! this.$ ) return;
        this.$.style.position = this.cssPosition;
      }
    },
    {
      model_: 'StringProperty',
      name: 'cssInnerPosition',
      defaultValue: 'fixed',
      postSet: function(old, nu) {
        if ( ! this.innerView ) return;
        this.innerView.style.position = this.cssInnerPosition;
      }
    },
    {
      name: 'left',
      defaultValue: '',
      postSet: function(old, nu) {
        if ( ! this.innerView || old === nu ) return;
        this.innerView.style.left = this.left ? this.left + 'px' : '';
      }
    },
    {
      name: 'top',
      defaultValue: '',
      postSet: function(old, nu) {
        if ( ! this.innerView || old === nu ) return;
        this.innerView.style.top = this.top ? this.top + 'px' : '';
      }
    },
    {
      model_: 'FloatProperty',
      name: 'alpha',
      defaultValue: 1
    },
    {
      model_: 'FloatProperty',
      name: 'zoom',
      defaultValue: 1
    },
    {
      model_: 'ViewFactoryProperty',
      name: 'overlay',
      defaultValue: 'foam.ui.md.ModalOverlayView'
    },
    {
      name: 'overlayView'
    },
    {
      model_: 'ViewFactoryProperty',
      name: 'delegate'
    },
    {
      name: 'delegateView'
    },
    {
      name: 'containerView'
    },
    {
      name: 'innerView'
    },
    {
      model_: 'FloatProperty',
      name: 'openDuration',
      defaultValue: 300
    },
    {
      model_: 'FloatProperty',
      name: 'closeDuration',
      defaultValue: 300
    },
    {
      name: 'animationEase',
      defaultValue: Movement.easeOut(0.9)
    },
    {
      name: 'animation',
      lazyFactory: function() {
        return this.Animation.create({ popup: this });
      }
    }
  ],

  methods: [
    {
      name: 'construct',
      code: function() {
        this.overlayView = this.overlay({ cssPosition: 'inerhit' });
        this.delegateView = this.delegate();
        this.addChild(this.overlayView);
        this.addDataChild(this.delegateView);
        return this.SUPER.apply(this, arguments);
      }
    },
    {
      name: 'initHTML',
      code: function() {
        this.SUPER.apply(this, arguments);
        this.containerView = this.X.$(this.id + '-container');
        this.innerView = this.X.$(this.id + '-view');

        this.$.style.position = this.cssPosition;

        Events.dynamic(function() {
          this.alpha; this.zoom;
          if ( this.containerView ) {
            var cvStyle = this.containerView.style;
            cvStyle.opacity = this.alpha;
            cvStyle.zoom = this.zoom;
          }
        }.bind(this));

        this.animation && this.animation.initHTML && this.animation.initHTML();
      }
    },
    {
      name: 'initInnerHTML',
      code: function() {
        this.SUPER.apply(this, arguments);
        this.animation && this.animation.initInnerHTML &&
            this.animation.initInnerHTML();
      }
    },
    {
      name: 'open',
      code: function() {
        this.className = '';
        if ( this.animation ) {
          this.animation.setInitialPosition &&
              this.animation.setInitialPosition(true);
          this.animation.openAnimation &&
              this.animation.openAnimation();
        }
      }
    },
    {
      name: 'close',
      code: function() {
        this.className = '';
        if ( this.animation ) {
          this.animation.setInitialPosition &&
              this.animation.setInitialPosition(false);
          this.animation.closeAnimation &&
              this.animation.closeAnimation();
        }
      }
    },
    {
      name: 'getPositionedAnimation',
      code: function(positionPropName, isOpen) {
        return Movement.animate(
            isOpen ? this.openDuration : this.closeDuration,
            function() {
              if ( isOpen ) {
                // this[positionPropName] = 0;
              } else {
                var parent = this.cssPosition === 'fixed' ?
                    this.document.body : this.$.parentNode;
                this[positionPropName] =
                    (positionPropName.indexOf('left') >= 0 ||
                    positionPropName.indexOf('right' >= 0)) ?
                    parent.clientWidth : parent.clientHeight;
              }
              if ( this.overlayView )
                this.overlayView.alpha = isOpen ? this.overlayView.openAlpha : 0;
            }.bind(this),
            this.animationEase,
            function() {
              this.className = isOpen ? 'open' : 'closed';
            }.bind(this));
      }
    }
  ],

  templates: [
    function toInnerHTML() {/*
      %%overlayView
      <popup-container id="{{this.id}}-container">
        <popup-view id="{{this.id}}-view">
          %%delegateView
        </popup-view>
      </popup-container>
    */},
    function CSS() {/*
      popup.closed { display: none; }
      popup.hidden { visibility: hidden; }
      popup {
        display: block;
        z-index: 100;
      }
      popup-container {
        position: inherit;
        top: 0px;
        left: 0px;
        right: 0px;
        bottom: 0px;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
      }
      popup-view {
        display: block;
      }
    */}
  ]
});
<commit_msg>foam.ui.md.PopupView: Move inner view initialization out of construct and into template<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */

CLASS({
  name: 'PopupView',
  package: 'foam.ui.md',
  extendsModel: 'foam.flow.Element',

  requires: [
    'foam.ui.md.ModalOverlayView',
    'foam.ui.md.PositionedPopupAnimation as Animation'
  ],
  exports: [ 'as popup' ],

  constants: { ELEMENT_NAME: 'popup' },

  properties: [
    {
      model_: 'StringProperty',
      name: 'className',
      defaultValue: 'closed'
    },
    {
      model_: 'StringProperty',
      name: 'cssPosition',
      defaultValue: 'fixed',
      postSet: function(old, nu) {
        if ( ! this.$ ) return;
        this.$.style.position = this.cssPosition;
      }
    },
    {
      model_: 'StringProperty',
      name: 'cssInnerPosition',
      defaultValue: 'fixed',
      postSet: function(old, nu) {
        if ( ! this.innerView ) return;
        this.innerView.style.position = this.cssInnerPosition;
      }
    },
    {
      name: 'left',
      defaultValue: '',
      postSet: function(old, nu) {
        if ( ! this.innerView || old === nu ) return;
        this.innerView.style.left = this.left ? this.left + 'px' : '';
      }
    },
    {
      name: 'top',
      defaultValue: '',
      postSet: function(old, nu) {
        if ( ! this.innerView || old === nu ) return;
        this.innerView.style.top = this.top ? this.top + 'px' : '';
      }
    },
    {
      model_: 'FloatProperty',
      name: 'alpha',
      defaultValue: 1
    },
    {
      model_: 'FloatProperty',
      name: 'zoom',
      defaultValue: 1
    },
    {
      model_: 'ViewFactoryProperty',
      name: 'overlay',
      defaultValue: 'foam.ui.md.ModalOverlayView'
    },
    {
      name: 'overlayView'
    },
    {
      model_: 'ViewFactoryProperty',
      name: 'delegate'
    },
    {
      name: 'delegateView'
    },
    {
      name: 'containerView'
    },
    {
      name: 'innerView'
    },
    {
      model_: 'FloatProperty',
      name: 'openDuration',
      defaultValue: 300
    },
    {
      model_: 'FloatProperty',
      name: 'closeDuration',
      defaultValue: 300
    },
    {
      name: 'animationEase',
      defaultValue: Movement.easeOut(0.9)
    },
    {
      name: 'animation',
      lazyFactory: function() {
        return this.Animation.create({ popup: this });
      }
    }
  ],

  methods: [
    {
      name: 'initHTML',
      code: function() {
        this.SUPER.apply(this, arguments);
        this.containerView = this.X.$(this.id + '-container');
        this.innerView = this.X.$(this.id + '-view');

        this.$.style.position = this.cssPosition;

        Events.dynamic(function() {
          this.alpha; this.zoom;
          if ( this.containerView ) {
            var cvStyle = this.containerView.style;
            cvStyle.opacity = this.alpha;
            cvStyle.zoom = this.zoom;
          }
        }.bind(this));

        this.animation && this.animation.initHTML && this.animation.initHTML();
      }
    },
    {
      name: 'initInnerHTML',
      code: function() {
        this.SUPER.apply(this, arguments);
        this.animation && this.animation.initInnerHTML &&
            this.animation.initInnerHTML();
      }
    },
    {
      name: 'open',
      code: function() {
        this.className = '';
        if ( this.animation ) {
          this.animation.setInitialPosition &&
              this.animation.setInitialPosition(true);
          this.animation.openAnimation &&
              this.animation.openAnimation();
        }
      }
    },
    {
      name: 'close',
      code: function() {
        this.className = '';
        if ( this.animation ) {
          this.animation.setInitialPosition &&
              this.animation.setInitialPosition(false);
          this.animation.closeAnimation &&
              this.animation.closeAnimation();
        }
      }
    },
    {
      name: 'getPositionedAnimation',
      code: function(positionPropName, isOpen) {
        return Movement.animate(
            isOpen ? this.openDuration : this.closeDuration,
            function() {
              if ( isOpen ) {
                // this[positionPropName] = 0;
              } else {
                var parent = this.cssPosition === 'fixed' ?
                    this.document.body : this.$.parentNode;
                this[positionPropName] =
                    (positionPropName.indexOf('left') >= 0 ||
                    positionPropName.indexOf('right' >= 0)) ?
                    parent.clientWidth : parent.clientHeight;
              }
              if ( this.overlayView )
                this.overlayView.alpha = isOpen ? this.overlayView.openAlpha : 0;
            }.bind(this),
            this.animationEase,
            function() {
              this.className = isOpen ? 'open' : 'closed';
            }.bind(this));
      }
    }
  ],

  templates: [
    function toInnerHTML() {/*
      <%
        this.overlayView = this.overlay({ cssPosition: 'inerhit' });
        this.delegateView = this.delegate();
        this.addChild(this.overlayView);
        this.addDataChild(this.delegateView);
      %>
      %%overlayView
      <popup-container id="{{this.id}}-container">
        <popup-view id="{{this.id}}-view">
          %%delegateView
        </popup-view>
      </popup-container>
    */},
    function CSS() {/*
      popup.closed { display: none; }
      popup.hidden { visibility: hidden; }
      popup {
        display: block;
        z-index: 100;
      }
      popup-container {
        position: inherit;
        top: 0px;
        left: 0px;
        right: 0px;
        bottom: 0px;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
      }
      popup-view {
        display: block;
      }
    */}
  ]
});
<|endoftext|>


<commit_before>var mapLink =
      'OpenStreetMap';
var baseLayer = L.tileLayer(
      'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: 'Map data © ' + mapLink,
      maxZoom: 18,
      });

//Heatmap test data
var testData = {
  max: 100,
  data: [{lat: 21.297355, lng:-157.861581, count: 3},{lat: 21.412146, lng:-157.746353, count: 2}]
};

var cfg = {
  // radius should be small ONLY if scaleRadius is true (or small radius is intended)
  // if scaleRadius is false it will be the constant radius used in pixels
  "radius": 30,
  "maxOpacity": 1,
  // scales the radius based on map zoom
  "scaleRadius": false,
  // if set to false the heatmap uses the global maximum for colorization
  // if activated: uses the data maximum within the current map boundaries
  //   (there will always be a red spot with useLocalExtremas true)
  "useLocalExtrema": true,
  // which field name in your data represents the latitude - default "lat"
  latField: 'lat',
  // which field name in your data represents the longitude - default "lng"
  lngField: 'lng',
  // which field name in your data represents the data value - default "value"
  valueField: 'count'
};

var heatmapLayer = new HeatmapOverlay(cfg);

var map = new L.Map('map', {
  center: new L.LatLng(21.4678, -157.9807),
  zoom: 11,
  layers: [baseLayer, heatmapLayer]
});

heatmapLayer.setData(testData);

//Display popup with mock data
var markers = [];

for (var i = 0; i < incidents.length; i++){
  var type = incidents[i].type;
  var lng = incidents[i].lng;
  var lat = incidents[i].lat;
  if (incidents[i].lng === null || incidents[i].lat === null){
    continue;
  }
  else{
    markers.push(L.marker([lat, lng]).addTo(map).bindPopup(type));
  }
}

var mark = L.marker([21.4678, -157.9807], {riseOnHover: true}).addTo(map)
     .bindPopup('Some crazy shit happened here, avoid this area at all costs.');

var markerLayer = L.layerGroup(markers);

//Filter between heatmap and popup
var overlaysMaps = {
  "Heatmap" : heatmapLayer,
  "Markers" : markerLayer
};

L.control.layers(overlaysMaps).addTo(map);

// Info box
var MyControl = L.Control.extend({
  options: {
      position: 'bottomleft'
  },

  onAdd: function (map) {
    // create the control container with a particular class name
    var container = L.DomUtil.create('div', 'my-custom-control');

    // ... initialize other DOM elements, add listeners, etc.
    container.innerHTML = "
HI Traffic
" +
    "

Bringing you the latest reported accidents and highest accident prone areas.
" +
    "
Click on the markers to view the accidents type.
" +
    "
The heatmap shows areas with the most accidents.
" +
    "
Hover over the icon on the top right corner to toggle between Markers and Heatmap.

";

    return container;
  }
});

map.addControl(new MyControl());<commit_msg>Finally got the markers to hover types of accidents!<commit_after>var mapLink =
      'OpenStreetMap';
var baseLayer = L.tileLayer(
      'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: 'Map data © ' + mapLink,
      maxZoom: 18,
      });

//Heatmap test data
var testData = {
  max: 100,
  data: [{lat: 21.297355, lng:-157.861581, count: 3},{lat: 21.412146, lng:-157.746353, count: 2}]
};

var cfg = {
  // radius should be small ONLY if scaleRadius is true (or small radius is intended)
  // if scaleRadius is false it will be the constant radius used in pixels
  "radius": 30,
  "maxOpacity": 1,
  // scales the radius based on map zoom
  "scaleRadius": false,
  // if set to false the heatmap uses the global maximum for colorization
  // if activated: uses the data maximum within the current map boundaries
  //   (there will always be a red spot with useLocalExtremas true)
  "useLocalExtrema": true,
  // which field name in your data represents the latitude - default "lat"
  latField: 'lat',
  // which field name in your data represents the longitude - default "lng"
  lngField: 'lng',
  // which field name in your data represents the data value - default "value"
  valueField: 'count'
};

var heatmapLayer = new HeatmapOverlay(cfg);

var map = new L.Map('map', {
  center: new L.LatLng(21.4678, -157.9807),
  zoom: 11,
  layers: [baseLayer, heatmapLayer]
});

heatmapLayer.setData(testData);

//Display popup with mock data
var markers = [];

for (var i = 0; i < incidents.length; i++){
  var type = incidents[i].type;
  var lng = incidents[i].lng;
  var lat = incidents[i].lat;
  if (incidents[i].lng === null || incidents[i].lat === null){
    continue;
  }
  else{
    markers.push(L.marker([lat, lng]).addTo(map).bindPopup(type));
  }
}

// Hovering markers for opening and closing popups
markers.forEach(function (e) {
  e.on('mouseover', function() {
    this.openPopup();
  });
});

markers.forEach(function (e) {
  e.on('mouseout', function() {
    this.closePopup();
  });
});

var markerLayer = L.layerGroup(markers);

//Filter between heatmap and markers
var overlaysMaps = {
  "Heatmap" : heatmapLayer,
  "Markers" : markerLayer
};

L.control.layers(overlaysMaps).addTo(map);

// Info box
var MyControl = L.Control.extend({
  options: {
      position: 'bottomleft'
  },

  onAdd: function (map) {
    // create the control container with a particular class name
    var container = L.DomUtil.create('div', 'my-custom-control');

    // ... initialize other DOM elements, add listeners, etc.
    container.innerHTML = "
HI Traffic
" +
    "

Bringing you the latest reported accidents and highest accident prone areas.
" +
    "
Hover over the markers to view the accidents type.
" +
    "
The heatmap shows areas with the most accidents.
" +
    "
Hover over the icon on the top right corner to toggle between Markers and Heatmap.

";

    return container;
  }
});

map.addControl(new MyControl());<|endoftext|>