<commit_before>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js

var socket = io.connect("172.18.1.251:3000");

angular.module('starter', ['ionic', 'starter.controllers', 'ngCordova', 'btford.socket-io'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('app', {
      url: "/app",
      abstract: true,
      templateUrl: "templates/side-menu.html"
    })

    .state('app.main', {
      url: "/main",
      views: {
        'menuContent' :{
          templateUrl: "templates/main.html"
        }
      }
    })

    .state('app.play', {
      url: "/play",
      views: {
        'menuContent' :{
          templateUrl: "templates/play.html"
        }
      }
    })

    .state('app.enter-name', {
      url: "/enter-name",
      views: {
        'menuContent' :{
          templateUrl: "templates/enter-name.html"
        }
      }
    })

    .state('app.single', {
      url: "/single",
      views: {
        'menuContent' :{
          templateUrl: "templates/single.html",
          controller: "SinglePlayerCtrl"
        }
      }
    })

    .state('app.multiplayer', {
      url: "/multiplayer",
      views: {
        'menuContent' :{
          templateUrl: "templates/multiplayer.html",
          controller: "MultiCtrl"
        }
      }
    })

    .state('app.geo', {
      url: "/geo",
      views: {
        "menuContent": {
          templateUrl: "templates/geo.html",
          controller: "GeoCtrl"
        }
      }
    })
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/play');
})
.factory('mySocket', function (socketFactory) {
    var myIoSocket = io.connect('http://172.18.1.251:3000');

    var mySocket = socketFactory({
      ioSocket: myIoSocket
    });

    return mySocket;
}).factory('twerkometer', ['$cordovaDeviceMotion', function twerkometer($cordovaDeviceMotion) {

  function Vector(x, y, z) {

    this.x = x;
    this.y = y;
    this.z = z;

    this.magnitude = function() {
      return Math.sqrt(x*x + y*y + z*z);
    }

    this.multiply = function(factor) {
      return new Vector(x * factor, y * factor, z * factor);
    }

    this.add = function(vector) {
      return new Vector(x + vector.x, y + vector.y, z + vector.z);
    }

    this.subtract = function(vector) {
      return new Vector(x - vector.x, y - vector.y, z - vector.z);
    }

    this.dot = function(vector) {
      return x * vector.x + y * vector.y + z * vector.z;
    }

    this.normalise = function() {
      var n = 1/this.magnitude();
      return new Vector(x*n, y*n, z*n);
    }

    this.jiggle = function(amount) {
      function j(num, amount) { return num + (Math.random() - 0.5) * amount; }
      return new Vector(j(x, amount), j(y, amount), j(z, amount));
    }

  }

  function DataPoint(time, vector) {
    this.time = time;
    this.vector = vector;
  }

  function TwerkDetector(threshold, frames, iterations, jiggle) {

    var dataPoints = [];
    var filteredPoints = [];
    var twerkLine = new Vector(1, 0, 0);

    var totalTwerks = 0;
    var startTime = 0;
    var endTime = 0;

    this.add = function(dataPoint) {
      dataPoints.push(dataPoint);

      while(dataPoints.length > frames) {
        dataPoints.shift();
      }

      this.process();

      if(this.twerkDetected()) {
        totalTwerks++;
      }

      if(startTime == 0) {
        startTime = Date.now();
      }
      endTime = Date.now();
    }

    this.process = function() {
      solveTwerkLine();
      filterPoints();
    }

    this.reset = function() {
      dataPoints = [];
      filteredPoints = [];
      twerkLine = new Vector(1, 0, 0);
      totalTwerks = 0;
      startTime = 0;
      endTime = 0;
    }

    this.stats = function() {
      var totalSeconds = (endTime - startTime) / 1000;
      return {
        totalSeconds: totalSeconds,
        totalTwerks: totalTwerks,
        twerksPerMinute: 60 * totalTwerks / totalSeconds
      }
    }

    this.getRawPoints = function() {
      return dataPoints;
    }

    this.getFilteredPoints = function() {
      return filteredPoints;
    }

    this.twerkDetected = function() {
      if(filteredPoints.length < 2) {
        return false;
      }
      var len = filteredPoints.length;
      //console.log(filteredPoints[len - 1].vector.x);
      return filteredPoints[len - 1].vector.x != filteredPoints[len - 2].vector.x;
    }

    var solveTwerkLine = function() {
      for(var i = 0; i < iterations; i++) {
        stepTwerkLine();
      }
    }

    var stepTwerkLine = function() {
      var alteredTwerkLine = twerkLine.jiggle(jiggle).normalise();
      var error = twerkLineError(twerkLine);
      var alteredError = twerkLineError(alteredTwerkLine);
      if(alteredError < error) {
        twerkLine = alteredTwerkLine;
      }
    }

    var filterPoints = function() {
      filteredPoints = dataPoints.map(function(dataPoint) {
        var x = twerkLine.dot(dataPoint.vector);
        return new DataPoint(dataPoint.time, new Vector(x, 0, 0));
      });
      var total = 0;
      for(var i = 0; i < filteredPoints.length; i++) {
        total += filteredPoints[i].vector.x;
      }
      var average = total / filteredPoints.length;
      for(var i = 0; i < filteredPoints.length; i++) {
        filteredPoints[i].vector.x -= average;
      }
      var clampedValue = -1;
      for(var i = 0; i < filteredPoints.length; i++) {
        x = filteredPoints[i].vector.x;
        if(x > threshold && clampedValue < 0) {
          filteredPoints[i].vector.x = 1;
          clampedValue = 1;
        } else if(x < -threshold && clampedValue > 0) {
          filteredPoints[i].vector.x = -1;
          clampedValue = -1;
        } else {
          filteredPoints[i].vector.x = clampedValue;
        }
      }
    }

    var twerkLineError = function (line) {
      var error = 0;
      dataPoints.forEach(function(dataPoint) {
        error += linePointDistance(line, dataPoint.vector);
      });
      return error
    }

    var linePointDistance = function(line, point) {
      return line.multiply(point.dot(line)).subtract(point).magnitude();
    }

  }

  function FakeStats() {

    var totalTwerks = 0;
    var startTime = 0;
    var endTime = 0;

    this.add = function() {
      totalTwerks++;
      if(startTime == 0) {
        startTime = Date.now();
      }
      endTime = Date.now();
    }

    this.stats = function() {
      var totalSeconds = (endTime - startTime) / 1000;
      return {
        totalSeconds: totalSeconds,
        totalTwerks: totalTwerks,
        twerksPerMinute: 60 * totalTwerks / totalSeconds
      }
    }
  }

  var twerkDetector = new TwerkDetector(3, 20, 30, 0.3);
  var fakeStats = new FakeStats();

  var resultProxy = {
    callback: function() {
      //To be reassigned in handler. Yuck :P
    },
    reset: function() {
      twerkDetector.reset();
    },
    stats: function() {
      twerkDetector.stats();
    }
  };

  setInterval(function() {

    var time = Date.now() / 1000;
    var stats = {};

    if(navigator.accelerometer) {
      $cordovaDeviceMotion.getCurrentAcceleration().then(function(acc) {
        var dataPoint = new DataPoint(time, new Vector(acc.x, acc.y, acc.z));
        twerkDetector.add(dataPoint);
        if(twerkDetector.twerkDetected()) {
          resultProxy.callback(twerkDetector.stats());
        }
      }, function(err) {
        // An error occured. Show a message to the user
      });
    } else {
      if(Math.random() < 0.1) {
        fakeStats.add();
        resultProxy.callback(fakeStats.stats());
      }
    }

  }, 100);

  return resultProxy;
}]);
<commit_msg>Rounds TPM to whole numbers<commit_after>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js

var socket = io.connect("172.18.1.251:3000");

angular.module('starter', ['ionic', 'starter.controllers', 'ngCordova', 'btford.socket-io'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('app', {
      url: "/app",
      abstract: true,
      templateUrl: "templates/side-menu.html"
    })

    .state('app.main', {
      url: "/main",
      views: {
        'menuContent' :{
          templateUrl: "templates/main.html"
        }
      }
    })

    .state('app.play', {
      url: "/play",
      views: {
        'menuContent' :{
          templateUrl: "templates/play.html"
        }
      }
    })

    .state('app.enter-name', {
      url: "/enter-name",
      views: {
        'menuContent' :{
          templateUrl: "templates/enter-name.html"
        }
      }
    })

    .state('app.single', {
      url: "/single",
      views: {
        'menuContent' :{
          templateUrl: "templates/single.html",
          controller: "SinglePlayerCtrl"
        }
      }
    })

    .state('app.multiplayer', {
      url: "/multiplayer",
      views: {
        'menuContent' :{
          templateUrl: "templates/multiplayer.html",
          controller: "MultiCtrl"
        }
      }
    })

    .state('app.geo', {
      url: "/geo",
      views: {
        "menuContent": {
          templateUrl: "templates/geo.html",
          controller: "GeoCtrl"
        }
      }
    })
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/play');
})
.factory('mySocket', function (socketFactory) {
    var myIoSocket = io.connect('http://172.18.1.251:3000');

    var mySocket = socketFactory({
      ioSocket: myIoSocket
    });

    return mySocket;
}).factory('twerkometer', ['$cordovaDeviceMotion', function twerkometer($cordovaDeviceMotion) {

  function Vector(x, y, z) {

    this.x = x;
    this.y = y;
    this.z = z;

    this.magnitude = function() {
      return Math.sqrt(x*x + y*y + z*z);
    }

    this.multiply = function(factor) {
      return new Vector(x * factor, y * factor, z * factor);
    }

    this.add = function(vector) {
      return new Vector(x + vector.x, y + vector.y, z + vector.z);
    }

    this.subtract = function(vector) {
      return new Vector(x - vector.x, y - vector.y, z - vector.z);
    }

    this.dot = function(vector) {
      return x * vector.x + y * vector.y + z * vector.z;
    }

    this.normalise = function() {
      var n = 1/this.magnitude();
      return new Vector(x*n, y*n, z*n);
    }

    this.jiggle = function(amount) {
      function j(num, amount) { return num + (Math.random() - 0.5) * amount; }
      return new Vector(j(x, amount), j(y, amount), j(z, amount));
    }

  }

  function DataPoint(time, vector) {
    this.time = time;
    this.vector = vector;
  }

  function TwerkDetector(threshold, frames, iterations, jiggle) {

    var dataPoints = [];
    var filteredPoints = [];
    var twerkLine = new Vector(1, 0, 0);

    var totalTwerks = 0;
    var startTime = 0;
    var endTime = 0;

    this.add = function(dataPoint) {
      dataPoints.push(dataPoint);

      while(dataPoints.length > frames) {
        dataPoints.shift();
      }

      this.process();

      if(this.twerkDetected()) {
        totalTwerks++;
      }

      if(startTime == 0) {
        startTime = Date.now();
      }
      endTime = Date.now();
    }

    this.process = function() {
      solveTwerkLine();
      filterPoints();
    }

    this.reset = function() {
      dataPoints = [];
      filteredPoints = [];
      twerkLine = new Vector(1, 0, 0);
      totalTwerks = 0;
      startTime = 0;
      endTime = 0;
    }

    this.stats = function() {
      var totalSeconds = (endTime - startTime) / 1000;
      return {
        totalSeconds: totalSeconds,
        totalTwerks: totalTwerks,
        twerksPerMinute: Math.round(60 * totalTwerks / totalSeconds)
      }
    }

    this.getRawPoints = function() {
      return dataPoints;
    }

    this.getFilteredPoints = function() {
      return filteredPoints;
    }

    this.twerkDetected = function() {
      if(filteredPoints.length < 2) {
        return false;
      }
      var len = filteredPoints.length;
      //console.log(filteredPoints[len - 1].vector.x);
      return filteredPoints[len - 1].vector.x != filteredPoints[len - 2].vector.x;
    }

    var solveTwerkLine = function() {
      for(var i = 0; i < iterations; i++) {
        stepTwerkLine();
      }
    }

    var stepTwerkLine = function() {
      var alteredTwerkLine = twerkLine.jiggle(jiggle).normalise();
      var error = twerkLineError(twerkLine);
      var alteredError = twerkLineError(alteredTwerkLine);
      if(alteredError < error) {
        twerkLine = alteredTwerkLine;
      }
    }

    var filterPoints = function() {
      filteredPoints = dataPoints.map(function(dataPoint) {
        var x = twerkLine.dot(dataPoint.vector);
        return new DataPoint(dataPoint.time, new Vector(x, 0, 0));
      });
      var total = 0;
      for(var i = 0; i < filteredPoints.length; i++) {
        total += filteredPoints[i].vector.x;
      }
      var average = total / filteredPoints.length;
      for(var i = 0; i < filteredPoints.length; i++) {
        filteredPoints[i].vector.x -= average;
      }
      var clampedValue = -1;
      for(var i = 0; i < filteredPoints.length; i++) {
        x = filteredPoints[i].vector.x;
        if(x > threshold && clampedValue < 0) {
          filteredPoints[i].vector.x = 1;
          clampedValue = 1;
        } else if(x < -threshold && clampedValue > 0) {
          filteredPoints[i].vector.x = -1;
          clampedValue = -1;
        } else {
          filteredPoints[i].vector.x = clampedValue;
        }
      }
    }

    var twerkLineError = function (line) {
      var error = 0;
      dataPoints.forEach(function(dataPoint) {
        error += linePointDistance(line, dataPoint.vector);
      });
      return error
    }

    var linePointDistance = function(line, point) {
      return line.multiply(point.dot(line)).subtract(point).magnitude();
    }

  }

  function FakeStats() {

    var totalTwerks = 0;
    var startTime = 0;
    var endTime = 0;

    this.add = function() {
      totalTwerks++;
      if(startTime == 0) {
        startTime = Date.now();
      }
      endTime = Date.now();
    }

    this.stats = function() {
      var totalSeconds = (endTime - startTime) / 1000;
      return {
        totalSeconds: totalSeconds,
        totalTwerks: totalTwerks,
        twerksPerMinute: Math.round(60 * totalTwerks / totalSeconds)
      }
    }
  }

  var twerkDetector = new TwerkDetector(3, 20, 30, 0.3);
  var fakeStats = new FakeStats();

  var resultProxy = {
    callback: function() {
      //To be reassigned in handler. Yuck :P
    },
    reset: function() {
      twerkDetector.reset();
    },
    stats: function() {
      twerkDetector.stats();
    }
  };

  setInterval(function() {

    var time = Date.now() / 1000;
    var stats = {};

    if(navigator.accelerometer) {
      $cordovaDeviceMotion.getCurrentAcceleration().then(function(acc) {
        var dataPoint = new DataPoint(time, new Vector(acc.x, acc.y, acc.z));
        twerkDetector.add(dataPoint);
        if(twerkDetector.twerkDetected()) {
          resultProxy.callback(twerkDetector.stats());
        }
      }, function(err) {
        // An error occured. Show a message to the user
      });
    } else {
      if(Math.random() < 0.1) {
        fakeStats.add();
        resultProxy.callback(fakeStats.stats());
      }
    }

  }, 100);

  return resultProxy;
}]);
<|endoftext|>


<commit_before>var THREE = require('three');

var Loader = THREE.Loader;
var LoaderUtils = THREE.LoaderUtils;
var AnimationClip = THREE.AnimationClip;
var Vector3 = THREE.Vector3;
var Vector4 = THREE.Vector4;
var Color = THREE.Color;
var Vector2 = THREE.Vector2;
var Face3 = THREE.Face3;
var Geometry = THREE.Geometry;
var FileLoader = THREE.FileLoader;
var DefaultLoadingManager = THREE.DefaultLoadingManager;

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

function JSONLoader( manager ) {

	if ( typeof manager === 'boolean' ) {

		console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
		manager = undefined;

	}

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

	this.withCredentials = false;

}

Object.assign( JSONLoader.prototype, {

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var texturePath = this.texturePath && ( typeof this.texturePath === 'string' ) ? this.texturePath : LoaderUtils.extractUrlBase( url );

		var loader = new FileLoader( this.manager );
		loader.setWithCredentials( this.withCredentials );
		loader.load( url, function ( text ) {

			var json = JSON.parse( text );
			var metadata = json.metadata;

			if ( metadata !== undefined ) {

				var type = metadata.type;

				if ( type !== undefined ) {

					if ( type.toLowerCase() === 'object' ) {

						console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
						return;

					}

				}

			}

			var object = scope.parse( json, texturePath );
			onLoad( object.geometry, object.materials );

		}, onProgress, onError );

	},

	setTexturePath: function ( value ) {

		this.texturePath = value;

	},

	parse: ( function () {

		function parseModel( json, geometry ) {

			function isBitSet( value, position ) {

				return value & ( 1 << position );

			}

			var i, j, fi,

				offset, zLength,

				colorIndex, normalIndex, uvIndex, materialIndex,

				type,
				isQuad,
				hasMaterial,
				hasFaceVertexUv,
				hasFaceNormal, hasFaceVertexNormal,
				hasFaceColor, hasFaceVertexColor,

				vertex, face, faceA, faceB, hex, normal,

				uvLayer, uv, u, v,

				faces = json.faces,
				vertices = json.vertices,
				normals = json.normals,
				colors = json.colors,

				scale = json.scale,

				nUvLayers = 0;

			if ( json.uvs !== undefined ) {

				// disregard empty arrays

				for ( i = 0; i < json.uvs.length; i ++ ) {

					if ( json.uvs[ i ].length ) nUvLayers ++;

				}

				for ( i = 0; i < nUvLayers; i ++ ) {

					geometry.faceVertexUvs[ i ] = [];

				}

			}

			offset = 0;
			zLength = vertices.length;

			while ( offset < zLength ) {

				vertex = new Vector3();

				vertex.x = vertices[ offset ++ ] * scale;
				vertex.y = vertices[ offset ++ ] * scale;
				vertex.z = vertices[ offset ++ ] * scale;

				geometry.vertices.push( vertex );

			}

			offset = 0;
			zLength = faces.length;

			while ( offset < zLength ) {

				type = faces[ offset ++ ];

				isQuad = isBitSet( type, 0 );
				hasMaterial = isBitSet( type, 1 );
				hasFaceVertexUv = isBitSet( type, 3 );
				hasFaceNormal = isBitSet( type, 4 );
				hasFaceVertexNormal = isBitSet( type, 5 );
				hasFaceColor = isBitSet( type, 6 );
				hasFaceVertexColor = isBitSet( type, 7 );

				// console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);

				if ( isQuad ) {

					faceA = new Face3();
					faceA.a = faces[ offset ];
					faceA.b = faces[ offset + 1 ];
					faceA.c = faces[ offset + 3 ];

					faceB = new Face3();
					faceB.a = faces[ offset + 1 ];
					faceB.b = faces[ offset + 2 ];
					faceB.c = faces[ offset + 3 ];

					offset += 4;

					if ( hasMaterial ) {

						materialIndex = faces[ offset ++ ];
						faceA.materialIndex = materialIndex;
						faceB.materialIndex = materialIndex;

					}

					// to get face <=> uv index correspondence

					fi = geometry.faces.length;

					if ( hasFaceVertexUv ) {

						for ( i = 0; i < nUvLayers; i ++ ) {

							uvLayer = json.uvs[ i ];

							geometry.faceVertexUvs[ i ][ fi ] = [];
							geometry.faceVertexUvs[ i ][ fi + 1 ] = [];

							for ( j = 0; j < 4; j ++ ) {

								uvIndex = faces[ offset ++ ];

								u = uvLayer[ uvIndex * 2 ];
								v = uvLayer[ uvIndex * 2 + 1 ];

								uv = new Vector2( u, v );

								if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
								if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );

							}

						}

					}

					if ( hasFaceNormal ) {

						normalIndex = faces[ offset ++ ] * 3;

						faceA.normal.set(
							normals[ normalIndex ++ ],
							normals[ normalIndex ++ ],
							normals[ normalIndex ]
						);

						faceB.normal.copy( faceA.normal );

					}

					if ( hasFaceVertexNormal ) {

						for ( i = 0; i < 4; i ++ ) {

							normalIndex = faces[ offset ++ ] * 3;

							normal = new Vector3(
								normals[ normalIndex ++ ],
								normals[ normalIndex ++ ],
								normals[ normalIndex ]
							);

							if ( i !== 2 ) faceA.vertexNormals.push( normal );
							if ( i !== 0 ) faceB.vertexNormals.push( normal );

						}

					}

					if ( hasFaceColor ) {

						colorIndex = faces[ offset ++ ];
						hex = colors[ colorIndex ];

						faceA.color.setHex( hex );
						faceB.color.setHex( hex );

					}

					if ( hasFaceVertexColor ) {

						for ( i = 0; i < 4; i ++ ) {

							colorIndex = faces[ offset ++ ];
							hex = colors[ colorIndex ];

							if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
							if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );

						}

					}

					geometry.faces.push( faceA );
					geometry.faces.push( faceB );

				} else {

					face = new Face3();
					face.a = faces[ offset ++ ];
					face.b = faces[ offset ++ ];
					face.c = faces[ offset ++ ];

					if ( hasMaterial ) {

						materialIndex = faces[ offset ++ ];
						face.materialIndex = materialIndex;

					}

					// to get face <=> uv index correspondence

					fi = geometry.faces.length;

					if ( hasFaceVertexUv ) {

						for ( i = 0; i < nUvLayers; i ++ ) {

							uvLayer = json.uvs[ i ];

							geometry.faceVertexUvs[ i ][ fi ] = [];

							for ( j = 0; j < 3; j ++ ) {

								uvIndex = faces[ offset ++ ];

								u = uvLayer[ uvIndex * 2 ];
								v = uvLayer[ uvIndex * 2 + 1 ];

								uv = new Vector2( u, v );

								geometry.faceVertexUvs[ i ][ fi ].push( uv );

							}

						}

					}

					if ( hasFaceNormal ) {

						normalIndex = faces[ offset ++ ] * 3;

						face.normal.set(
							normals[ normalIndex ++ ],
							normals[ normalIndex ++ ],
							normals[ normalIndex ]
						);

					}

					if ( hasFaceVertexNormal ) {

						for ( i = 0; i < 3; i ++ ) {

							normalIndex = faces[ offset ++ ] * 3;

							normal = new Vector3(
								normals[ normalIndex ++ ],
								normals[ normalIndex ++ ],
								normals[ normalIndex ]
							);

							face.vertexNormals.push( normal );

						}

					}

					if ( hasFaceColor ) {

						colorIndex = faces[ offset ++ ];
						face.color.setHex( colors[ colorIndex ] );

					}

					if ( hasFaceVertexColor ) {

						for ( i = 0; i < 3; i ++ ) {

							colorIndex = faces[ offset ++ ];
							face.vertexColors.push( new Color( colors[ colorIndex ] ) );

						}

					}

					geometry.faces.push( face );

				}

			}

		}

		function parseSkin( json, geometry ) {

			var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;

			if ( json.skinWeights ) {

				for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {

					var x = json.skinWeights[ i ];
					var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
					var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
					var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;

					geometry.skinWeights.push( new Vector4( x, y, z, w ) );

				}

			}

			if ( json.skinIndices ) {

				for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {

					var a = json.skinIndices[ i ];
					var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
					var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
					var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;

					geometry.skinIndices.push( new Vector4( a, b, c, d ) );

				}

			}

			geometry.bones = json.bones;

			if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {

				console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
					geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );

			}

		}

		function parseMorphing( json, geometry ) {

			var scale = json.scale;

			if ( json.morphTargets !== undefined ) {

				for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {

					geometry.morphTargets[ i ] = {};
					geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
					geometry.morphTargets[ i ].vertices = [];

					var dstVertices = geometry.morphTargets[ i ].vertices;
					var srcVertices = json.morphTargets[ i ].vertices;

					for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {

						var vertex = new Vector3();
						vertex.x = srcVertices[ v ] * scale;
						vertex.y = srcVertices[ v + 1 ] * scale;
						vertex.z = srcVertices[ v + 2 ] * scale;

						dstVertices.push( vertex );

					}

				}

			}

			if ( json.morphColors !== undefined ) {

				var i, l, c, cl, dstColors, srcColors, color;

				for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {

					geometry.morphColors[ i ] = {};
					geometry.morphColors[ i ].name = json.morphColors[ i ].name;
					geometry.morphColors[ i ].colors = [];

					dstColors = geometry.morphColors[ i ].colors;
					srcColors = json.morphColors[ i ].colors;

					for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {

						color = new THREE.Color( 0xffaa00 );
						color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
						dstColors.push( color );

					}

				}

			}

		}

		function parseAnimations( json, geometry ) {

			var outputAnimations = [];

			// parse old style Bone/Hierarchy animations
			var animations = [];

			if ( json.animation !== undefined ) {

				animations.push( json.animation );

			}

			if ( json.animations !== undefined ) {

				if ( json.animations.length ) {

					animations = animations.concat( json.animations );

				} else {

					animations.push( json.animations );

				}

			}

			for ( var i = 0; i < animations.length; i ++ ) {

				var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
				if ( clip ) outputAnimations.push( clip );

			}

			// parse implicit morph animations
			if ( geometry.morphTargets ) {

				// TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
				var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
				outputAnimations = outputAnimations.concat( morphAnimationClips );

			}

			if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;

		}

		return function parse( json, texturePath ) {

			if ( json.data !== undefined ) {

				// Geometry 4.0 spec
				json = json.data;

			}

			if ( json.scale !== undefined ) {

				json.scale = 1.0 / json.scale;

			} else {

				json.scale = 1.0;

			}

			var geometry = new Geometry();

			parseModel( json, geometry );
			parseSkin( json, geometry );
			parseMorphing( json, geometry );
			parseAnimations( json, geometry );

			geometry.computeFaceNormals();
			geometry.computeBoundingSphere();

			if ( json.materials === undefined || json.materials.length === 0 ) {

				return { geometry: geometry };

			} else {

				var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );

				return { geometry: geometry, materials: materials };

			}

		};

	} )()

} );

export { JSONLoader };
<commit_msg>Update loader.js to instantiate a morphColors array.<commit_after>var THREE = require('three');

var Loader = THREE.Loader;
var LoaderUtils = THREE.LoaderUtils;
var AnimationClip = THREE.AnimationClip;
var Vector3 = THREE.Vector3;
var Vector4 = THREE.Vector4;
var Color = THREE.Color;
var Vector2 = THREE.Vector2;
var Face3 = THREE.Face3;
var Geometry = THREE.Geometry;
var FileLoader = THREE.FileLoader;
var DefaultLoadingManager = THREE.DefaultLoadingManager;

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

function JSONLoader( manager ) {

	if ( typeof manager === 'boolean' ) {

		console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
		manager = undefined;

	}

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

	this.withCredentials = false;

}

Object.assign( JSONLoader.prototype, {

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var texturePath = this.texturePath && ( typeof this.texturePath === 'string' ) ? this.texturePath : LoaderUtils.extractUrlBase( url );

		var loader = new FileLoader( this.manager );
		loader.setWithCredentials( this.withCredentials );
		loader.load( url, function ( text ) {

			var json = JSON.parse( text );
			var metadata = json.metadata;

			if ( metadata !== undefined ) {

				var type = metadata.type;

				if ( type !== undefined ) {

					if ( type.toLowerCase() === 'object' ) {

						console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
						return;

					}

				}

			}

			var object = scope.parse( json, texturePath );
			onLoad( object.geometry, object.materials );

		}, onProgress, onError );

	},

	setTexturePath: function ( value ) {

		this.texturePath = value;

	},

	parse: ( function () {

		function parseModel( json, geometry ) {

			function isBitSet( value, position ) {

				return value & ( 1 << position );

			}

			var i, j, fi,

				offset, zLength,

				colorIndex, normalIndex, uvIndex, materialIndex,

				type,
				isQuad,
				hasMaterial,
				hasFaceVertexUv,
				hasFaceNormal, hasFaceVertexNormal,
				hasFaceColor, hasFaceVertexColor,

				vertex, face, faceA, faceB, hex, normal,

				uvLayer, uv, u, v,

				faces = json.faces,
				vertices = json.vertices,
				normals = json.normals,
				colors = json.colors,

				scale = json.scale,

				nUvLayers = 0;

			if ( json.uvs !== undefined ) {

				// disregard empty arrays

				for ( i = 0; i < json.uvs.length; i ++ ) {

					if ( json.uvs[ i ].length ) nUvLayers ++;

				}

				for ( i = 0; i < nUvLayers; i ++ ) {

					geometry.faceVertexUvs[ i ] = [];

				}

			}

			offset = 0;
			zLength = vertices.length;

			while ( offset < zLength ) {

				vertex = new Vector3();

				vertex.x = vertices[ offset ++ ] * scale;
				vertex.y = vertices[ offset ++ ] * scale;
				vertex.z = vertices[ offset ++ ] * scale;

				geometry.vertices.push( vertex );

			}

			offset = 0;
			zLength = faces.length;

			while ( offset < zLength ) {

				type = faces[ offset ++ ];

				isQuad = isBitSet( type, 0 );
				hasMaterial = isBitSet( type, 1 );
				hasFaceVertexUv = isBitSet( type, 3 );
				hasFaceNormal = isBitSet( type, 4 );
				hasFaceVertexNormal = isBitSet( type, 5 );
				hasFaceColor = isBitSet( type, 6 );
				hasFaceVertexColor = isBitSet( type, 7 );

				// console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);

				if ( isQuad ) {

					faceA = new Face3();
					faceA.a = faces[ offset ];
					faceA.b = faces[ offset + 1 ];
					faceA.c = faces[ offset + 3 ];

					faceB = new Face3();
					faceB.a = faces[ offset + 1 ];
					faceB.b = faces[ offset + 2 ];
					faceB.c = faces[ offset + 3 ];

					offset += 4;

					if ( hasMaterial ) {

						materialIndex = faces[ offset ++ ];
						faceA.materialIndex = materialIndex;
						faceB.materialIndex = materialIndex;

					}

					// to get face <=> uv index correspondence

					fi = geometry.faces.length;

					if ( hasFaceVertexUv ) {

						for ( i = 0; i < nUvLayers; i ++ ) {

							uvLayer = json.uvs[ i ];

							geometry.faceVertexUvs[ i ][ fi ] = [];
							geometry.faceVertexUvs[ i ][ fi + 1 ] = [];

							for ( j = 0; j < 4; j ++ ) {

								uvIndex = faces[ offset ++ ];

								u = uvLayer[ uvIndex * 2 ];
								v = uvLayer[ uvIndex * 2 + 1 ];

								uv = new Vector2( u, v );

								if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
								if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );

							}

						}

					}

					if ( hasFaceNormal ) {

						normalIndex = faces[ offset ++ ] * 3;

						faceA.normal.set(
							normals[ normalIndex ++ ],
							normals[ normalIndex ++ ],
							normals[ normalIndex ]
						);

						faceB.normal.copy( faceA.normal );

					}

					if ( hasFaceVertexNormal ) {

						for ( i = 0; i < 4; i ++ ) {

							normalIndex = faces[ offset ++ ] * 3;

							normal = new Vector3(
								normals[ normalIndex ++ ],
								normals[ normalIndex ++ ],
								normals[ normalIndex ]
							);

							if ( i !== 2 ) faceA.vertexNormals.push( normal );
							if ( i !== 0 ) faceB.vertexNormals.push( normal );

						}

					}

					if ( hasFaceColor ) {

						colorIndex = faces[ offset ++ ];
						hex = colors[ colorIndex ];

						faceA.color.setHex( hex );
						faceB.color.setHex( hex );

					}

					if ( hasFaceVertexColor ) {

						for ( i = 0; i < 4; i ++ ) {

							colorIndex = faces[ offset ++ ];
							hex = colors[ colorIndex ];

							if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
							if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );

						}

					}

					geometry.faces.push( faceA );
					geometry.faces.push( faceB );

				} else {

					face = new Face3();
					face.a = faces[ offset ++ ];
					face.b = faces[ offset ++ ];
					face.c = faces[ offset ++ ];

					if ( hasMaterial ) {

						materialIndex = faces[ offset ++ ];
						face.materialIndex = materialIndex;

					}

					// to get face <=> uv index correspondence

					fi = geometry.faces.length;

					if ( hasFaceVertexUv ) {

						for ( i = 0; i < nUvLayers; i ++ ) {

							uvLayer = json.uvs[ i ];

							geometry.faceVertexUvs[ i ][ fi ] = [];

							for ( j = 0; j < 3; j ++ ) {

								uvIndex = faces[ offset ++ ];

								u = uvLayer[ uvIndex * 2 ];
								v = uvLayer[ uvIndex * 2 + 1 ];

								uv = new Vector2( u, v );

								geometry.faceVertexUvs[ i ][ fi ].push( uv );

							}

						}

					}

					if ( hasFaceNormal ) {

						normalIndex = faces[ offset ++ ] * 3;

						face.normal.set(
							normals[ normalIndex ++ ],
							normals[ normalIndex ++ ],
							normals[ normalIndex ]
						);

					}

					if ( hasFaceVertexNormal ) {

						for ( i = 0; i < 3; i ++ ) {

							normalIndex = faces[ offset ++ ] * 3;

							normal = new Vector3(
								normals[ normalIndex ++ ],
								normals[ normalIndex ++ ],
								normals[ normalIndex ]
							);

							face.vertexNormals.push( normal );

						}

					}

					if ( hasFaceColor ) {

						colorIndex = faces[ offset ++ ];
						face.color.setHex( colors[ colorIndex ] );

					}

					if ( hasFaceVertexColor ) {

						for ( i = 0; i < 3; i ++ ) {

							colorIndex = faces[ offset ++ ];
							face.vertexColors.push( new Color( colors[ colorIndex ] ) );

						}

					}

					geometry.faces.push( face );

				}

			}

		}

		function parseSkin( json, geometry ) {

			var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;

			if ( json.skinWeights ) {

				for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {

					var x = json.skinWeights[ i ];
					var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
					var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
					var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;

					geometry.skinWeights.push( new Vector4( x, y, z, w ) );

				}

			}

			if ( json.skinIndices ) {

				for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {

					var a = json.skinIndices[ i ];
					var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
					var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
					var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;

					geometry.skinIndices.push( new Vector4( a, b, c, d ) );

				}

			}

			geometry.bones = json.bones;

			if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {

				console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
					geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );

			}

		}

		function parseMorphing( json, geometry ) {

			var scale = json.scale;

			if ( json.morphTargets !== undefined ) {

				for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {

					geometry.morphTargets[ i ] = {};
					geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
					geometry.morphTargets[ i ].vertices = [];

					var dstVertices = geometry.morphTargets[ i ].vertices;
					var srcVertices = json.morphTargets[ i ].vertices;

					for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {

						var vertex = new Vector3();
						vertex.x = srcVertices[ v ] * scale;
						vertex.y = srcVertices[ v + 1 ] * scale;
						vertex.z = srcVertices[ v + 2 ] * scale;

						dstVertices.push( vertex );

					}

				}

			}

			if ( json.morphColors !== undefined ) {

				var i, l, c, cl, dstColors, srcColors, color;

				for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {

					geometry.morphColors[ i ] = {};
					geometry.morphColors[ i ].name = json.morphColors[ i ].name;
					geometry.morphColors[ i ].colors = [];

					dstColors = geometry.morphColors[ i ].colors;
					srcColors = json.morphColors[ i ].colors;

					for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {

						color = new THREE.Color( 0xffaa00 );
						color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
						dstColors.push( color );

					}

				}

			}

		}

		function parseAnimations( json, geometry ) {

			var outputAnimations = [];

			// parse old style Bone/Hierarchy animations
			var animations = [];

			if ( json.animation !== undefined ) {

				animations.push( json.animation );

			}

			if ( json.animations !== undefined ) {

				if ( json.animations.length ) {

					animations = animations.concat( json.animations );

				} else {

					animations.push( json.animations );

				}

			}

			for ( var i = 0; i < animations.length; i ++ ) {

				var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
				if ( clip ) outputAnimations.push( clip );

			}

			// parse implicit morph animations
			if ( geometry.morphTargets ) {

				// TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
				var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
				outputAnimations = outputAnimations.concat( morphAnimationClips );

			}

			if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;

		}

		return function parse( json, texturePath ) {

			if ( json.data !== undefined ) {

				// Geometry 4.0 spec
				json = json.data;

			}

			if ( json.scale !== undefined ) {

				json.scale = 1.0 / json.scale;

			} else {

				json.scale = 1.0;

			}

			var geometry = new Geometry();
			geometry.morphColors = [];
			parseModel( json, geometry );
			parseSkin( json, geometry );
			parseMorphing( json, geometry );
			parseAnimations( json, geometry );

			geometry.computeFaceNormals();
			geometry.computeBoundingSphere();

			if ( json.materials === undefined || json.materials.length === 0 ) {

				return { geometry: geometry };

			} else {

				var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );

				return { geometry: geometry, materials: materials };

			}

		};

	} )()

} );

export { JSONLoader };
<|endoftext|>


<commit_before>'use strict';

module.exports = function karmaConfig(config) {
  config.set({
    basePath: '',
    frameworks: [
      'mocha',
      'browserify'
    ],
    files: [
      'src/**/*.js',
      'test/**/*.js'
    ],
    preprocessors: {
      'src/**/*.js': 'browserify',
      'test/**/*.js': 'browserify'
    },
    browserify: {
      debug: true,
      transform: [
        [
          'babelify',
          {
            presets: 'es2015'
          }
        ],
        'browserify-ngannotate',
        require('browserify-istanbul')
      ]
    },
    reporters: [
      'mocha',
      'coverage'
    ],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS2'],
    singleRun: false,
    concurrency: require('os')
      .cpus().length,
    coverageReporter: {
      dir: 'coverage',
      reporters: [
        {
          type: 'html'
        },
        {
          type: 'text-summary'
        }
      ]
    }
  });
};
<commit_msg>.karma.conf fix for browserify-istanbul<commit_after>'use strict';

module.exports = function karmaConfig(config) {
  config.set({
    basePath: '',
    frameworks: [
      'mocha',
      'browserify'
    ],
    files: [
      'src/**/*.js',
      'test/**/*.js'
    ],
    preprocessors: {
      'src/**/*.js': 'browserify',
      'test/**/*.js': 'browserify'
    },
    browserify: {
      debug: true,
      transform: [
        [
          'babelify',
          {
            presets: 'es2015'
          }
        ],
        'browserify-ngannotate',
        [
          'browserify-istanbul',
          {
            instrumenterConfig: {
              embedSource: true
            }
          }
        ]
      ]
    },
    reporters: [
      'mocha',
      'coverage'
    ],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS2'],
    singleRun: false,
    concurrency: require('os')
      .cpus().length,
    coverageReporter: {
      dir: 'coverage',
      reporters: [
        {
          type: 'html'
        },
        {
          type: 'text-summary'
        }
      ]
    }
  });
};
<|endoftext|>


<commit_before>var _ = require('lodash')
var React = require('react')

var CourseList = require('./courseList')
var Course = require('./course')

var makeCourseObjects = require('../helpers/makeCourseObjects')

var Semester = React.createClass({
	makeSemesterName: function() {
		if      (this.props.semester === 1) return 'Fall';
		else if (this.props.semester === 2) return 'Interim';
		else if (this.props.semester === 3) return 'Spring';
		else if (this.props.semester === 4) return 'Early Summer';
		else if (this.props.semester === 5) return 'Late Summer';

		return 'Unknown (' + this.props.semester + ')';
	},
	findActiveSchedules: function() {
		var activeSchedules = this.props.schedules.find(function(schedule) {
			if (schedule.active)
				return schedule.active.val() === true
		})
		return activeSchedules || this.props.schedules[0]
	},
	removeSemester: function() {
		console.log('deleting', String(this.props.year) + '.' + String(this.props.semester))
		console.log(this.props.schedule)
		this.props.schedule.remove()
	},
	render: function() {
		console.log('semester render')

		var semesterName = this.makeSemesterName()
		var active = this.findActiveSchedules()
		var courseObjects = makeCourseObjects(_.uniq(active.val().clbids))

		return React.DOM.div( {className:"semester"},
			React.DOM.header({className: "semester-title"},
				React.DOM.h1(null, semesterName, ' (' + _.size(this.props.schedules) + ')'),
				React.DOM.button({
					className: "remove-semester",
					title: "Remove " + String(this.props.year) + ' ' + this.props.semesterName,
					onClick: this.removeSemester,
				})
			),
			CourseList( {courses: courseObjects} )
		)
	}
})

module.exports = Semester
<commit_msg>Update the removeSemester button<commit_after>var _ = require('lodash')
var React = require('react')

var CourseList = require('./courseList')
var Course = require('./course')

var makeCourseObjects = require('../helpers/makeCourseObjects')

var Semester = React.createClass({
	makeSemesterName: function() {
		if      (this.props.semester === 1) return 'Fall';
		else if (this.props.semester === 2) return 'Interim';
		else if (this.props.semester === 3) return 'Spring';
		else if (this.props.semester === 4) return 'Early Summer';
		else if (this.props.semester === 5) return 'Late Summer';

		return 'Unknown (' + this.props.semester + ')';
	},
	findActiveSchedules: function() {
		var activeSchedules = this.props.schedules.find(function(schedule) {
			if (schedule.active)
				return schedule.active.val() === true
		})
		return activeSchedules || this.props.schedules[0]
	},
	removeSemester: function() {
		console.log(this.props.schedules)
		this.props.schedules.forEach(function(schedule, scheduleIndex, scheduleArray) {
			console.log('deleting', String(this.props.year) + '.' + String(this.props.semester) + '#' + schedule.title.val())
			console.log('to delete:', schedule, scheduleIndex, scheduleArray)
			schedule.remove()
			console.log('deleted', String(this.props.year) + '.' + String(this.props.semester) + '#' + schedule.title.val())
		}, this)
	},
	render: function() {
		console.log('semester render')

		var semesterName = this.makeSemesterName()
		var active = this.findActiveSchedules()
		var courseObjects = makeCourseObjects(_.uniq(active.val().clbids))

		return React.DOM.div( {className:"semester"},
			React.DOM.header({className: "semester-title"},
				React.DOM.h1(null, semesterName, ' (' + _.size(this.props.schedules) + ')'),
				React.DOM.button({
					className: "remove-semester",
					title: "Remove " + String(this.props.year) + ' ' + this.props.semesterName,
					onClick: this.removeSemester,
				})
			),
			CourseList( {courses: courseObjects} )
		)
	}
})

module.exports = Semester
<|endoftext|>


<commit_before>/*
 * Please see the included LICENSE.md file for license terms and conditions.
 */
/* jshint browser:true */
(function() {
    var myFirebaseRef;
	// Wait for DOM tree is ready for access
    document.addEventListener('DOMContentLoaded', function() {
        var canvas = document.getElementById('gameScene');
        // make canvas full screen
        var width = screen.availWidth;
        var height = screen.availHeight;
        canvas.width = width;
        canvas.height = height;

        // get canvas 2d context
        // With canvas 2d context, you can draw anything freely on the canvas.
        // See https://docs.webplatform.org/wiki/tutorials/canvas/canvas_tutorial
        // for tutorials of using canvas.
        var context = canvas.getContext('2d');

        // load and draw image on the canvas
        var img = new Image();
        img.onload = function() {
            context.drawImage(img, (width - img.width) / 2, (height - img.height) / 2);
        };
        img.src = "asset/logo.png";

        myFirebaseRef = new Firebase("https://battlepong.firebaseio.com/");

        watchForRoll();
        throwball(20, 100);

    }, false);

    function throwball (yPercent, velocity) {
      myFirebaseRef.child('throws').push({
        'ypercent': yPercent,
        'velocity': velocity,
        'complete': true,
        'caught': false,
        'thrower': 'player1'
      });
    }

    function watchForRoll () {
      myFirebaseRef.child("throws").on("child_added", function(snapshot,  prevChildKey) {
        if (snapshot.val().complete == false)
          startRoll(snapshot.val());
      });
    }

    function startRoll (snap) {
      console.log(snap);
    }

}());
<commit_msg>Basic set of score and watchers for firebase<commit_after>/*
 * Please see the included LICENSE.md file for license terms and conditions.
 */
/* jshint browser:true */
(function() {
    var myFirebaseRef;
    var myPlayerId = "player1";
	// Wait for DOM tree is ready for access
    document.addEventListener('DOMContentLoaded', function() {
        var canvas = document.getElementById('gameScene');
        // make canvas full screen
        var width = screen.availWidth;
        var height = screen.availHeight;
        canvas.width = width;
        canvas.height = height;

        // get canvas 2d context
        // With canvas 2d context, you can draw anything freely on the canvas.
        // See https://docs.webplatform.org/wiki/tutorials/canvas/canvas_tutorial
        // for tutorials of using canvas.
        var context = canvas.getContext('2d');

        // load and draw image on the canvas
        var img = new Image();
        img.onload = function() {
            context.drawImage(img, (width - img.width) / 2, (height - img.height) / 2);
        };
        img.src = "asset/logo.png";
        init();
    }, false);

    function init() {
      myFirebaseRef = new Firebase("https://battlepong.firebaseio.com/");
      myFirebaseRef.child('players').set({
          'player1': { score: 0},
          'player2': { score: 0}
      });
      watchForThrow();
      throwball(20, 100);
    }

    function throwball (yPercent, velocity) {
      myFirebaseRef.child('throws').push({
        'ypercent': yPercent,
        'velocity': velocity,
        'complete': false,
        'caught': false,
        'thrower': myPlayerId
      });
    }

    function watchForThrow () {
      myFirebaseRef.child("throws").on("child_added", function(snapshot,  prevChildKey) {
        if (snapshot.val().complete == false)
          startRoll(snapshot.key(), snapshot.val());
      });
    }

    function startRoll (id, snap) {
      catchBall(id);
    }

    function catchBall (throwId) {
      myFirebaseRef.child("throws").child(throwId).update({
        complete: true,
        caught: true,
      });

      var scoreRef = myFirebaseRef.child('players').child(myPlayerId).child('score');
      scoreRef.transaction(function(currentScore) {
        return currentScore+10;
      });
    }

    function missBall (throwId) {
      myFirebaseRef.child("throws").child(throwId).update({
        complete: true
      });
    }

}());
<|endoftext|>


<commit_before>/*
 * MagicBootTabs & colorConsole Loader
 * Quickly Load Scripts Required
 *
 * Author: Unreal Designs <contact@unreal-designs.co.uk>
 * Copyright: Unreal Designs 2015
 */

//Declare Version
var MBTCCLoaderVersion = "1.05";

function loader(scripts, loadedCallback) {
	var scriptURLS = {
		"colorConsole": "//rawgit.com/MattCowley/MagicBootTabs/master/src/colorConsole.js",
		"MagicBootTabs": "//rawgit.com/MattCowley/MagicBootTabs/master/src/jquery.magicBootTabs.js"
	}

	var scriptCount = scripts.length;

	function loadScript(url, callback) {
	    // Adding the script tag to the head as suggested before
	    var head = document.getElementsByTagName('head')[0];
	    var script = document.createElement('script');
	    script.type = 'text/javascript';
	    script.src = url;

	    // Then bind the event to the callback function.
	    // There are several events for cross browser compatibility.
	    script.onreadystatechange = callback;
	    script.onload = callback;

	    // Fire the loading
	    head.appendChild(script);
	}
	function loadNext(index) {
		if (index < scriptCount) {
			loadScript(
				scriptURLS[scripts[index]],
				function(){ loadNext(index+1); }
			);
		} else {
			loadedCallback();
		}
	}
	loadNext(0);

}<commit_msg>loader<commit_after>/*
 * MagicBootTabs & colorConsole Loader
 * Quickly Load Scripts Required
 *
 * Author: Unreal Designs <contact@unreal-designs.co.uk>
 * Copyright: Unreal Designs 2015
 */

//Declare Version
var LoaderVersion = "1.06";

function loader(scripts, loadedCallback) {
	var scriptURLS = {
		"colorConsole": "//rawgit.com/MattCowley/MagicBootTabs/master/src/colorConsole.js",
		"MagicBootTabs": "//rawgit.com/MattCowley/MagicBootTabs/master/src/jquery.magicBootTabs.js",
		"jQuery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js",
		"bootStrap": "//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"
	}

	var scriptCount = scripts.length;

	function loadScript(url, callback) {
	    // Adding the script tag to the head as suggested before
	    var head = document.getElementsByTagName('head')[0];
	    var script = document.createElement('script');
	    script.type = 'text/javascript';
	    script.src = url;

	    // Then bind the event to the callback function.
	    // There are several events for cross browser compatibility.
	    script.onreadystatechange = callback;
	    script.onload = callback;

	    // Fire the loading
	    head.appendChild(script);
	}
	function loadNext(index) {
		if (index < scriptCount) {
			loadScript(
				scriptURLS[scripts[index]],
				function(){ loadNext(index+1); }
			);
		} else {
			loadedCallback();
		}
	}
	loadNext(0);

}<|endoftext|>


<commit_before>"use strict";

$(function() {

  $("button#sendMessageButton").click(function() {
    var name = $("input#name").val();
    var jobTitle = $("input#jobTitle").val();
    var company = $("input#company").val();
    var state = $("input#state").val();
    var city = $("input#city").val();
    alert(name+jobTitle+company+state+city);
  });

  $("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
  });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
  $('#success').html('');
});
<commit_msg>Add some search js to reader<commit_after>"use strict";

function isMatch(query, entry) {
  // query: search object
  // entry: data object
  return Object.keys(query).every((key) => entry[key].toLowerCase().includes(query[key].toLowerCase()));
}

var data = [
  {"name": "jake", "jobTitle":"doctor", "company":"goodhospital", "state":"washington", "city": "seattle"},
  {"name": "jim", "jobTitle":"webdev", "company":"google", "state":"san francisco", "city": "california"}
];

$(function() {

  $("button#sendMessageButton").click(function() {
    var name = $("input#name").val();
    var jobTitle = $("input#jobTitle").val();
    var company = $("input#company").val();
    var state = $("input#state").val();
    var city = $("input#city").val();
    var query = {name, jobTitle, company, state, city};
    var matches = data.filter((entry) => isMatch(query, entry));
    alert(JSON.stringify(matches, null, 2));
  });

  $("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
  });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
  $('#success').html('');
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

//Import Actions
import {getUserLoggedIn} from './AppActions'

// Import Style
import styles from './App.css';

// Import Components
import Helmet from 'react-helmet';
import DevTools from './components/DevTools';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Login from './components/Login/Login';
import Home from './components/Home/Home';

export class App extends Component {
  constructor(props) {
    super(props);
    this.state = { isMounted: false };
  }

  componentDidMount() {
    this.props.checkUser();
    this.setState({isMounted: true}); // eslint-disable-line
  }

  render() {
    let home = null
    //if user is logged in then we will render the courses page once it is prepared.
    if(this.props.user.first_name == "login"){
      if(this.props.location.pathname != "/"){
        this.props.history.push("/");
      }
      home = <Login />
    }
    return (

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
        {this.state.isMounted && !window.devToolsExtension && process.env.NODE_ENV === 'development' && <DevTools /> && false}

          <Helmet
            title="Autograder 3.0"
            titleTemplate="%s"
            meta={[
              { charset: 'utf-8' },
              {
                'http-equiv': 'X-UA-Compatible',
                content: 'IE=edge',
              },
              {
                name: 'viewport',
                content: 'width=device-width, initial-scale=1',
              },
            ]}
          />

          {home}

           {this.props.children}

    );
  }
}

// Retrieve data from store as props
function mapStateToProps(state) {
  return {
    user: state.app.user,

  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    checkUser:getUserLoggedIn,
  }, dispatch);
}

export default connect(mapStateToProps,mapDispatchToProps)(App);
<commit_msg>placeholder<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

//Import Actions
import {getUserLoggedIn} from './AppActions'

// Import Style
import styles from './App.css';

// Import Components
import Helmet from 'react-helmet';
import DevTools from './components/DevTools';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Login from './components/Login/Login';
import Home from './components/Home/Home';

export class App extends Component {
  constructor(props) {
    super(props);
    this.state = { isMounted: false };
  }

  componentDidMount() {
    this.props.checkUser();
    this.setState({isMounted: true}); // eslint-disable-line
  }

  render() {
    let home = null
    //if user is logged in then we will render the courses page once it is prepared.
    if(this.props.user.first_name == "login"){
      if(this.props.location.pathname != "/"){
        this.context.router.push("/");
      }
      home = <Login />
    }else{
      if(this.props.location.pathname == "/"){
        this.context.router.push("/courses");
      }
    }
    return (

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
        {this.state.isMounted && !window.devToolsExtension && process.env.NODE_ENV === 'development' && <DevTools /> && false}

          <Helmet
            title="Autograder 3.0"
            titleTemplate="%s"
            meta={[
              { charset: 'utf-8' },
              {
                'http-equiv': 'X-UA-Compatible',
                content: 'IE=edge',
              },
              {
                name: 'viewport',
                content: 'width=device-width, initial-scale=1',
              },
            ]}
          />

          {home}

           {this.props.children}

    );
  }
}

App.contextTypes = {
  router: React.PropTypes.object.isRequired
};

// Retrieve data from store as props
function mapStateToProps(state) {
  return {
    user: state.app.user,

  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    checkUser:getUserLoggedIn,
  }, dispatch);
}

export default connect(mapStateToProps,mapDispatchToProps)(App);
<|endoftext|>


<commit_before>//Define Modules here first
angular.module("omniConfig")
  .factory("TESTNET",["$location",function TestnetFactory($location){
    if($location.host().match('testnet') != null){
      Bitcoin.setNetwork('test');
      return true;
    } else
      return false;
  }])
  .factory("TX_DATA_URL",["TESTNET", function TxDataUrlFactory(TESTNET){
    if(TESTNET)
      return "http://tbtc.blockr.io/tx/info/";
    else
      return "https://blockchain.info/tx/";
  }]);

angular.module("omniFilters", ["omniConfig"]);
angular.module("omniFactories", ["omniConfig"]);
angular.module("omniServices", ["omniConfig", "omniFactories"]);
angular.module("omniControllers", ["omniConfig", "omniFactories", "omniServices"]);

var app = angular.module('omniwallet', [
  'ngRoute',
  'ui.bootstrap',
  'ui.bootstrap.modal',
  'ngNumeraljs',
  'vr.filters.passwordStrength',
  'ngIdle',
  'reCAPTCHA',
  'pascalprecht.translate',
  'nvd3',
  'omniConfig',
  'omniFilters',
  'omniFactories',
  'omniServices',
  'omniControllers'
], function($routeProvider, $locationProvider, $httpProvider) {

  if (!$httpProvider.defaults.headers.get)
        $httpProvider.defaults.headers.get = {};
  $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache, no-store, must-revalidate';
  $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
  $httpProvider.defaults.headers.get['Expires'] = '0';
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
  $httpProvider.defaults.transformRequest = [TransformRequest];

  if (document.location.href.match('testnet') != null) {
    Bitcoin.setNetwork('test');
    TESTNET=true;
  } else {
    TESTNET=false;
  }

  $routeProvider.when('/assets/:page?', {
      templateUrl: function(route) {
        //new views added here
        var availableViews = ['issue','crowdsale'];

        var view;
        var viewFound = availableViews.indexOf(route.page);
        if (viewFound != -1)
          view = '/partials/wallet_assets_' + route.page + '.html';
        else
          view = '/views/wallet/assets.html';

        ga('send', 'event', 'button', 'click', route.page);
        return view;
      }
    }).otherwise({
      redirectTo:'/explorer/assets'
    });

  $routeProvider.when('/wallet/:page?', {
      templateUrl: function(route) {
        //new views added here
        var availableViews = ['overview', 'assets', 'addresses', 'trade', 'history', 'send', 'myoffers', 'settings'];

        var viewFound = availableViews.indexOf(route.page);
        if (viewFound == -1)
          route.page = 'overview';

        var view = '/views/wallet/' + route.page + '.html';
        //DEBUG console.log(view, route.page, view == '/wallet_addresses.html')

        ga('send', 'event', 'button', 'click', route.page);
        return view
      }
    }).otherwise({
    redirectTo: '/wallet'
  });

  $routeProvider.when('/explorer/:page?', {
      templateUrl: function(route) {
        var availableViews = ['overview', 'assets', 'bookmarks', 'following', 'inspector'];

        var viewFound = availableViews.indexOf(route.page);
        if (viewFound == -1)
          route.page = 'overview';

        var view = '/partials/explorer_' + route.page + '.html';
        //DEBUG console.log(view, route.page, view == '/wallet_addresses.html')

        ga('send', 'event', 'button', 'click', route.page);
        return view
      }
    }).otherwise({
    redirectTo: '/explorer'
  });

  $routeProvider.when('/about/:page?', {
      templateUrl: function(route) {
        var availableViews = ['omniwallet', 'mastercoin', 'contact', 'faq' ];

        var viewFound = availableViews.indexOf(route.page);
        if (viewFound == -1) //Default view
          route.page = 'omniwallet';

        var view = '/partials/about_' + route.page + '.html';
        //DEBUG console.log(view, route.page, view == '/wallet_addresses.html')

        ga('send', 'event', 'button', 'click', route.page);
        return view
      }
    }).when('/', {
      templateUrl: '/homepage.html'
    }).when('/login/:uuid', {
      template: '

',
      controller: HiddenLoginController
    }).when('/loginfs/:uuid', {
      template: '

',
      controller: FailedSaveLoginController
    }).when('/import', {
      templateUrl: '/partials/wallet_import.html',
    }).when('/status', {
      templateUrl: '/status.html',
      controller: StatsCtrl
    }).otherwise({
    redirectTo: '/'
  });

  $locationProvider.html5Mode(true).hashPrefix('!');
});

app.config(function($idleProvider, $keepaliveProvider, reCAPTCHAProvider, idleDuration, idleWarningDuration, reCaptchaKey, $translateProvider, EnglishTranslation) {
  $idleProvider.idleDuration(idleDuration);
  $idleProvider.warningDuration(idleWarningDuration);
  // $keepaliveProvider.interval(2);
  // required: please use your own key :)
  reCAPTCHAProvider.setPublicKey(reCaptchaKey);

  // optional: gets passed into the Recaptcha.create call
  reCAPTCHAProvider.setOptions({
      theme: 'clean'
  });

  $translateProvider.translations('en', EnglishTranslation);

  $translateProvider.preferredLanguage('en');
})
.run(function(Account, $location, TESTNET, BalanceSocket) {
  //Whitelist pages
  whitelisted = ['login', 'about', 'status', 'explorer'];

  if (!Account.loggedIn) {
    for (var i = 0; i < whitelisted.length; i++) {
      if ($location.path().search(whitelisted[i]) != -1) {
        return;
      }
    }
    $location.path('/');
  }
  BalanceSocket.connect();
});

//app helpers
function TransformRequest(data) {
  var param = function(obj) {
    var query = '';
    var name, value, fullSubName, subName, subValue, innerObj, i;

    for (name in obj) {
      value = obj[name];

      if (value instanceof Array) {
        for (i = 0; i < value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      } else if (value instanceof Object) {
        for (subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      } else if (value !== undefined && value !== null) {
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}
app.directive('fixedHeader', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        scope: {
            tableHeight: '@'
        },
        link: function ($scope, $elem, $attrs, $ctrl) {
            // wait for content to load into table and the tbody to be visible
            $scope.$watch(function () { return $elem.find("tbody").is(':visible') },
                function (newValue, oldValue) {
                    if (newValue === true) {
                        // wrap in $timeout to give table a chance to finish rendering
                        $timeout(function () {
                            // reset display styles so column widths are correct when measured below
                            $elem.find('thead, tbody').css('display', '');
                            // set widths of columns
                            $elem.find('th').each(function (i, thElem) {
                                thElem = $(thElem);

                                var columnWidth = thElem.width();
                                thElem.width(columnWidth);
                            });
                            $elem.find('td').each(function (j, tdElem) {
                                tdElem = $(tdElem);

                                var columnWidth = tdElem.width();
                                tdElem.width(columnWidth);
                            });

                            // set css styles on thead and tbody
                            $elem.find('thead').css({
                                'display': 'block',
                            });

                            $elem.find('tbody').css({
                                'display': 'block',
                                'height': $scope.tableHeight || '350px',
                                'overflow': 'auto',
                            });

                            var scrollBarWidth = $elem.find('thead').width() - $elem.find('tbody')[0].clientWidth;
                            if (scrollBarWidth > 0) {
                                $elem.find('tbody').each(function (i, elem) {
                                    $(elem).width($(elem).width() + scrollBarWidth);
                                });
                                $elem.find('thead').each(function (j, elem) {
                                    $(elem).width($(elem).width() - scrollBarWidth);
                                });
                            }
                        });
                    }
                });
        }
    }
}]);
<commit_msg>Add assets forms routing<commit_after>//Define Modules here first
angular.module("omniConfig")
  .factory("TESTNET",["$location",function TestnetFactory($location){
    if($location.host().match('testnet') != null){
      Bitcoin.setNetwork('test');
      return true;
    } else
      return false;
  }])
  .factory("TX_DATA_URL",["TESTNET", function TxDataUrlFactory(TESTNET){
    if(TESTNET)
      return "http://tbtc.blockr.io/tx/info/";
    else
      return "https://blockchain.info/tx/";
  }]);

angular.module("omniFilters", ["omniConfig"]);
angular.module("omniFactories", ["omniConfig"]);
angular.module("omniServices", ["omniConfig", "omniFactories"]);
angular.module("omniControllers", ["omniConfig", "omniFactories", "omniServices"]);

var app = angular.module('omniwallet', [
  'ngRoute',
  'ui.bootstrap',
  'ui.bootstrap.modal',
  'ngNumeraljs',
  'vr.filters.passwordStrength',
  'ngIdle',
  'reCAPTCHA',
  'pascalprecht.translate',
  'nvd3',
  'omniConfig',
  'omniFilters',
  'omniFactories',
  'omniServices',
  'omniControllers'
], function($routeProvider, $locationProvider, $httpProvider) {

  if (!$httpProvider.defaults.headers.get)
        $httpProvider.defaults.headers.get = {};
  $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache, no-store, must-revalidate';
  $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
  $httpProvider.defaults.headers.get['Expires'] = '0';
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
  $httpProvider.defaults.transformRequest = [TransformRequest];

  if (document.location.href.match('testnet') != null) {
    Bitcoin.setNetwork('test');
    TESTNET=true;
  } else {
    TESTNET=false;
  }

  $routeProvider.when('/assets/:page?', {
      templateUrl: function(route) {
        //new views added here
        var availableViews = ['issue','crowdsale'];

        var view;
        var viewFound = availableViews.indexOf(route.page);
        if (viewFound != -1)
          view = '/views/assets/' + route.page + '.html';
        else
          view = '/views/wallet/assets.html';

        ga('send', 'event', 'button', 'click', route.page);
        return view;
      }
    }).otherwise({
      redirectTo:'/wallet/assets'
    });

  $routeProvider.when('/wallet/:page?', {
      templateUrl: function(route) {
        //new views added here
        var availableViews = ['overview', 'assets', 'addresses', 'trade', 'history', 'send', 'myoffers', 'settings'];

        var viewFound = availableViews.indexOf(route.page);
        if (viewFound == -1)
          route.page = 'overview';

        var view = '/views/wallet/' + route.page + '.html';
        //DEBUG console.log(view, route.page, view == '/wallet_addresses.html')

        ga('send', 'event', 'button', 'click', route.page);
        return view
      }
    }).otherwise({
    redirectTo: '/wallet'
  });

  $routeProvider.when('/explorer/:page?', {
      templateUrl: function(route) {
        var availableViews = ['overview', 'assets', 'bookmarks', 'following', 'inspector'];

        var viewFound = availableViews.indexOf(route.page);
        if (viewFound == -1)
          route.page = 'overview';

        var view = '/partials/explorer_' + route.page + '.html';
        //DEBUG console.log(view, route.page, view == '/wallet_addresses.html')

        ga('send', 'event', 'button', 'click', route.page);
        return view
      }
    }).otherwise({
    redirectTo: '/explorer'
  });

  $routeProvider.when('/about/:page?', {
      templateUrl: function(route) {
        var availableViews = ['omniwallet', 'mastercoin', 'contact', 'faq' ];

        var viewFound = availableViews.indexOf(route.page);
        if (viewFound == -1) //Default view
          route.page = 'omniwallet';

        var view = '/partials/about_' + route.page + '.html';
        //DEBUG console.log(view, route.page, view == '/wallet_addresses.html')

        ga('send', 'event', 'button', 'click', route.page);
        return view
      }
    }).when('/', {
      templateUrl: '/homepage.html'
    }).when('/login/:uuid', {
      template: '

',
      controller: HiddenLoginController
    }).when('/loginfs/:uuid', {
      template: '

',
      controller: FailedSaveLoginController
    }).when('/import', {
      templateUrl: '/partials/wallet_import.html',
    }).when('/status', {
      templateUrl: '/status.html',
      controller: StatsCtrl
    }).otherwise({
    redirectTo: '/'
  });

  $locationProvider.html5Mode(true).hashPrefix('!');
});

app.config(function($idleProvider, $keepaliveProvider, reCAPTCHAProvider, idleDuration, idleWarningDuration, reCaptchaKey, $translateProvider, EnglishTranslation) {
  $idleProvider.idleDuration(idleDuration);
  $idleProvider.warningDuration(idleWarningDuration);
  // $keepaliveProvider.interval(2);
  // required: please use your own key :)
  reCAPTCHAProvider.setPublicKey(reCaptchaKey);

  // optional: gets passed into the Recaptcha.create call
  reCAPTCHAProvider.setOptions({
      theme: 'clean'
  });

  $translateProvider.translations('en', EnglishTranslation);

  $translateProvider.preferredLanguage('en');
})
.run(function(Account, $location, TESTNET, BalanceSocket) {
  //Whitelist pages
  whitelisted = ['login', 'about', 'status', 'explorer'];

  if (!Account.loggedIn) {
    for (var i = 0; i < whitelisted.length; i++) {
      if ($location.path().search(whitelisted[i]) != -1) {
        return;
      }
    }
    $location.path('/');
  }
  BalanceSocket.connect();
});

//app helpers
function TransformRequest(data) {
  var param = function(obj) {
    var query = '';
    var name, value, fullSubName, subName, subValue, innerObj, i;

    for (name in obj) {
      value = obj[name];

      if (value instanceof Array) {
        for (i = 0; i < value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      } else if (value instanceof Object) {
        for (subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      } else if (value !== undefined && value !== null) {
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}
app.directive('fixedHeader', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        scope: {
            tableHeight: '@'
        },
        link: function ($scope, $elem, $attrs, $ctrl) {
            // wait for content to load into table and the tbody to be visible
            $scope.$watch(function () { return $elem.find("tbody").is(':visible') },
                function (newValue, oldValue) {
                    if (newValue === true) {
                        // wrap in $timeout to give table a chance to finish rendering
                        $timeout(function () {
                            // reset display styles so column widths are correct when measured below
                            $elem.find('thead, tbody').css('display', '');
                            // set widths of columns
                            $elem.find('th').each(function (i, thElem) {
                                thElem = $(thElem);

                                var columnWidth = thElem.width();
                                thElem.width(columnWidth);
                            });
                            $elem.find('td').each(function (j, tdElem) {
                                tdElem = $(tdElem);

                                var columnWidth = tdElem.width();
                                tdElem.width(columnWidth);
                            });

                            // set css styles on thead and tbody
                            $elem.find('thead').css({
                                'display': 'block',
                            });

                            $elem.find('tbody').css({
                                'display': 'block',
                                'height': $scope.tableHeight || '350px',
                                'overflow': 'auto',
                            });

                            var scrollBarWidth = $elem.find('thead').width() - $elem.find('tbody')[0].clientWidth;
                            if (scrollBarWidth > 0) {
                                $elem.find('tbody').each(function (i, elem) {
                                    $(elem).width($(elem).width() + scrollBarWidth);
                                });
                                $elem.find('thead').each(function (j, elem) {
                                    $(elem).width($(elem).width() - scrollBarWidth);
                                });
                            }
                        });
                    }
                });
        }
    }
}]);
<|endoftext|>


<commit_before>/**
 * Copyright 2018 Google LLC
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import loaderUtils from 'loader-utils';
import SingleEntryPlugin from 'webpack/lib/SingleEntryPlugin';
import WebWorkerTemplatePlugin from 'webpack/lib/webworker/WebWorkerTemplatePlugin';

const NAME = 'WorkerPluginLoader';
let hasWarned = false;

export function pitch (request) {
  this.cacheable(false);
  const cb = this.async();

  const compilerOptions = this._compiler.options || {};
  if (!hasWarned && compilerOptions.output && compilerOptions.output.globalObject === 'window') {
    hasWarned = true;
    console.warn('Warning (workerize-loader): output.globalObject is set to "window". It should be set to "self" or "this" to support HMR in Workers.');
  }

  const options = loaderUtils.getOptions(this) || {};
  const chunkFilename = compilerOptions.output.chunkFilename.replace(/\.([a-z]+)$/i, '.worker.$1');
  const workerOptions = {
    filename: chunkFilename.replace(/\[(?:chunkhash|contenthash)(:\d+(?::\d+)?)?\]/g, '[hash$1]'),
    chunkFilename,
    globalObject: 'self'
  };

  const workerCompiler = this._compilation.createChildCompiler(NAME, workerOptions);
  (new WebWorkerTemplatePlugin(workerOptions)).apply(workerCompiler);
  (new SingleEntryPlugin(this.context, request, options.name)).apply(workerCompiler);

  const subCache = `subcache ${__dirname} ${request}`;
  workerCompiler.hooks.compilation.tap(NAME, compilation => {
    if (compilation.cache) {
      if (!compilation.cache[subCache]) compilation.cache[subCache] = {};
      compilation.cache = compilation.cache[subCache];
    }
  });

  workerCompiler.runAsChild((err, entries, compilation) => {
    if (!err && compilation.errors && compilation.errors.length) {
      err = compilation.errors[0];
    }
    const entry = entries && entries[0] && entries[0].files[0];
    if (!err && !entry) err = Error(`WorkerPlugin: no entry for ${request}`);
    if (err) return cb(err);
    return cb(null, `module.exports = __webpack_public_path__ + ${JSON.stringify(entry)}`);
  });
};

export default { pitch };
<commit_msg>Enable FetchCompileWasmTemplatePlugin<commit_after>/**
 * Copyright 2018 Google LLC
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import loaderUtils from 'loader-utils';
import SingleEntryPlugin from 'webpack/lib/SingleEntryPlugin';
import WebWorkerTemplatePlugin from 'webpack/lib/webworker/WebWorkerTemplatePlugin';
import FetchCompileWasmTemplatePlugin from 'webpack/lib/web/FetchCompileWasmTemplatePlugin';

const NAME = 'WorkerPluginLoader';
let hasWarned = false;

export function pitch (request) {
  this.cacheable(false);
  const cb = this.async();

  const compilerOptions = this._compiler.options || {};
  if (!hasWarned && compilerOptions.output && compilerOptions.output.globalObject === 'window') {
    hasWarned = true;
    console.warn('Warning (workerize-loader): output.globalObject is set to "window". It should be set to "self" or "this" to support HMR in Workers.');
  }

  const options = loaderUtils.getOptions(this) || {};
  const chunkFilename = compilerOptions.output.chunkFilename.replace(/\.([a-z]+)$/i, '.worker.$1');
  const workerOptions = {
    filename: chunkFilename.replace(/\[(?:chunkhash|contenthash)(:\d+(?::\d+)?)?\]/g, '[hash$1]'),
    chunkFilename,
    globalObject: 'self'
  };

  const workerCompiler = this._compilation.createChildCompiler(NAME, workerOptions);
  (new WebWorkerTemplatePlugin(workerOptions)).apply(workerCompiler);
  (new FetchCompileWasmTemplatePlugin({
    mangleImports: compilerOptions.optimization.mangleWasmImports
  })).apply(workerCompiler);
  (new SingleEntryPlugin(this.context, request, options.name)).apply(workerCompiler);

  const subCache = `subcache ${__dirname} ${request}`;
  workerCompiler.hooks.compilation.tap(NAME, compilation => {
    if (compilation.cache) {
      if (!compilation.cache[subCache]) compilation.cache[subCache] = {};
      compilation.cache = compilation.cache[subCache];
    }
  });

  workerCompiler.runAsChild((err, entries, compilation) => {
    if (!err && compilation.errors && compilation.errors.length) {
      err = compilation.errors[0];
    }
    const entry = entries && entries[0] && entries[0].files[0];
    if (!err && !entry) err = Error(`WorkerPlugin: no entry for ${request}`);
    if (err) return cb(err);
    return cb(null, `module.exports = __webpack_public_path__ + ${JSON.stringify(entry)}`);
  });
};

export default { pitch };
<|endoftext|>


<commit_before>$.widget( "readmore.carddeck", {
	// Default options
	options: {
		controlwidget: "articleviewer",
		cover: null,
		carddecks: [{ 'url': '/widgets/dictionary/', 'params': {'word':"%%WORD%%"}}]
	},
	_create: function(){
		var _self = this
		// Find any instance of the controlwidget and
		// bind to the `wordclick' event
		$(":readmore-"+this.options.controlwidget).bind(
			this.options.controlwidget+"wordclick",
			function(event, data){
				location.hash = "#cover-"+data['word'];
			}
		)
		$(window).hashchange(function(){
			if(location.hash == ''){
				_self.close(_self.options.cover);
			}else{
				hash_parts = location.hash.split("-");
				if(hash_parts[0] == '#cover'){
					_self.load(hash_parts[1])
				}
			}
		});
	},
	decks: function(word){
		decks = []
		for(var i = 0; i < this.options.carddecks.length ; i++){
			var url = this.options.carddecks[i].url;
			var params = {};
			for(key in this.options.carddecks[i].params){
				params[key] = this.options.carddecks[i].params[key]
					.replace("%%WORD%%", word);
			}
			decks.push({'url':url, 'params':params});
		}
        $.post( "/add_to_history/", {
                article: location.pathname.split('/')[3],
                value: word,
                type: 'word',
                csrfmiddlewaretoken: getCookie('csrftoken'),
        });
		return decks;
	},
    load: function(word){
        var _self = this;
		if(this.options.cover){
			if($(this.options.cover).hasClass('open')){
				alert(0);
				this.carddeck.close();
			}else{
				$(this.options.cover).addClass('open');
				$(this.options.cover).find("#closeCover").click(
						function(){
							alert(1);
							window.history.back();
							return false;
						});
				$(this.options.cover).find("#closeOnBackground").click(
						function(){
							alert(2);
							window.history.back();
							return false;
						});
			}
		}
		this.carddeck = new CardDeck(this.element, this.decks(word));
	},
    close: function(cover){
		alert(3);
		if(cover){
		    $(cover).removeClass('open');
        }
        $('.lastSelected.prevSelected').removeClass('lastSelected');
        $('#selected').addClass('lastSelected');
        $('#selected').addClass('prevSelected');
        $('#selected').removeAttr('id');
        this.carddeck.close();
    }
})
<commit_msg>Added debug info<commit_after>$.widget( "readmore.carddeck", {
	// Default options
	options: {
		controlwidget: "articleviewer",
		cover: null,
		carddecks: [{ 'url': '/widgets/dictionary/', 'params': {'word':"%%WORD%%"}}]
	},
	_create: function(){
		var _self = this
		// Find any instance of the controlwidget and
		// bind to the `wordclick' event
		$(":readmore-"+this.options.controlwidget).bind(
			this.options.controlwidget+"wordclick",
			function(event, data){
				location.hash = "#cover-"+data['word'];
			}
		)
		$(window).hashchange(function(){
			if(location.hash == ''){
				_self.close(_self.options.cover);
			}else{
				hash_parts = location.hash.split("-");
				if(hash_parts[0] == '#cover'){
					_self.load(hash_parts[1])
				}
			}
		});
	},
	decks: function(word){
		decks = []
		for(var i = 0; i < this.options.carddecks.length ; i++){
			var url = this.options.carddecks[i].url;
			var params = {};
			for(key in this.options.carddecks[i].params){
				params[key] = this.options.carddecks[i].params[key]
					.replace("%%WORD%%", word);
			}
			decks.push({'url':url, 'params':params});
		}
        $.post( "/add_to_history/", {
                article: location.pathname.split('/')[3],
                value: word,
                type: 'word',
                csrfmiddlewaretoken: getCookie('csrftoken'),
        });
		return decks;
	},
    load: function(word){
        var _self = this;
		if(this.options.cover){
			if($(this.options.cover).hasClass('open')){
				alert(0);
				this.carddeck.close();
			}else{
				$(this.options.cover).addClass('open');
				$(this.options.cover).find("#closeCover").click(
						function(){
							alert(1);
							//window.history.back();
							return false;
						});
				$(this.options.cover).find("#closeOnBackground").click(
						function(){
							alert(2);
							//window.history.back();
							return false;
						});
			}
		}
		this.carddeck = new CardDeck(this.element, this.decks(word));
	},
    close: function(cover){
		alert(3);
		if(cover){
		    $(cover).removeClass('open');
        }
        $('.lastSelected.prevSelected').removeClass('lastSelected');
        $('#selected').addClass('lastSelected');
        $('#selected').addClass('prevSelected');
        $('#selected').removeAttr('id');
        this.carddeck.close();
    }
})
<|endoftext|>


<commit_before>module.exports = [
  {
    name: '@sentry/browser - CDN Bundle (gzipped)',
    path: 'packages/browser/build/bundle.min.js',
    gzip: true,
    limit: '18 KB',
  },
  {
    name: '@sentry/browser - Webpack',
    path: 'packages/browser/esm/index.js',
    import: '{ init }',
    limit: '19 KB',
  },
  {
    name: '@sentry/react - Webpack',
    path: 'packages/react/esm/index.js',
    import: '{ init }',
    limit: '19 KB',
  },
  {
    name: '@sentry/browser + @sentry/tracing - CDN Bundle (gzipped)',
    path: 'packages/tracing/build/bundle.tracing.min.js',
    gzip: true,
    limit: '23 KB',
  },
];
<commit_msg>fix(build): Increase size limit for browser+tracing bundle (#2899)<commit_after>module.exports = [
  {
    name: '@sentry/browser - CDN Bundle (gzipped)',
    path: 'packages/browser/build/bundle.min.js',
    gzip: true,
    limit: '18 KB',
  },
  {
    name: '@sentry/browser - Webpack',
    path: 'packages/browser/esm/index.js',
    import: '{ init }',
    limit: '19 KB',
  },
  {
    name: '@sentry/react - Webpack',
    path: 'packages/react/esm/index.js',
    import: '{ init }',
    limit: '19 KB',
  },
  {
    name: '@sentry/browser + @sentry/tracing - CDN Bundle (gzipped)',
    path: 'packages/tracing/build/bundle.tracing.min.js',
    gzip: true,
    limit: '25 KB',
  },
];
<|endoftext|>