<commit_before>var gulp = require('gulp');
var path = require('path');
var fs = require('fs');
var glob = require("glob");
var through2 = require('through2');
var runSequence = require('run-sequence');
var exec = require('child_process').exec;
var uiIndex = require('./lib/findBy/tagname/searchIndex/build-stream');
var codeIndex = require('./lib/findBy/code/searchIndex/build-stream');
var Promise = require("bluebird");
var execAsync = Promise.promisify(exec);
var config = require("config");
var mongo = require('./lib/db/connection');
var DATASET_ROOT = config.get('dataset.root');

gulp.task('index:ui', function () {
    gulp.src(path.join(DATASET_ROOT, 'ui', '*.xml'))
        .pipe(uiIndex())
        .pipe(gulp.dest('indexes/tagname'));
});

gulp.task('solr:indexCode', function (callback) {
    glob(path.join(DATASET_ROOT, 'code', '*.txt'), function (er, files) {
        codeIndex.index(files);
        callback();
    });
});

gulp.task('solr:commit', function () {
    codeIndex.commit();
});

gulp.task('extract:archives', function (done) {
    var untarListings = 'tar xvjf ' + path.join(DATASET_ROOT, 'listing',
            'listing.tar.bz2') + ' -C ' + path.join(DATASET_ROOT, 'listing');
    var untarUI = 'tar xvjf ' + path.join(DATASET_ROOT, 'ui', 'ui-xml.tar.bz2') +
        ' -C ' + path.join(DATASET_ROOT, 'ui');
    var untarCode = 'tar xvjf ' + path.join(DATASET_ROOT, 'code',
            'smali-invoked-methods.tar.bz2') + ' -C ' + path.join(DATASET_ROOT,
            'code');
    console.log("Extracting listing details json files...");
    execAsync(untarListings)
        .then(function () {
            console.log("Extracting UI xml files...");
            return execAsync(untarUI);
        })
        .then(function () {
            console.log("Extracting code text files...");
            return execAsync(untarCode);
        })
        .then(function () {
            console.log("All archives have been extracted.");
            done();
        })
        .error(function (error) {
            console.error(error);
            done(error);
        });
});

gulp.task('start:db', function (callback) {
    try {
        fs.mkdirSync(path.join(DATASET_ROOT, 'db'));
    } catch (error) {
        if (error.code != 'EEXIST') callback(error);
    }
    // start Solr in SolrCloud mode as a daemon
    var solr = 'solr start -cloud -V -h ' + config.get('dbConfig.solr.host') +
        ' -p ' + config.get('dbConfig.solr.port');
    console.log("Starting Solr server in SolrCloud mode. " + solr);
    exec(solr,
        function (error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            callback(stderr);
        });
    // start MongoDB
    var mongod = 'mongod --port ' + config.get('dbConfig.mongo.port') +
        ' --config ' + config.get('dbConfig.mongo.config') +
        ' --dbpath ' + path.join(DATASET_ROOT, 'db');
    console.log("Starting MongoDB server: " + mongod);
    exec(mongod,
        function (error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            callback(stderr);
        });
});

gulp.task('mongo:insertListing', function (done) {
    gulp.src(path.join(DATASET_ROOT, 'listing', '*.json'))
        .pipe(new through2.obj(function (file, enc, cb) {
            var doc = JSON.parse(file.contents);
            doc['id'] = doc['n'] + '-' + doc['verc'];
            mongo.upsertOne('listings', doc, doc)
                .then(function () {
                    cb();
                })
                .error(function (e) {
                    console.error('Error in insert:listing task: ' + e.message);
                });
        }, function () {
            done();
        }));

});

gulp.task('mongo:indexListing', function (done) {
    mongo.createIndex('listings', {id: 1}, {unique: true})
        .then(function () {
            done();
        })
        .error(function (e) {
            console.error('Error in mongoIndex task: ' + e.message);
        })
});

gulp.task('mongo:close', function () {
    mongo.close();
});

gulp.task('load:db', function (callback) {
    runSequence('mongo:insertListing', 'mongo:indexListing', 'mongo:close', callback)
});

gulp.task('default', function (callback) {
    runSequence('extract:archives', 'index:ui', 'solr:indexCode', 'solr:commit',
        'load:db', callback);
});<commit_msg>change default task<commit_after>var gulp = require('gulp');
var path = require('path');
var fs = require('fs');
var glob = require("glob");
var through2 = require('through2');
var runSequence = require('run-sequence');
var exec = require('child_process').exec;
var uiIndex = require('./lib/findBy/tagname/searchIndex/build-stream');
var codeIndex = require('./lib/findBy/code/searchIndex/build-stream');
var Promise = require("bluebird");
var execAsync = Promise.promisify(exec);
var config = require("config");
var mongo = require('./lib/db/connection');
var DATASET_ROOT = config.get('dataset.root');

gulp.task('index:ui', function () {
    gulp.src(path.join(DATASET_ROOT, 'ui', '*.xml'))
        .pipe(uiIndex())
        .pipe(gulp.dest('indexes/tagname'));
});

gulp.task('solr:indexCode', function (callback) {
    glob(path.join(DATASET_ROOT, 'code', '*.txt'), function (er, files) {
        codeIndex.index(files);
        callback();
    });
});

gulp.task('solr:commit', function () {
    codeIndex.commit();
});

gulp.task('extract:archives', function (done) {
    var untarListings = 'tar xvjf ' + path.join(DATASET_ROOT, 'listing',
            'listing.tar.bz2') + ' -C ' + path.join(DATASET_ROOT, 'listing');
    var untarUI = 'tar xvjf ' + path.join(DATASET_ROOT, 'ui', 'ui-xml.tar.bz2') +
        ' -C ' + path.join(DATASET_ROOT, 'ui');
    var untarCode = 'tar xvjf ' + path.join(DATASET_ROOT, 'code',
            'smali-invoked-methods.tar.bz2') + ' -C ' + path.join(DATASET_ROOT,
            'code');
    console.log("Extracting listing details json files...");
    execAsync(untarListings)
        .then(function () {
            console.log("Extracting UI xml files...");
            return execAsync(untarUI);
        })
        .then(function () {
            console.log("Extracting code text files...");
            return execAsync(untarCode);
        })
        .then(function () {
            console.log("All archives have been extracted.");
            done();
        })
        .error(function (error) {
            console.error(error);
            done(error);
        });
});

gulp.task('start:db', function (callback) {
    try {
        fs.mkdirSync(path.join(DATASET_ROOT, 'db'));
    } catch (error) {
        if (error.code != 'EEXIST') callback(error);
    }
    // start Solr in SolrCloud mode as a daemon
    var solr = 'solr start -cloud -V -h ' + config.get('dbConfig.solr.host') +
        ' -p ' + config.get('dbConfig.solr.port');
    console.log("Starting Solr server in SolrCloud mode. " + solr);
    exec(solr,
        function (error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            callback(stderr);
        });
    // start MongoDB
    var mongod = 'mongod --port ' + config.get('dbConfig.mongo.port') +
        ' --config ' + config.get('dbConfig.mongo.config') +
        ' --dbpath ' + path.join(DATASET_ROOT, 'db');
    console.log("Starting MongoDB server: " + mongod);
    exec(mongod,
        function (error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            callback(stderr);
        });
});

gulp.task('mongo:insertListing', function (done) {
    gulp.src(path.join(DATASET_ROOT, 'listing', '*.json'))
        .pipe(new through2.obj(function (file, enc, cb) {
            var doc = JSON.parse(file.contents);
            doc['id'] = doc['n'] + '-' + doc['verc'];
            mongo.upsertOne('listings', doc, doc)
                .then(function () {
                    cb();
                })
                .error(function (e) {
                    console.error('Error in insert:listing task: ' + e.message);
                });
        }, function () {
            done();
        }));

});

gulp.task('mongo:indexListing', function (done) {
    mongo.createIndex('listings', {id: 1}, {unique: true})
        .then(function () {
            done();
        })
        .error(function (e) {
            console.error('Error in mongoIndex task: ' + e.message);
        })
});

gulp.task('mongo:close', function () {
    mongo.close();
});

gulp.task('load:db', function (callback) {
    runSequence('mongo:insertListing', 'mongo:indexListing', 'mongo:close', callback)
});

gulp.task('default', function (callback) {
    runSequence('extract:archives', 'load:db', callback);
});<|endoftext|>


<commit_before>/**
* JavaScript project for accessing and normalizing the accelerometer and gyroscope data on mobile devices
*
* @author Doruk Eker <dorukeker@gmail.com>
* @copyright 2015 Doruk Eker <http://dorukeker.com>
* @version 2.0.0
* @license MIT License | http://opensource.org/licenses/MIT
*/

(function (root, factory) {
  if(typeof define === "function" && define.amd) {
    define(function(){
      return (root.GyroNorm = factory());
    });
  } else if(typeof module === "object" && module.exports) {
    module.exports = (root.GyroNorm = factory());
  } else {
    root.GyroNorm = factory();
  }
}(this, function() {
  	/*-------------------------------------------------------*/
	/* PRIVATE VARIABLES */

	var _interval = null;									// Timer to return values
	var _isCalibrating = false;								// Flag if calibrating
	var _calibrationValue = 0;								// Alpha offset value
	var _gravityCoefficient = 0;							// Coefficient to normalze gravity related values
	var _isRunning = false;									// Boolean value if GyroNorm is tracking
	var _isReady = false;									// Boolean value if GyroNorm is is initialized

	var _do = null;											// Object to store the device orientation values
	var _dm = null;											// Object to store the device motion values

	/* OPTIONS */
	var _frequency 				= 50;		// Frequency for the return data in milliseconds
	var _gravityNormalized		= true;		// Flag if to normalize gravity values
	var _orientationBase		= 'game';	// Can be GyroNorm.GAME or GyroNorm.WORLD. GyroNorm.GAME returns orientation values with respect to the head direction of the device. GyroNorm.WORLD returns the orientation values with respect to the actual north direction of the world.
	var _decimalCount			= 2;		// Number of digits after the decimals point for the return values
	var _logger 				= null;		// Function to callback on error. There is no default value. It can only be set by the user on gn.init()
	var _screenAdjusted			= false;	// If set to true it will return screen adjusted values. (e.g. On a horizontal orientation of a mobile device, the head would be one of the sides, instead of  the actual head of the device.)

	var _values = {
		do:{
			alpha:0,
			beta:0,
			gamma:0,
			absolute:false
		},
		dm:{
			x:0,
			y:0,
			z:0,
			gx:0,
			gy:0,
			gz:0,
			alpha:0,
			beta:0,
			gamma:0
		}
	}

	/* Constants */
	var GAME 								= 'game';
	var WORLD 								= 'world';
	var DEVICE_ORIENTATION 					= 'deviceorientation';
	var ACCELERATION 						= 'acceleration';
	var ACCELERATION_INCLUDING_GRAVITY 		= 'accelerationinludinggravity';
	var ROTATION_RATE 						= 'rotationrate';

	/*-------------------------------------------------------*/
	/* PUBLIC FUNCTIONS */

	/*
	*
	* Constructor function
	*
	*/

	var GyroNorm = function(options){}

	/* Constants */
	GyroNorm.prototype.GAME 								= 'game';
	GyroNorm.prototype.WORLD 								= 'world';
	GyroNorm.prototype.DEVICE_ORIENTATION 					= 'deviceorientation';
	GyroNorm.prototype.ACCELERATION 						= 'acceleration';
	GyroNorm.prototype.ACCELERATION_INCLUDING_GRAVITY 		= 'accelerationinludinggravity';
	GyroNorm.prototype.ROTATION_RATE 						= 'rotationrate';

	/*
	*
	* Initialize GyroNorm instance function
	*
	* @param object options - values are as follows. If set in the init function they overwrite the default option values
	* @param int options.frequency
	* @param boolean options.gravityNormalized
	* @param boolean options.orientationBase
	* @param boolean options.decimalCount
	* @param function options.logger
	* @param function options.screenAdjusted
	*
	*/

	GyroNorm.prototype.init = function(options){
		// Assign options that are passed with the constructor function
		if(options && options.frequency) _frequency = options.frequency;
		if(options && options.gravityNormalized) _gravityNormalized = options.gravityNormalized;
		if(options && options.orientationBase) _orientationBase = options.orientationBase;
		if(options && options.decimalCount) _decimalCount = options.decimalCount;
		if(options && options.logger) _logger = options.logger;
		if(options && options.screenAdjusted) _screenAdjusted = options.screenAdjusted;

		return new Promise(function( resolve , reject ){

			var isDeviceOrientationReady = false;
			var isDeviceMotionReady = false;

			new FULLTILT.getDeviceOrientation({ 'type': _orientationBase }).then(function(controller){

				_do = controller;

				isDeviceOrientationReady = true;

				if(isDeviceOrientationReady && isDeviceMotionReady){
					_isReady = true;
					resolve();
				}

			}).catch(function(err){

				reject(err);

			});

			new FULLTILT.getDeviceMotion().then(function(controller){

				_dm = controller;

				// Set gravity coefficient
				_gravityCoefficient = (_dm.getScreenAdjustedAccelerationIncludingGravity().z > 0)? 1 : -1;

				isDeviceMotionReady = true;

				if(isDeviceOrientationReady && isDeviceMotionReady){
					_isReady = true;
					resolve();
				}

			}).catch(function(err){

				reject(err);

			});

		});

	}

	/*
	*
	* Stops all the tracking and listening on the window objects
	*
	*/
	GyroNorm.prototype.end = function(){
		try{
			_isReady = false;
			this.stop();
			_dm.stop();
			_do.stop();
		} catch(err){
			log(err);
		}
	}

	/*
	*
	* Starts tracking the values
	*
	* @param function callback - Callback function to read the values
	*
	*/
	GyroNorm.prototype.start = function(callback){
		if(!_isReady){
			log({message:'GyroNorm is not initialized yet. First call the "init()" function.' , code:1});
			return;
		}

		_interval = setInterval(function(){
			callback(snapShot());
		},_frequency);
		_isRunning = true;
	}

	/*
	*
	* Stops tracking the values
	*
	*/
	GyroNorm.prototype.stop = function(){
		if(_interval){
			clearInterval(_interval);
			_isRunning = false;
		}
	}

	/*
	*
	* Toggles if to normalize gravity related values
	*
	* @param boolean flag
	*
	*/
	GyroNorm.prototype.normalizeGravity = function(flag){
		_gravityNormalized = (flag)?true:false;
	}

	/*
	*
	* Sets the current head direction as alpha = 0
	* Can only be used if device orientation is being tracked, values are not screen adjusted, value type is GyroNorm.EULER and orientation base is GyroNorm.GAME
	*
	* @return: If head direction is set successfully returns true, else false
	*
	*/
	GyroNorm.prototype.setHeadDirection = function(){
		if(_screenAdjusted || _orientationBase === this.WORLD){
			return false;
		}

		_calibrationValue = _do.getFixedFrameEuler().alpha;
		return true;

	}

	/*
	*
	* Sets the log function
	*
	*/
	GyroNorm.prototype.startLogging = function(logger){
		if(logger){
			_logger = logger;
		}
	}

	/*
	*
	* Sets the log function to null which stops the logging
	*
	*/
	GyroNorm.prototype.stopLogging = function(){
		_logger = null;
	}

	/*
	*
	* Returns if certain type of event is available on the device
	*
	* @param string _eventType - possible values are "deviceorientation" , "devicemotion" , "compassneedscalibration"
	*
	* @return true if event is available false if not
	*
	*/
	GyroNorm.prototype.isAvailable = function(_eventType){

		switch(_eventType){
			case this.DEVICE_ORIENTATION:
				return (_do.isAvailable(_do.ALPHA) && _do.isAvailable(_do.BETA) && _do.isAvailable(_do.GAMMA));
				break;

			case this.ACCELERATION:
				return (_dm.isAvailable(_dm.ACCELERATION_X) && _dm.isAvailable(_dm.ACCELERATION_Y) && _dm.isAvailable(_dm.ACCELERATION_Z));
				break;

			case this.ACCELERATION_INCLUDING_GRAVITY:
				return (_dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_X) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Y) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Z));
				break;

			case this.ROTATION_RATE:
				return (_dm.isAvailable(_dm.ROTATION_RATE_ALPHA) && _dm.isAvailable(_dm.ROTATION_RATE_BETA) && _dm.isAvailable(_dm.ROTATION_RATE_GAMMA));
				break;

			default:
				return {
					deviceOrientationAvailable:(_do.isAvailable(_do.ALPHA) && _do.isAvailable(_do.BETA) && _do.isAvailable(_do.GAMMA)),
					accelerationAvailable:(_dm.isAvailable(_dm.ACCELERATION_X) && _dm.isAvailable(_dm.ACCELERATION_Y) && _dm.isAvailable(_dm.ACCELERATION_Z)),
					accelerationIncludingGravityAvailable:(_dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_X) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Y) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Z)),
					rotationRateAvailable:(_dm.isAvailable(_dm.ROTATION_RATE_ALPHA) && _dm.isAvailable(_dm.ROTATION_RATE_BETA) && _dm.isAvailable(_dm.ROTATION_RATE_GAMMA))
				}
				break;
		}
	}

	/*
	*
	* Returns boolean value if the GyroNorm is running
	*
	*/
	GyroNorm.prototype.isRunning = function(){
		return _isRunning;
	}

	/*-------------------------------------------------------*/
	/* PRIVATE FUNCTIONS */

	/*
	*
	* Utility function to round with digits after the decimal point
	*
	* @param float number - the original number to round
	*
	*/
	function rnd(number){
		return Math.round(number * Math.pow(10 , _decimalCount)) / Math.pow(10 , _decimalCount);
	}

	/*
	*
	* Starts calibration
	*
	*/
	function calibrate(){
		_isCalibrating = true;
		_calibrationValues = new Array();
	}

	/*
	*
	* Takes a snapshot of the current deviceo orientaion and device motion values
	*
	*/
	function snapShot(){

		var doSnapShot = {};

		if(_screenAdjusted){
			doSnapShot = _do.getScreenAdjustedEuler();
		} else {
			doSnapShot = _do.getFixedFrameEuler();
		}

		var accSnapShot = _dm.getScreenAdjustedAcceleration();
		var accGraSnapShot = _dm.getScreenAdjustedAccelerationIncludingGravity();
		var rotRateSnapShot = _dm.getScreenAdjustedRotationRate();

		var alphaToSend = 0;

		if(_orientationBase === GAME){
			alphaToSend = doSnapShot.alpha - _calibrationValue;
			alphaToSend = (alphaToSend < 0)?(360 - Math.abs(alphaToSend)):alphaToSend;
		} else {
			alphaToSend = doSnapShot.alpha;
		}

		var snapShot = {
			do:{
				alpha:rnd(alphaToSend),
				beta:rnd(doSnapShot.beta),
				gamma:rnd(doSnapShot.gamma),
				absolute:_do.isAbsolute()
			},
			dm:{
				x:rnd(accSnapShot.x),
				y:rnd(accSnapShot.y),
				z:rnd(accSnapShot.z),
				gx:rnd(accGraSnapShot.x),
				gy:rnd(accGraSnapShot.y),
				gz:rnd(accGraSnapShot.z),
				alpha:rnd(rotRateSnapShot.alpha),
				beta:rnd(rotRateSnapShot.beta),
				gamma:rnd(rotRateSnapShot.gamma)
			}
		};

		// Normalize gravity
		if(_gravityNormalized){
			snapShot.dm.gx *= _gravityCoefficient;
			snapShot.dm.gy *= _gravityCoefficient;
			snapShot.dm.gz *= _gravityCoefficient;
		}

		return snapShot;
	}

	/*
	*
	* Starts listening to orientation event on the window object
	*
	*/
	function log(err){
		if(_logger){
			if(typeof(err) == 'string'){
				err = {message:err , code:0}
			}
			_logger(err);
		}
	}

	return GyroNorm;
}));
<commit_msg>Changed indentation and made spacing consistent. * Changed tabs to 2 space indentation. * Aligned constants and private vars in top of factory function. * Added whitespace to function definitions   * function(){ -> function() { * Added whitespace to if statements   * if(){ -> if () { * Added whitespace between property assignments (for object literals)   * {x:'y' ,z:'a'} -> { x: 'y', z: 'a' } * Added whitespace to all usage of the ternary operator   * x?y:z -> x ? y : z<commit_after>/**
* JavaScript project for accessing and normalizing the accelerometer and gyroscope data on mobile devices
*
* @author Doruk Eker <dorukeker@gmail.com>
* @copyright 2015 Doruk Eker <http://dorukeker.com>
* @version 2.0.0
* @license MIT License | http://opensource.org/licenses/MIT
*/

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(function() {
      return (root.GyroNorm = factory());
    });
  } else if (typeof module === 'object' && module.exports) {
    module.exports = (root.GyroNorm = factory());
  } else {
    root.GyroNorm = factory();
  }
}(this, function() {
  /* Constants */
  var GAME                            = 'game';
  var WORLD                           = 'world';
  var DEVICE_ORIENTATION              = 'deviceorientation';
  var ACCELERATION                    = 'acceleration';
  var ACCELERATION_INCLUDING_GRAVITY  = 'accelerationinludinggravity';
  var ROTATION_RATE                   = 'rotationrate';

  /*-------------------------------------------------------*/
  /* PRIVATE VARIABLES */

  var _interval           = null;       // Timer to return values
  var _isCalibrating      = false;      // Flag if calibrating
  var _calibrationValue   = 0;          // Alpha offset value
  var _gravityCoefficient = 0;          // Coefficient to normalze gravity related values
  var _isRunning          = false;      // Boolean value if GyroNorm is tracking
  var _isReady            = false;      // Boolean value if GyroNorm is is initialized

  var _do                 = null;       // Object to store the device orientation values
  var _dm                 = null;       // Object to store the device motion values

  /* OPTIONS */
  var _frequency          = 50;         // Frequency for the return data in milliseconds
  var _gravityNormalized  = true;       // Flag if to normalize gravity values
  var _orientationBase    = 'game';     // Can be GyroNorm.GAME or GyroNorm.WORLD. GyroNorm.GAME returns orientation values with respect to the head direction of the device. GyroNorm.WORLD returns the orientation values with respect to the actual north direction of the world.
  var _decimalCount       = 2;          // Number of digits after the decimals point for the return values
  var _logger             = null;       // Function to callback on error. There is no default value. It can only be set by the user on gn.init()
  var _screenAdjusted     = false;      // If set to true it will return screen adjusted values. (e.g. On a horizontal orientation of a mobile device, the head would be one of the sides, instead of  the actual head of the device.)

  var _values = {
    do: {
      alpha: 0,
      beta: 0,
      gamma: 0,
      absolute: false
    },
    dm: {
      x: 0,
      y: 0,
      z: 0,
      gx: 0,
      gy: 0,
      gz: 0,
      alpha: 0,
      beta: 0,
      gamma: 0
    }
  }

  /*-------------------------------------------------------*/
  /* PUBLIC FUNCTIONS */

  /*
  *
  * Constructor function
  *
  */

  var GyroNorm = function(options) {}

  /* Constants */
  GyroNorm.prototype.GAME                             = 'game';
  GyroNorm.prototype.WORLD                            = 'world';
  GyroNorm.prototype.DEVICE_ORIENTATION               = 'deviceorientation';
  GyroNorm.prototype.ACCELERATION                     = 'acceleration';
  GyroNorm.prototype.ACCELERATION_INCLUDING_GRAVITY   = 'accelerationinludinggravity';
  GyroNorm.prototype.ROTATION_RATE                    = 'rotationrate';

  /*
  *
  * Initialize GyroNorm instance function
  *
  * @param object options - values are as follows. If set in the init function they overwrite the default option values
  * @param int options.frequency
  * @param boolean options.gravityNormalized
  * @param boolean options.orientationBase
  * @param boolean options.decimalCount
  * @param function options.logger
  * @param function options.screenAdjusted
  *
  */

  GyroNorm.prototype.init = function(options) {
    // Assign options that are passed with the constructor function
    if (options && options.frequency) _frequency = options.frequency;
    if (options && options.gravityNormalized) _gravityNormalized = options.gravityNormalized;
    if (options && options.orientationBase) _orientationBase = options.orientationBase;
    if (options && options.decimalCount) _decimalCount = options.decimalCount;
    if (options && options.logger) _logger = options.logger;
    if (options && options.screenAdjusted) _screenAdjusted = options.screenAdjusted;

    return new Promise(function(resolve, reject) {
      var isDeviceOrientationReady = false;
      var isDeviceMotionReady = false;

      new FULLTILT.getDeviceOrientation({ 'type': _orientationBase }).then(function(controller) {
        _do = controller;
        isDeviceOrientationReady = true;

        if (isDeviceOrientationReady && isDeviceMotionReady) {
          _isReady = true;
          resolve();
        }
      }).catch(function(err) {
        reject(err);
      });

      new FULLTILT.getDeviceMotion().then(function(controller) {
        isDeviceMotionReady = true;
        _dm = controller;
        // Set gravity coefficient
        _gravityCoefficient = (_dm.getScreenAdjustedAccelerationIncludingGravity().z > 0) ? 1 : -1;

        if (isDeviceOrientationReady && isDeviceMotionReady) {
          _isReady = true;
          resolve();
        }
      }).catch(function(err) {
        reject(err);
      });
    });

  }

  /*
  *
  * Stops all the tracking and listening on the window objects
  *
  */
  GyroNorm.prototype.end = function() {
    try {
      _isReady = false;
      this.stop();
      _dm.stop();
      _do.stop();
    } catch(err){
      log(err);
    }
  }

  /*
  *
  * Starts tracking the values
  *
  * @param function callback - Callback function to read the values
  *
  */
  GyroNorm.prototype.start = function(callback) {
    if (!_isReady) {
      log({ message: 'GyroNorm is not initialized yet. First call the "init()" function.', code: 1 });
      return;
    }

    _interval = setInterval(function() {
      callback(snapShot());
    }, _frequency);
    _isRunning = true;
  }

  /*
  *
  * Stops tracking the values
  *
  */
  GyroNorm.prototype.stop = function() {
    if (_interval) {
      clearInterval(_interval);
      _isRunning = false;
    }
  }

  /*
  *
  * Toggles if to normalize gravity related values
  *
  * @param boolean flag
  *
  */
  GyroNorm.prototype.normalizeGravity = function(flag) {
    _gravityNormalized = (flag) ? true : false;
  }

  /*
  *
  * Sets the current head direction as alpha = 0
  * Can only be used if device orientation is being tracked, values are not screen adjusted, value type is GyroNorm.EULER and orientation base is GyroNorm.GAME
  *
  * @return: If head direction is set successfully returns true, else false
  *
  */
  GyroNorm.prototype.setHeadDirection = function() {
    if (_screenAdjusted || _orientationBase === this.WORLD) {
      return false;
    }

    _calibrationValue = _do.getFixedFrameEuler().alpha;
    return true;
  }

  /*
  *
  * Sets the log function
  *
  */
  GyroNorm.prototype.startLogging = function(logger) {
    if (logger) {
      _logger = logger;
    }
  }

  /*
  *
  * Sets the log function to null which stops the logging
  *
  */
  GyroNorm.prototype.stopLogging = function() {
    _logger = null;
  }

  /*
  *
  * Returns if certain type of event is available on the device
  *
  * @param string _eventType - possible values are "deviceorientation" , "devicemotion" , "compassneedscalibration"
  *
  * @return true if event is available false if not
  *
  */
  GyroNorm.prototype.isAvailable = function(_eventType) {

    switch (_eventType) {
      case this.DEVICE_ORIENTATION:
        return (_do.isAvailable(_do.ALPHA) && _do.isAvailable(_do.BETA) && _do.isAvailable(_do.GAMMA));
        break;

      case this.ACCELERATION:
        return (_dm.isAvailable(_dm.ACCELERATION_X) && _dm.isAvailable(_dm.ACCELERATION_Y) && _dm.isAvailable(_dm.ACCELERATION_Z));
        break;

      case this.ACCELERATION_INCLUDING_GRAVITY:
        return (_dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_X) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Y) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Z));
        break;

      case this.ROTATION_RATE:
        return (_dm.isAvailable(_dm.ROTATION_RATE_ALPHA) && _dm.isAvailable(_dm.ROTATION_RATE_BETA) && _dm.isAvailable(_dm.ROTATION_RATE_GAMMA));
        break;

      default:
        return {
          deviceOrientationAvailable: (_do.isAvailable(_do.ALPHA) && _do.isAvailable(_do.BETA) && _do.isAvailable(_do.GAMMA)),
          accelerationAvailable: (_dm.isAvailable(_dm.ACCELERATION_X) && _dm.isAvailable(_dm.ACCELERATION_Y) && _dm.isAvailable(_dm.ACCELERATION_Z)),
          accelerationIncludingGravityAvailable: (_dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_X) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Y) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Z)),
          rotationRateAvailable: (_dm.isAvailable(_dm.ROTATION_RATE_ALPHA) && _dm.isAvailable(_dm.ROTATION_RATE_BETA) && _dm.isAvailable(_dm.ROTATION_RATE_GAMMA))
        }
        break;
    }
  }

  /*
  *
  * Returns boolean value if the GyroNorm is running
  *
  */
  GyroNorm.prototype.isRunning = function() {
    return _isRunning;
  }

  /*-------------------------------------------------------*/
  /* PRIVATE FUNCTIONS */

  /*
  *
  * Utility function to round with digits after the decimal point
  *
  * @param float number - the original number to round
  *
  */
  function rnd(number) {
    return Math.round(number * Math.pow(10, _decimalCount)) / Math.pow(10, _decimalCount);
  }

  /*
  *
  * Starts calibration
  *
  */
  function calibrate() {
    _isCalibrating = true;
    _calibrationValues = new Array();
  }

  /*
  *
  * Takes a snapshot of the current deviceo orientaion and device motion values
  *
  */
  function snapShot() {
    var doSnapShot = {};

    if (_screenAdjusted) {
      doSnapShot = _do.getScreenAdjustedEuler();
    } else {
      doSnapShot = _do.getFixedFrameEuler();
    }

    var accSnapShot = _dm.getScreenAdjustedAcceleration();
    var accGraSnapShot = _dm.getScreenAdjustedAccelerationIncludingGravity();
    var rotRateSnapShot = _dm.getScreenAdjustedRotationRate();

    var alphaToSend = 0;

    if (_orientationBase === GAME) {
      alphaToSend = doSnapShot.alpha - _calibrationValue;
      alphaToSend = (alphaToSend < 0) ? (360 - Math.abs(alphaToSend)) : alphaToSend;
    } else {
      alphaToSend = doSnapShot.alpha;
    }

    var snapShot = {
      do: {
        alpha: rnd(alphaToSend),
        beta: rnd(doSnapShot.beta),
        gamma: rnd(doSnapShot.gamma),
        absolute: _do.isAbsolute()
      },
      dm: {
        x: rnd(accSnapShot.x),
        y: rnd(accSnapShot.y),
        z: rnd(accSnapShot.z),
        gx: rnd(accGraSnapShot.x),
        gy: rnd(accGraSnapShot.y),
        gz: rnd(accGraSnapShot.z),
        alpha: rnd(rotRateSnapShot.alpha),
        beta: rnd(rotRateSnapShot.beta),
        gamma: rnd(rotRateSnapShot.gamma)
      }
    };

    // Normalize gravity
    if (_gravityNormalized) {
      snapShot.dm.gx *= _gravityCoefficient;
      snapShot.dm.gy *= _gravityCoefficient;
      snapShot.dm.gz *= _gravityCoefficient;
    }

    return snapShot;
  }

  /*
  *
  * Starts listening to orientation event on the window object
  *
  */
  function log(err) {
    if (_logger) {
      if (typeof(err) == 'string') {
        err = { message: err, code: 0 }
      }
      _logger(err);
    }
  }

  return GyroNorm;
}));
<|endoftext|>


<commit_before>'use strict';
const db = require('../../db/data-service');
const _ = require('lodash');
const superagent = require('superagent-promise')(require('superagent'), Promise);

function recordPayment() {
  // contact AIS team to create a payment transaction

  // this is Group 1
  return superagent
    .post('52.168.10.209:1337/transaction')
    .send({
      subledgerId: 6, // for sales revenue
    	amount: 550, // this should really be passed in
    	date: (new Date).toISOString(),
    	description: "testing sales team integration"
    })
    .set('Content-Type', 'application/json')
    .catch((err) => {
      throw new Error('Failed to record payment with AIS: ' + err);
    });

  // group 2 is pending

  // return Promise.resolve('successfully recorded the payment');
}

function scheduleDelivery() {
  // contact SCM team to schedule a delivery
  return Promise.resolve('successfully scheduled a delivery'); //@TODO:this needs to be a POST request to SCM team
  // return Promise.reject(new Error('SCM goes boom!'));
}

function saveOrder(params) {
  // save the order data to our own database
  const orderObject = _.pick(params, ['user_id', 'product_id', 'salesperson_id', 'quantity']);
  return db
    .putItem({
      database: 'Orders',
      table: 'table1',
      item: orderObject
    })
    .then(() => {
      const salesObject = {
        date: parseInt(Date.now() / 1000, 10),
        item: params.product_id,
        quantity: params.quantity,
        discount: 0,
        location: 'N/A',
        channel: 1, // retail
        promotion: 4 // personal selling
      };
      return db.putItem({
        database: 'Marketing',
        table: 'sales',
        item: salesObject
      });
    })
    .catch((err) => {
      throw new Error('Failed to save order to DB: ' + err); // this is impossible
    });
}

function newOrder(params) {
  return recordPayment()
    .then(() => {
      return scheduleDelivery()
        .then(() => {
          return saveOrder(params);
        });
    });
}

module.exports = {
  newOrder
};
<commit_msg>update order processing to save shipping address and other feilds<commit_after>'use strict';
const db = require('../../db/data-service');
const _ = require('lodash');
const superagent = require('superagent-promise')(require('superagent'), Promise);

function recordPayment(params) {
  // contact AIS team to create a payment transaction

  // this is Group 1
  return superagent
    .post('52.168.10.209:1337/transaction')
    .send({
      subledgerId: 6, // for sales revenue
    	amount: params.price_total, // this should really be passed in
    	date: (new Date).toISOString(),
    	description: `Sale of ${params.quantity} unit of '${params.product_name}' to user_${params.user_id}:${params.user_name}`
    })
    .set('Content-Type', 'application/json')
    .catch((err) => {
      throw new Error('Failed to record payment with AIS: ' + err);
    });

  // group 2 is pending

  // return Promise.resolve('successfully recorded the payment');
}

function scheduleDelivery(params) {
  // contact SCM team to schedule a delivery
  // console.log({
  //   order_id: params.orderId,
  //   shipping_address: params.ship_addr,
  //   model: params.product_name,
  //   quantity: params.quantity
  // });
  return Promise.resolve('successfully scheduled a delivery'); //@TODO:this needs to be a POST request to SCM team
  // return Promise.reject(new Error('SCM goes boom!'));
}

function saveOrder(params) {
  // save the order data to our own database
  const salesObject = {
    date: parseInt(Date.now() / 1000, 10),
    item: params.product_id,
    quantity: params.quantity,
    discount: 0,
    location: 'N/A',
    channel: 1, // retail
    promotion: 4 // personal selling
  };

  return db
    .putItem({
      database: 'Marketing',
      table: 'sales',
      item: salesObject
    })
    .then(() => {
      return db.putItem({
        database: 'Orders',
        table: 'table1',
        item: params
      });
    })
    .catch((err) => {
      throw new Error('Failed to save order to DB: ' + err); // this is impossible
    });
}

function newOrder(params) {
  return saveOrder(params)
    .then((orderItem) => {
      params.orderId = orderItem.id;
      return recordPayment(params)
        .then(() => {
          return scheduleDelivery(params);
        });
    });
}

module.exports = {
  newOrder
};
<|endoftext|>


<commit_before>enyo.kind({
	name: "ServiceRegistry",
	debug: false,
	kind: enyo.Component,
	events: {
		onServicesChange: ""
	},
	components: [
		{name: "errorPopup", kind: "Ares.ErrorPopup"}
	],
	published: {
		services: []
	},
	create: function() {
		this.inherited(arguments);
		if (!ServiceRegistry.instance) {
			ServiceRegistry.instance = this;
			this.reloadServices();
		}
	},
	listServices: function(inType) {
		if (this.services.length === 0) {
			this.reloadServices();
		} else {
			this.notifyServicesChange();
		}
	},
	serviceFailure: function(serviceType, serviceId) {
		this.error("type="+ serviceType + ", id=" + serviceId);
		this.reloadServices();
	},
	reloadServices: function() {
		var self = this;
		this._reloadServices(function(err) {
			if (err) {
					self._handleReloadError(err);
			} else {
					self.notifyServicesChange();
			}
		});
	},
	/**
	 * @private
	 */
	_reloadServices: function(next) {
		if (this.debug) this.log("Refreshing the list of available services");
		var origin = window.location.origin || window.location.protocol + "//" + window.location.host; // Webkit/FF vs IE
		var url = origin + '/res/services';
		this.services = [];

		/* built-in services */

		// http://www.html5rocks.com/en/tutorials/file/filesystem/
		if (null /*window.requestFileSystem*/) {
			this.services.push({
				type: "filesystem",
				provider: "browser",
				name: "Browser Local Storage",
				icon: "server",
				moniker: "Browser Local Storage"
			});
		}

		/* Hermes Services (reload from the IDE server) */
		if (origin.match('^http')) {
			var req = new enyo.Ajax({url: url, handleAs: 'json'})
				.response(this, function(inSender, inValue) {
					var configs, self = this;
					if (inValue) {
						if (inValue.services && inValue.services[0]) {
							// dis-regard inactive service providers
							configs = inValue.services.filter(function(config){
								return config.active;
							});
							enyo.forEach(configs, function(config){
								this.services.push({
									config: config
								});
							}, this);
							this.complete(next);
						}
					} else {
						next(new Error("Empty response from Ares IDE Server"));
					}
					if (this.debug) this.log(this.services);
				})
				.error(this, function(err){
					next(err);
				})
				.go();
		}

	},
	/**
	 * Complete services configuration using localStorage
	 *
	 * Complement services loaded from the server with per-service
	 * data in the browser localStorage (for example the 'auth'
	 * property).  The completion vallbaclk is invoked once every
	 * configured services are completed.
	 *
	 * @param {Function} next a CommonJS callback
	 * @private
	 */
	complete: function(next) {
		var self = this,
		    tasks = enyo.map(this.services, function(service){
			return function(cb) {
				var key = [self.SERVICES_STORAGE_KEY, service.config.id].join('.');
				if (self.debug) self.log("localStorage[" + key + "]...");
				Ares.LocalStorage.get(key, function(str) {
					if (self.debug) self.log("localStorage[" + key + "] = ", str);
					var obj;
					try {
						obj = JSON.parse(str);
					} catch(e) {
						obj = {};
					}
					ares.extend(service.config, obj);
					self.instanciate(service, cb);
				});
			};
		});
		async.parallel(tasks, next);
	},
	instanciate: function(service, next) {
		if (this.debug) this.log("id:", service.config.id, "config:", service.config);
		try {
			if (service.config.type === "filesystem" && service.config.provider === "hermes") {
				// hermes type of services use
				// a common front-end
				service.impl = new HermesFileSystem();
				service.impl.notifyFailure = enyo.bind(this, this.serviceFailure, service.config.type, service.config.id);
			} else if (service.config.type === "build" && service.config.provider === "hermes" && service.config.id === "phonegap") {
				service.impl = new Phonegap.Build();
			} else if (service.config.type === "other" && service.config.provider === "hermes" && service.config.id === "openwebos") {
				service.impl = new OpenwebosBuild();
			}
			if (this.debug) this.log("id:", service.config.id, "created");
			// If the service does not define an
			// 'authorize()' entry point (which optionally
			// returns user acccount information), stub it
			// using a Common-JS pass-through.
			if (service.impl && !service.impl.authorize) {
				if (this.debug) this.log("Adding " + service.config.id + "#authorize() stub");
				service.impl.authorize = enyo.bind(service.impl, function(next) {
					if (this.debug) this.log('authorize(): stubbed');
					next(null, {});
				});
			}

			// Make sure both the service configuration
			// Object & the resulting implementation
			// Object know the serviceId.
			service.impl.id = service.config.id;

			service.impl.setConfig(service.config);
			if (this.debug) this.log("id:", service.config.id, "configured");
			next();
		} catch(err) {
			this.error(err);
			next(err);
		}
	},
	/**
	 * @private
	 */
	SERVICES_STORAGE_KEY: "com.enyojs.ares.services",
	/**
	 * Set the given value in the given serviceId configuration
	 *
	 * Update the living instances & save the modified
	 * configuration in the localStorage, if applicable.
	 *
	 * Today, only auth part of the given config object is saved
	 * to localStorage.
	 * @param {String} inServiceId
	 * @param {Object} inConfig
	 * @param {Function} inCallback a CommonJS callback
	 */
	setConfig: function (inServiceId, inConfig, inCallback) {
		if (this.debug) this.log("serviceId:", inServiceId, "config:", inConfig);
		var service = this.resolveServiceId(inServiceId);
		if (!service) return;	// should we rather fail here?
		ares.extend(service.config, inConfig);
		service.setConfig(service.config);

		var key = [this.SERVICES_STORAGE_KEY, service.config.id].join('.');
		Ares.LocalStorage.set(key, JSON.stringify({auth: service.config.auth}), inCallback);
	},
	/**
	 * @param {String} serviceId
	 * @return {Object} service associated with the given serviceId
	 * @public
	 * @deprecated
	 * @see ServiceRegistry#filter
	 */
	resolveServiceId: function(serviceId) {
		var services = this.filter({properties: ['id'], id: serviceId});
		return services && services[0];
	},
	/**
	 * Give services whose type matches the given one
	 *
	 * If type is not provided or falsy, this method returns every
	 * registered & active services.
	 *
	 * @param {String} type one of ['filesystem', 'build', undefined]
	 * @return {Array} services matching the required type
	 * @public
	 * @deprecated
	 * @see ServiceRegistry#filter
	 */
	getServicesByType: function(type) {
		return this.filter({properties: ['type'], type: type});
	},
	/**
	 * Get {Array} or service matching the given criteria
	 * @param {Object} criteria
	 * @return {Array} services matching the required criteria
	 * @public
	 */
	filter: function(criteria) {
		//if (this.debug) this.log("criteria:", criteria, ", services:", this.services);
		var matches = enyo.filter(this.services, function(service){
			var match = true;
			if (criteria &&
			    criteria.properties &&
			    criteria.properties.length &&
			    criteria.properties[0]) {
				enyo.forEach(criteria.properties, function(prop) {
					if (criteria[prop]) {
						// filter on criteria property value
						match = match && (service.config[prop] === criteria[prop]);
					} else {
						// filter on criteria property presence
						match = match && (service.config[prop] !== undefined);
					}
				}, this);
			}
			//if (this.debug) this.log("match:", match, "<= service:", service.config);
			return match;
		}, this);
		var services = [];
		//if (this.debug) this.log("matches:", matches);
		enyo.forEach(matches, function(match){
			if (match.impl) {
				services.push(match.impl);
			}
		}, this);
		if (this.debug) this.log("criteria:", criteria , " => services:", services);
		return services;
	},
	/**
	 * Calls the given callback for each instanciated service
	 *
	 * The service implementation instance is the first & only
	 * parameter of the callback.
	 *
	 * @param {Function} fn the callback
	 * @return nothing
	 */
	forEach: function(fn) {
		enyo.forEach(this.services, function(service) {
			if (service.impl) {
				fn(service.impl);
			}
		}, this);
	},
	//* @private
	_handleReloadError: function(err) {
		this.$.errorPopup.setErrorMsg("Ares IDE Server returned an error");
		this.$.errorPopup.show();
		this.error("Error: "+JSON.stringify(err));
	},
	/**
	 * Notify every possible users of a change in the list of providers
	 *
	 * For example, there might be many instances of the
	 * {ProvidersList} control (widget) in the application.
	 *
	 * @private
	 */
	notifyServicesChange: function() {
		if (this.debug) this.log("sending signal...");
		enyo.Signals.send("onServicesChange", {serviceRegistry: this});
	},
	statics: {
		instance: null
	}
});
<commit_msg>ENYO-1783: Renamed project gen into prjToolkit<commit_after>enyo.kind({
	name: "ServiceRegistry",
	debug: false,
	kind: enyo.Component,
	events: {
		onServicesChange: ""
	},
	components: [
		{name: "errorPopup", kind: "Ares.ErrorPopup"}
	],
	published: {
		services: []
	},
	create: function() {
		this.inherited(arguments);
		if (!ServiceRegistry.instance) {
			ServiceRegistry.instance = this;
			this.reloadServices();
		}
	},
	listServices: function(inType) {
		if (this.services.length === 0) {
			this.reloadServices();
		} else {
			this.notifyServicesChange();
		}
	},
	serviceFailure: function(serviceType, serviceId) {
		this.error("type="+ serviceType + ", id=" + serviceId);
		this.reloadServices();
	},
	reloadServices: function() {
		var self = this;
		this._reloadServices(function(err) {
			if (err) {
					self._handleReloadError(err);
			} else {
					self.notifyServicesChange();
			}
		});
	},
	/**
	 * @private
	 */
	_reloadServices: function(next) {
		if (this.debug) this.log("Refreshing the list of available services");
		var origin = window.location.origin || window.location.protocol + "//" + window.location.host; // Webkit/FF vs IE
		var url = origin + '/res/services';
		this.services = [];

		/* built-in services */

		// http://www.html5rocks.com/en/tutorials/file/filesystem/
		if (null /*window.requestFileSystem*/) {
			this.services.push({
				type: "filesystem",
				provider: "browser",
				name: "Browser Local Storage",
				icon: "server",
				moniker: "Browser Local Storage"
			});
		}

		/* Hermes Services (reload from the IDE server) */
		if (origin.match('^http')) {
			var req = new enyo.Ajax({url: url, handleAs: 'json'})
				.response(this, function(inSender, inValue) {
					var configs, self = this;
					if (inValue) {
						if (inValue.services && inValue.services[0]) {
							// dis-regard inactive service providers
							configs = inValue.services.filter(function(config){
								return config.active;
							});
							enyo.forEach(configs, function(config){
								this.services.push({
									config: config
								});
							}, this);
							this.complete(next);
						}
					} else {
						next(new Error("Empty response from Ares IDE Server"));
					}
					if (this.debug) this.log(this.services);
				})
				.error(this, function(err){
					next(err);
				})
				.go();
		}

	},
	/**
	 * Complete services configuration using localStorage
	 *
	 * Complement services loaded from the server with per-service
	 * data in the browser localStorage (for example the 'auth'
	 * property).  The completion vallbaclk is invoked once every
	 * configured services are completed.
	 *
	 * @param {Function} next a CommonJS callback
	 * @private
	 */
	complete: function(next) {
		var self = this,
		    tasks = enyo.map(this.services, function(service){
			return function(cb) {
				var key = [self.SERVICES_STORAGE_KEY, service.config.id].join('.');
				if (self.debug) self.log("localStorage[" + key + "]...");
				Ares.LocalStorage.get(key, function(str) {
					if (self.debug) self.log("localStorage[" + key + "] = ", str);
					var obj;
					try {
						obj = JSON.parse(str);
					} catch(e) {
						obj = {};
					}
					ares.extend(service.config, obj);
					self.instanciate(service, cb);
				});
			};
		});
		async.parallel(tasks, next);
	},
	instanciate: function(service, next) {
		if (this.debug) this.log("id:", service.config.id, "config:", service.config);
		try {
			if (service.config.type === "filesystem" && service.config.provider === "hermes") {
				// hermes type of services use
				// a common front-end
				service.impl = new HermesFileSystem();
				service.impl.notifyFailure = enyo.bind(this, this.serviceFailure, service.config.type, service.config.id);
			} else if (service.config.type === "build" && service.config.provider === "hermes" && service.config.id === "phonegap") {
				service.impl = new Phonegap.Build();
			} else if (service.config.type === "other" && service.config.provider === "hermes" && service.config.id === "prj-toolkit") {
				service.impl = new ProjectToolkit();
			} else if (service.config.type === "plugin") {
				// TODO: TBC
			}
			if (service.impl) {
				if (this.debug) this.log("id:", service.config.id, "created");
				// If the service does not define an
				// 'authorize()' entry point (which optionally
				// returns user acccount information), stub it
				// using a Common-JS pass-through.
				if (service.impl && !service.impl.authorize) {
					if (this.debug) this.log("Adding " + service.config.id + "#authorize() stub");
					service.impl.authorize = enyo.bind(service.impl, function(next) {
						if (this.debug) this.log('authorize(): stubbed');
						next(null, {});
					});
				}

				// Make sure both the service configuration
				// Object & the resulting implementation
				// Object know the serviceId.
				service.impl.id = service.config.id;

				service.impl.setConfig(service.config);
				if (this.debug) this.log("id:", service.config.id, "configured");
			} else {
				this.log("Ignoring service: " + service.config.id);
			}
			next();
		} catch(err) {
			this.error(err);
			next(err);
		}
	},
	/**
	 * @private
	 */
	SERVICES_STORAGE_KEY: "com.enyojs.ares.services",
	/**
	 * Set the given value in the given serviceId configuration
	 *
	 * Update the living instances & save the modified
	 * configuration in the localStorage, if applicable.
	 *
	 * Today, only auth part of the given config object is saved
	 * to localStorage.
	 * @param {String} inServiceId
	 * @param {Object} inConfig
	 * @param {Function} inCallback a CommonJS callback
	 */
	setConfig: function (inServiceId, inConfig, inCallback) {
		if (this.debug) this.log("serviceId:", inServiceId, "config:", inConfig);
		var service = this.resolveServiceId(inServiceId);
		if (!service) return;	// should we rather fail here?
		ares.extend(service.config, inConfig);
		service.setConfig(service.config);

		var key = [this.SERVICES_STORAGE_KEY, service.config.id].join('.');
		Ares.LocalStorage.set(key, JSON.stringify({auth: service.config.auth}), inCallback);
	},
	/**
	 * @param {String} serviceId
	 * @return {Object} service associated with the given serviceId
	 * @public
	 * @deprecated
	 * @see ServiceRegistry#filter
	 */
	resolveServiceId: function(serviceId) {
		var services = this.filter({properties: ['id'], id: serviceId});
		return services && services[0];
	},
	/**
	 * Give services whose type matches the given one
	 *
	 * If type is not provided or falsy, this method returns every
	 * registered & active services.
	 *
	 * @param {String} type one of ['filesystem', 'build', undefined]
	 * @return {Array} services matching the required type
	 * @public
	 * @deprecated
	 * @see ServiceRegistry#filter
	 */
	getServicesByType: function(type) {
		return this.filter({properties: ['type'], type: type});
	},
	/**
	 * Get {Array} or service matching the given criteria
	 * @param {Object} criteria
	 * @return {Array} services matching the required criteria
	 * @public
	 */
	filter: function(criteria) {
		//if (this.debug) this.log("criteria:", criteria, ", services:", this.services);
		var matches = enyo.filter(this.services, function(service){
			var match = true;
			if (criteria &&
			    criteria.properties &&
			    criteria.properties.length &&
			    criteria.properties[0]) {
				enyo.forEach(criteria.properties, function(prop) {
					if (criteria[prop]) {
						// filter on criteria property value
						match = match && (service.config[prop] === criteria[prop]);
					} else {
						// filter on criteria property presence
						match = match && (service.config[prop] !== undefined);
					}
				}, this);
			}
			//if (this.debug) this.log("match:", match, "<= service:", service.config);
			return match;
		}, this);
		var services = [];
		//if (this.debug) this.log("matches:", matches);
		enyo.forEach(matches, function(match){
			if (match.impl) {
				services.push(match.impl);
			}
		}, this);
		if (this.debug) this.log("criteria:", criteria , " => services:", services);
		return services;
	},
	/**
	 * Calls the given callback for each instanciated service
	 *
	 * The service implementation instance is the first & only
	 * parameter of the callback.
	 *
	 * @param {Function} fn the callback
	 * @return nothing
	 */
	forEach: function(fn) {
		enyo.forEach(this.services, function(service) {
			if (service.impl) {
				fn(service.impl);
			}
		}, this);
	},
	//* @private
	_handleReloadError: function(err) {
		this.$.errorPopup.setErrorMsg("Ares IDE Server returned an error");
		this.$.errorPopup.show();
		this.error("Error: "+JSON.stringify(err));
	},
	/**
	 * Notify every possible users of a change in the list of providers
	 *
	 * For example, there might be many instances of the
	 * {ProvidersList} control (widget) in the application.
	 *
	 * @private
	 */
	notifyServicesChange: function() {
		if (this.debug) this.log("sending signal...");
		enyo.Signals.send("onServicesChange", {serviceRegistry: this});
	},
	statics: {
		instance: null
	}
});
<|endoftext|>


<commit_before>enyo.kind({
	name: "ServiceRegistry",
	debug: false,
	kind: enyo.Component,
	events: {
		onServicesChange: ""
	},
	components: [
		{name: "errorPopup", kind: "Ares.ErrorPopup"}
	],
	published: {
		services: []
	},
	create: function() {
		this.inherited(arguments);
		if (!ServiceRegistry.instance) {
			ServiceRegistry.instance = this;
			this.reloadServices();
		}
	},
	listServices: function(inType) {
		if (this.services.length === 0) {
			this.reloadServices();
		} else {
			this.notifyServicesChange();
		}
	},
	serviceFailure: function(serviceType, serviceId) {
		this.error("type="+ serviceType + ", id=" + serviceId);
		this.reloadServices();
	},
	reloadServices: function() {
		var self = this;
		this._reloadServices(function(err) {
			if (err) {
					self._handleReloadError(err);
			} else {
					self.notifyServicesChange();
			}
		});
	},
	/**
	 * @private
	 */
	_reloadServices: function(next) {
		if (this.debug) this.log("Refreshing the list of available services");
		var origin = window.location.origin || window.location.protocol + "//" + window.location.host; // Webkit/FF vs IE
		var url = origin + '/res/services';
		this.services = [];

		/* built-in services */

		// http://www.html5rocks.com/en/tutorials/file/filesystem/
		if (null /*window.requestFileSystem*/) {
			this.services.push({
				type: "filesystem",
				provider: "browser",
				name: "Browser Local Storage",
				icon: "server",
				moniker: "Browser Local Storage"
			});
		}

		/* Hermes Services (reload from the IDE server) */
		if (origin.match('^http')) {
			var req = new enyo.Ajax({url: url, handleAs: 'json'})
				.response(this, function(inSender, inValue) {
					var configs, self = this;
					if (inValue) {
						if (inValue.services && inValue.services[0]) {
							// dis-regard inactive service providers
							configs = inValue.services.filter(function(config){
								return config.active;
							});
							enyo.forEach(configs, function(config){
								this.services.push({
									config: config
								});
							}, this);
							this.complete(next);
						}
					} else {
						next(new Error("Empty response from Ares IDE Server"));
					}
					if (this.debug) this.log(this.services);
				})
				.error(this, function(err){
					next(err);
				})
				.go();
		}

	},
	/**
	 * Complete services configuration using localStorage
	 *
	 * Complement services loaded from the server with per-service
	 * data in the browser localStorage (for example the 'auth'
	 * property).  The completion vallbaclk is invoked once every
	 * configured services are completed.
	 *
	 * @param {Function} next a CommonJS callback
	 * @private
	 */
	complete: function(next) {
		var self = this,
		    tasks = enyo.map(this.services, function(service){
			return function(cb) {
				var key = [self.SERVICES_STORAGE_KEY, service.config.id].join('.');
				if (self.debug) self.log("localStorage[" + key + "]...");
			Ares.LocalStorage.get(key, function(str) {
					if (self.debug) self.log("localStorage[" + key + "] = ", str);
				var obj;
				try {
					obj = JSON.parse(str);
				} catch(e) {
					obj = {};
				}
				ares.extend(service.config, obj);
					self.instanciate(service, cb);
				});
			};
		});
		async.parallel(tasks, next);
	},
	instanciate: function(service, next) {
		if (this.debug) this.log("id:", service.config.id, "config:", service.config);
		try {
			if (service.config.type === "filesystem" && service.config.provider === "hermes") {
				// hermes type of services use
				// a common front-end
				service.impl = new HermesFileSystem();
				service.impl.notifyFailure = enyo.bind(this, this.serviceFailure, service.config.type, service.config.id);
			} else if (service.config.type === "build" && service.config.provider === "hermes" && service.config.id === "phonegap") {
				service.impl = new PhonegapBuild();
			}
			if (this.debug) this.log("id:", service.config.id, "created");
			// If the service does not define an
			// 'authorize()' entry point (which optionally
			// returns user acccount information), stub it
			// using a Common-JS pass-through.
			if (service.impl && !service.impl.authorize) {
				if (this.debug) this.log("Adding " + service.config.id + "#authorize() stub");
				service.impl.authorize = enyo.bind(service.impl, function(next) {
					console.log('authorize(): stubbed');
					if (this.debug) this.log('authorize(): stubbed');
					next(null, {});
				});
			}
			service.impl.setConfig(service.config);
			if (this.debug) this.log("id:", service.config.id, "configured");
			next();
		} catch(err) {
			this.error(err);
			next(err);
		}
	},
	/**
	 * @private
	 */
	SERVICES_STORAGE_KEY: "com.enyojs.ares.services",
	/**
	 * Set the given value in the given serviceId configuration
	 *
	 * Update the living instances & save the modified
	 * configuration in the localStorage, if applicable.
	 *
	 * Today, only auth part of the given config object is saved
	 * to localStorage.
	 * @param {String} inServiceId
	 * @param {Object} inConfig
	 * @param {Function} inCallback a CommonJS callback
	 */
	setConfig: function (inServiceId, inConfig, inCallback) {
		if (this.debug) this.log("serviceId:", inServiceId, "config:", inConfig);
		var service = this.resolveServiceId(inServiceId);
		if (!service) return;	// should we rather fail here?
		ares.extend(service.config, inConfig);
		service.setConfig(service.config);

		var key = [this.SERVICES_STORAGE_KEY, service.config.id].join('.');
		Ares.LocalStorage.set(key, JSON.stringify({auth: service.config.auth}), inCallback);
	},
	/**
	 * @param {String} serviceId
	 * @return {Object} service associated with the given serviceId
	 * @public
	 * @deprecated
	 * @see ServiceRegistry#filter
	 */
	resolveServiceId: function(serviceId) {
		var services = this.filter({properties: ['id'], id: serviceId});
		return services && services[0];
	},
	/**
	 * Give services whose type matches the given one
	 *
	 * If type is not provided or falsy, this method returns every
	 * registered & active services.
	 *
	 * @param {String} type one of ['filesystem', 'build', undefined]
	 * @return {Array} services matching the required type
	 * @public
	 * @deprecated
	 * @see ServiceRegistry#filter
	 */
	getServicesByType: function(type) {
		return this.filter({properties: ['type'], type: type});
	},
	/**
	 * Get {Array} or service matching the given criteria
	 * @param {Object} criterai
	 * @return {Array} services matching the required criteria
	 * @public
	 */
	filter: function(criteria) {
		//if (this.debug) this.log("criteria:", criteria, ", services:", this.services);
		var matches = enyo.filter(this.services, function(service){
			var match = true;
			if (criteria &&
			    criteria.properties &&
			    criteria.properties.length &&
			    criteria.properties[0]) {
				enyo.forEach(criteria.properties, function(prop) {
					if (criteria[prop]) {
						// filter on criteria property value
						match = match && (service.config[prop] === criteria[prop]);
					} else {
						// filter on criteria property presence
						match = match && (service.config[prop] !== undefined);
					}
				}, this);
			}
			//if (this.debug) this.log("match:", match, "<= service:", service.config);
			return match;
		}, this);
		var services = [];
		//if (this.debug) this.log("matches:", matches);
		enyo.forEach(matches, function(match){
			if (match.impl) {
			services.push(match.impl);
			}
		}, this);
		if (this.debug) this.log("criteria:", criteria , " => services:", services);
		return services;
	},
	//* @private
	_handleReloadError: function(err) {
		this.$.errorPopup.setErrorMsg("Ares IDE Server returned an error");
		this.$.errorPopup.show();
		this.error("Error: "+JSON.stringify(err));
	},
	/**
	 * Notify every possible users of a change in the list of providers
	 *
	 * For example, there might be many instances of the
	 * {ProvidersList} control (widget) in the application.
	 *
	 * @private
	 */
	notifyServicesChange: function() {
		if (this.debug) this.log("sending signal...");
		enyo.Signals.send("onServicesChange", {serviceRegistry: this});
	},
	statics: {
		instance: null
	}
});
<commit_msg>ENYO-1712: cleanup ServiceRegistry (indentation)<commit_after>enyo.kind({
	name: "ServiceRegistry",
	debug: false,
	kind: enyo.Component,
	events: {
		onServicesChange: ""
	},
	components: [
		{name: "errorPopup", kind: "Ares.ErrorPopup"}
	],
	published: {
		services: []
	},
	create: function() {
		this.inherited(arguments);
		if (!ServiceRegistry.instance) {
			ServiceRegistry.instance = this;
			this.reloadServices();
		}
	},
	listServices: function(inType) {
		if (this.services.length === 0) {
			this.reloadServices();
		} else {
			this.notifyServicesChange();
		}
	},
	serviceFailure: function(serviceType, serviceId) {
		this.error("type="+ serviceType + ", id=" + serviceId);
		this.reloadServices();
	},
	reloadServices: function() {
		var self = this;
		this._reloadServices(function(err) {
			if (err) {
					self._handleReloadError(err);
			} else {
					self.notifyServicesChange();
			}
		});
	},
	/**
	 * @private
	 */
	_reloadServices: function(next) {
		if (this.debug) this.log("Refreshing the list of available services");
		var origin = window.location.origin || window.location.protocol + "//" + window.location.host; // Webkit/FF vs IE
		var url = origin + '/res/services';
		this.services = [];

		/* built-in services */

		// http://www.html5rocks.com/en/tutorials/file/filesystem/
		if (null /*window.requestFileSystem*/) {
			this.services.push({
				type: "filesystem",
				provider: "browser",
				name: "Browser Local Storage",
				icon: "server",
				moniker: "Browser Local Storage"
			});
		}

		/* Hermes Services (reload from the IDE server) */
		if (origin.match('^http')) {
			var req = new enyo.Ajax({url: url, handleAs: 'json'})
				.response(this, function(inSender, inValue) {
					var configs, self = this;
					if (inValue) {
						if (inValue.services && inValue.services[0]) {
							// dis-regard inactive service providers
							configs = inValue.services.filter(function(config){
								return config.active;
							});
							enyo.forEach(configs, function(config){
								this.services.push({
									config: config
								});
							}, this);
							this.complete(next);
						}
					} else {
						next(new Error("Empty response from Ares IDE Server"));
					}
					if (this.debug) this.log(this.services);
				})
				.error(this, function(err){
					next(err);
				})
				.go();
		}

	},
	/**
	 * Complete services configuration using localStorage
	 *
	 * Complement services loaded from the server with per-service
	 * data in the browser localStorage (for example the 'auth'
	 * property).  The completion vallbaclk is invoked once every
	 * configured services are completed.
	 *
	 * @param {Function} next a CommonJS callback
	 * @private
	 */
	complete: function(next) {
		var self = this,
		    tasks = enyo.map(this.services, function(service){
			return function(cb) {
				var key = [self.SERVICES_STORAGE_KEY, service.config.id].join('.');
				if (self.debug) self.log("localStorage[" + key + "]...");
				Ares.LocalStorage.get(key, function(str) {
					if (self.debug) self.log("localStorage[" + key + "] = ", str);
					var obj;
					try {
						obj = JSON.parse(str);
					} catch(e) {
						obj = {};
					}
					ares.extend(service.config, obj);
					self.instanciate(service, cb);
				});
			};
		});
		async.parallel(tasks, next);
	},
	instanciate: function(service, next) {
		if (this.debug) this.log("id:", service.config.id, "config:", service.config);
		try {
			if (service.config.type === "filesystem" && service.config.provider === "hermes") {
				// hermes type of services use
				// a common front-end
				service.impl = new HermesFileSystem();
				service.impl.notifyFailure = enyo.bind(this, this.serviceFailure, service.config.type, service.config.id);
			} else if (service.config.type === "build" && service.config.provider === "hermes" && service.config.id === "phonegap") {
				service.impl = new PhonegapBuild();
			}
			if (this.debug) this.log("id:", service.config.id, "created");
			// If the service does not define an
			// 'authorize()' entry point (which optionally
			// returns user acccount information), stub it
			// using a Common-JS pass-through.
			if (service.impl && !service.impl.authorize) {
				if (this.debug) this.log("Adding " + service.config.id + "#authorize() stub");
				service.impl.authorize = enyo.bind(service.impl, function(next) {
					console.log('authorize(): stubbed');
					if (this.debug) this.log('authorize(): stubbed');
					next(null, {});
				});
			}
			service.impl.setConfig(service.config);
			if (this.debug) this.log("id:", service.config.id, "configured");
			next();
		} catch(err) {
			this.error(err);
			next(err);
		}
	},
	/**
	 * @private
	 */
	SERVICES_STORAGE_KEY: "com.enyojs.ares.services",
	/**
	 * Set the given value in the given serviceId configuration
	 *
	 * Update the living instances & save the modified
	 * configuration in the localStorage, if applicable.
	 *
	 * Today, only auth part of the given config object is saved
	 * to localStorage.
	 * @param {String} inServiceId
	 * @param {Object} inConfig
	 * @param {Function} inCallback a CommonJS callback
	 */
	setConfig: function (inServiceId, inConfig, inCallback) {
		if (this.debug) this.log("serviceId:", inServiceId, "config:", inConfig);
		var service = this.resolveServiceId(inServiceId);
		if (!service) return;	// should we rather fail here?
		ares.extend(service.config, inConfig);
		service.setConfig(service.config);

		var key = [this.SERVICES_STORAGE_KEY, service.config.id].join('.');
		Ares.LocalStorage.set(key, JSON.stringify({auth: service.config.auth}), inCallback);
	},
	/**
	 * @param {String} serviceId
	 * @return {Object} service associated with the given serviceId
	 * @public
	 * @deprecated
	 * @see ServiceRegistry#filter
	 */
	resolveServiceId: function(serviceId) {
		var services = this.filter({properties: ['id'], id: serviceId});
		return services && services[0];
	},
	/**
	 * Give services whose type matches the given one
	 *
	 * If type is not provided or falsy, this method returns every
	 * registered & active services.
	 *
	 * @param {String} type one of ['filesystem', 'build', undefined]
	 * @return {Array} services matching the required type
	 * @public
	 * @deprecated
	 * @see ServiceRegistry#filter
	 */
	getServicesByType: function(type) {
		return this.filter({properties: ['type'], type: type});
	},
	/**
	 * Get {Array} or service matching the given criteria
	 * @param {Object} criterai
	 * @return {Array} services matching the required criteria
	 * @public
	 */
	filter: function(criteria) {
		//if (this.debug) this.log("criteria:", criteria, ", services:", this.services);
		var matches = enyo.filter(this.services, function(service){
			var match = true;
			if (criteria &&
			    criteria.properties &&
			    criteria.properties.length &&
			    criteria.properties[0]) {
				enyo.forEach(criteria.properties, function(prop) {
					if (criteria[prop]) {
						// filter on criteria property value
						match = match && (service.config[prop] === criteria[prop]);
					} else {
						// filter on criteria property presence
						match = match && (service.config[prop] !== undefined);
					}
				}, this);
			}
			//if (this.debug) this.log("match:", match, "<= service:", service.config);
			return match;
		}, this);
		var services = [];
		//if (this.debug) this.log("matches:", matches);
		enyo.forEach(matches, function(match){
			if (match.impl) {
				services.push(match.impl);
			}
		}, this);
		if (this.debug) this.log("criteria:", criteria , " => services:", services);
		return services;
	},
	//* @private
	_handleReloadError: function(err) {
		this.$.errorPopup.setErrorMsg("Ares IDE Server returned an error");
		this.$.errorPopup.show();
		this.error("Error: "+JSON.stringify(err));
	},
	/**
	 * Notify every possible users of a change in the list of providers
	 *
	 * For example, there might be many instances of the
	 * {ProvidersList} control (widget) in the application.
	 *
	 * @private
	 */
	notifyServicesChange: function() {
		if (this.debug) this.log("sending signal...");
		enyo.Signals.send("onServicesChange", {serviceRegistry: this});
	},
	statics: {
		instance: null
	}
});
<|endoftext|>


<commit_before>(function (env) {
    "use strict";
    env.ddg_spice_vrc_teams = function(team_data) {
        if (!team_data || team_data.status !== 1 || team_data.size === 0 || team_data.result[0].is_registered === "0") {
            return Spice.failed('vrc_teams');
        }

        //infobox data for statistics
        function infobox(ranking, skills){
            var l = []
            if (ranking.status === 1 && ranking.size > 0){
                l.push({heading: 'Qualifying Matches'});
                var total_wins = 0,
                    total_losses = 0,
                    total_ties = 0,
                    total_ccwm = 0.0,
                    max_score = 0,
                    latest = ranking.result[0];

                $.each(ranking.result, function(ind, i){
                    total_wins += parseInt(i.wins);
                    total_losses += parseInt(i.losses);
                    total_ties += parseInt(i.ties);
                    total_ccwm += parseFloat(i.ccwm);
                    max_score = Math.max(max_score, parseInt(i.max_score));
                });

                var total_wlt = total_wins + '-' + total_losses + '-' + total_ties;
                var latest_wlt = latest.wins + '-' + latest.losses + '-' + latest.ties;
                l.push({label: 'Total W-L-T', value: total_wlt});
                l.push({label: 'Latest W-L-T', value: latest_wlt});
                l.push({label: 'Greatest Match Score', value: max_score});

                var average_ccwm = total_ccwm / ranking.size;
                l.push({label: 'Average CCWM', value: average_ccwm.toFixed(2)});
                l.push({label: 'Latest CCWM', value: parseFloat(latest.ccwm).toFixed(2)});
            }
            if (skills.status === 1 && skills.size > 0){
                l.push({heading: 'Best Skills'});
                var best_robot = 0,
                    best_programming = 0;

                $.each(skills.result, function(ind, i){
                    if (i.type === "0" && parseInt(i.score) > best_robot){
                        best_robot = parseInt(i.score);
                    }
                    if (i.type === "1" && parseInt(i.score) > best_programming){
                        best_programming = parseInt(i.score);
                    }
                });

                l.push({label: 'Robot', value: best_robot});
                l.push({label: 'Programming', value: best_programming});
            }

            return l.length ? l : undefined;
        }

        //description data for team location and grade
        function description(team){
            return team.grade + ' team from ' + team.city + ', ' + team.region + ', ' + team.country;
        }

        var team = team_data.result[0], ranking_data, skills_data;

        //the api splits the data up into multiple endpoints, fire them simultaneously
        $.when(
            $.getJSON('/js/spice/vrc/rankings/' + team.number, function(res){
                ranking_data = res;
            }),
            $.getJSON('/js/spice/vrc/skills/' + team.number, function(res){
                skills_data = res;
            })
        ).then(function(){
            Spice.add({
                id: "vrc_teams",
                name: "VRC Team",
                data: team,
                meta: {
                    sourceName: "VexDB.io",
                    sourceUrl: 'http://vexdb.io/teams/view/' + team.number
                },
                normalize: function(item) {
                    return {
                        title: item.team_name,
                        subtitle: item.program + ' Team ' + item.number + ' — ' + item.organisation,
                        description: description(item),
                        infoboxData: infobox(ranking_data, skills_data)
                    };
                },
                templates: {
                    group: 'info',
                    options: {
                        moreAt: true
                    }
                }
            });
        }, function(){
            //one of these requests failed
            Spice.failed('vrc_teams');
        });
    };
}(this));
<commit_msg>VRCTeams: skip registration check<commit_after>(function (env) {
    "use strict";
    env.ddg_spice_vrc_teams = function(team_data) {
        if (!team_data || team_data.status !== 1 || team_data.size === 0) {
            return Spice.failed('vrc_teams');
        }

        //infobox data for statistics
        function infobox(ranking, skills){
            var l = []
            if (ranking.status === 1 && ranking.size > 0){
                l.push({heading: 'Qualifying Matches'});
                var total_wins = 0,
                    total_losses = 0,
                    total_ties = 0,
                    total_ccwm = 0.0,
                    max_score = 0,
                    latest = ranking.result[0];

                $.each(ranking.result, function(ind, i){
                    total_wins += parseInt(i.wins);
                    total_losses += parseInt(i.losses);
                    total_ties += parseInt(i.ties);
                    total_ccwm += parseFloat(i.ccwm);
                    max_score = Math.max(max_score, parseInt(i.max_score));
                });

                var total_wlt = total_wins + '-' + total_losses + '-' + total_ties;
                var latest_wlt = latest.wins + '-' + latest.losses + '-' + latest.ties;
                l.push({label: 'Total W-L-T', value: total_wlt});
                l.push({label: 'Latest W-L-T', value: latest_wlt});
                l.push({label: 'Greatest Match Score', value: max_score});

                var average_ccwm = total_ccwm / ranking.size;
                l.push({label: 'Average CCWM', value: average_ccwm.toFixed(2)});
                l.push({label: 'Latest CCWM', value: parseFloat(latest.ccwm).toFixed(2)});
            }
            if (skills.status === 1 && skills.size > 0){
                l.push({heading: 'Best Skills'});
                var best_robot = 0,
                    best_programming = 0;

                $.each(skills.result, function(ind, i){
                    if (i.type === "0" && parseInt(i.score) > best_robot){
                        best_robot = parseInt(i.score);
                    }
                    if (i.type === "1" && parseInt(i.score) > best_programming){
                        best_programming = parseInt(i.score);
                    }
                });

                l.push({label: 'Robot', value: best_robot});
                l.push({label: 'Programming', value: best_programming});
            }

            return l.length ? l : undefined;
        }

        //description data for team location and grade
        function description(team){
            return team.grade + ' team from ' + team.city + ', ' + team.region + ', ' + team.country;
        }

        var team = team_data.result[0], ranking_data, skills_data;

        //the api splits the data up into multiple endpoints, fire them simultaneously
        $.when(
            $.getJSON('/js/spice/vrc/rankings/' + team.number, function(res){
                ranking_data = res;
            }),
            $.getJSON('/js/spice/vrc/skills/' + team.number, function(res){
                skills_data = res;
            })
        ).then(function(){
            Spice.add({
                id: "vrc_teams",
                name: "VRC Team",
                data: team,
                meta: {
                    sourceName: "VexDB.io",
                    sourceUrl: 'http://vexdb.io/teams/view/' + team.number
                },
                normalize: function(item) {
                    return {
                        title: item.team_name,
                        subtitle: item.program + ' Team ' + item.number + ' — ' + item.organisation,
                        description: description(item),
                        infoboxData: infobox(ranking_data, skills_data)
                    };
                },
                templates: {
                    group: 'info',
                    options: {
                        moreAt: true
                    }
                }
            });
        }, function(){
            //one of these requests failed
            Spice.failed('vrc_teams');
        });
    };
}(this));
<|endoftext|>


<commit_before>// 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.

couchTests.bulk_docs = function(debug) {
  var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"});
  db.deleteDb();
  db.createDb();
  if (debug) debugger;

  var docs = makeDocs(5);

  // Create the docs
  var results = db.bulkSave(docs);

  T(results.length == 5);
  for (var i = 0; i < 5; i++) {
    T(results[i].id == docs[i]._id);
    T(results[i].rev);
    // Update the doc
    docs[i].string = docs[i].string + ".00";
  }

  // Save the docs
  results = db.bulkSave(docs);
  T(results.length == 5);
  for (i = 0; i < 5; i++) {
    T(results[i].id == i.toString());

    // set the delete flag to delete the docs in the next step
    docs[i]._deleted = true;
  }

  // now test a bulk update with a conflict
  // open and save
  var doc = db.open("0");
  db.save(doc);

  // Now bulk delete the docs
  results = db.bulkSave(docs);

  // doc "0" should be a conflict
  T(results.length == 5);
  T(results[0].id == "0");
  T(results[0].error == "conflict");
  T(results[0].rev === undefined); // no rev member when a conflict

  // but the rest are not
  for (i = 1; i < 5; i++) {
    T(results[i].id == i.toString());
    T(results[i].rev)
    T(db.open(docs[i]._id) == null);
  }

  // now force a conflict to to save

  // save doc 0, this will cause a conflict when we save docs[0]
  var doc = db.open("0");
  docs[0] = db.open("0");
  db.save(doc);

  docs[0].shooby = "dooby";

  // Now save the bulk docs, When we use all_or_nothing, we don't get conflict
  // checking, all docs are saved regardless of conflict status, or none are
  // saved.
  results = db.bulkSave(docs,{all_or_nothing:true});
  T(results.error === undefined);

  var doc = db.open("0", {conflicts:true});
  var docConflict = db.open("0", {rev:doc._conflicts[0]});

  T(doc.shooby == "dooby" || docConflict.shooby == "dooby");

  // verify creating a document with no id returns a new id
  var req = CouchDB.request("POST", "/test_suite_db/_bulk_docs", {
    body: JSON.stringify({"docs": [{"foo":"bar"}]})
  });
  results = JSON.parse(req.responseText);

  T(results[0].id != "");
  T(results[0].rev != "");

  // Regression test for failure on update/delete
  var newdoc = {"_id": "foobar", "body": "baz"};
  T(db.save(newdoc).ok);
  update = {"_id": newdoc._id, "_rev": newdoc._rev, "body": "blam"};
  torem = {"_id": newdoc._id, "_rev": newdoc._rev, "_deleted": true};
  results = db.bulkSave([update, torem]);
  T(results[0].error == "conflict" || results[1].error == "conflict");
};
<commit_msg>Fix bad JavaScript practices and avoid declaration of 2 global variables.<commit_after>// 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.

couchTests.bulk_docs = function(debug) {
  var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"});
  db.deleteDb();
  db.createDb();
  if (debug) debugger;

  var docs = makeDocs(5);

  // Create the docs
  var results = db.bulkSave(docs);

  T(results.length == 5);
  for (var i = 0; i < 5; i++) {
    T(results[i].id == docs[i]._id);
    T(results[i].rev);
    // Update the doc
    docs[i].string = docs[i].string + ".00";
  }

  // Save the docs
  results = db.bulkSave(docs);
  T(results.length == 5);
  for (i = 0; i < 5; i++) {
    T(results[i].id == i.toString());

    // set the delete flag to delete the docs in the next step
    docs[i]._deleted = true;
  }

  // now test a bulk update with a conflict
  // open and save
  var doc = db.open("0");
  db.save(doc);

  // Now bulk delete the docs
  results = db.bulkSave(docs);

  // doc "0" should be a conflict
  T(results.length == 5);
  T(results[0].id == "0");
  T(results[0].error == "conflict");
  T(typeof results[0].rev === "undefined"); // no rev member when a conflict

  // but the rest are not
  for (i = 1; i < 5; i++) {
    T(results[i].id == i.toString());
    T(results[i].rev);
    T(db.open(docs[i]._id) == null);
  }

  // now force a conflict to to save

  // save doc 0, this will cause a conflict when we save docs[0]
  var doc = db.open("0");
  docs[0] = db.open("0");
  db.save(doc);

  docs[0].shooby = "dooby";

  // Now save the bulk docs, When we use all_or_nothing, we don't get conflict
  // checking, all docs are saved regardless of conflict status, or none are
  // saved.
  results = db.bulkSave(docs,{all_or_nothing:true});
  T(results.error === undefined);

  var doc = db.open("0", {conflicts:true});
  var docConflict = db.open("0", {rev:doc._conflicts[0]});

  T(doc.shooby == "dooby" || docConflict.shooby == "dooby");

  // verify creating a document with no id returns a new id
  var req = CouchDB.request("POST", "/test_suite_db/_bulk_docs", {
    body: JSON.stringify({"docs": [{"foo":"bar"}]})
  });
  results = JSON.parse(req.responseText);

  T(results[0].id != "");
  T(results[0].rev != "");

  // Regression test for failure on update/delete
  var newdoc = {"_id": "foobar", "body": "baz"};
  T(db.save(newdoc).ok);
  var update = {"_id": newdoc._id, "_rev": newdoc._rev, "body": "blam"};
  var torem = {"_id": newdoc._id, "_rev": newdoc._rev, "_deleted": true};
  results = db.bulkSave([update, torem]);
  T(results[0].error == "conflict" || results[1].error == "conflict");
};
<|endoftext|>


<commit_before>var win = Titanium.UI.currentWindow;

var annotation = Titanium.Map.createAnnotation({
	latitude:42.334537,
	longitude:-71.170101,
	title:"Boston College",
	subtitle:'Newton Campus, Chestnut Hill, MA',
	animate:true,
	image:"../images/boston_college.png"
});

var boston = {latitude:42.334537,longitude:-71.170101,latitudeDelta:0.010, longitudeDelta:0.018};

//
// CREATE MAP VIEW
//
var mapview = Titanium.Map.createView({
	mapType: Titanium.Map.STANDARD_TYPE,
	region: boston,
	animate:true,
	regionFit:true,
	userLocation:true,
	annotations:[annotation]
});

// read in our routes from a comma-separated file
var f = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'examples','route.csv');
var csv = f.read();
var points = [];
var lines = csv.toString().split("\n");
for (var c=0;c<lines.length;c++)
{
	var line = lines[c];
	var latlong = line.split(",");
	if (latlong.length > 1)
	{
		var lat = latlong[0];
		var lon = latlong[1];
		var entry = {latitude:lat,longitude:lon};
		points[c]=entry;
	}
}

// route object
var route = {
	name:"boston",
	points:points,
	color:"red",
	width:4
};

// add a route
mapview.addRoute(route);

win.add(mapview);

// when you click the logo, remove the route
annotation.addEventListener('click',function()
{
	mapview.removeRoute(route);
});
<commit_msg>test change<commit_after>var win = Titanium.UI.currentWindow;

var annotation = Titanium.Map.createAnnotation({
	latitude:42.334537,
	longitude:-71.170101,
	title:"Boston College",
	subtitle:'Newton Campus, Chestnut Hill, MA',
	animate:true,
	leftButton:'../images/atlanta.jpg',
	image:"../images/boston_college.png"
});

var boston = {latitude:42.334537,longitude:-71.170101,latitudeDelta:0.010, longitudeDelta:0.018};

//
// CREATE MAP VIEW
//
var mapview = Titanium.Map.createView({
	mapType: Titanium.Map.STANDARD_TYPE,
	region: boston,
	animate:true,
	regionFit:true,
	userLocation:true,
	annotations:[annotation]
});

// read in our routes from a comma-separated file
var f = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'examples','route.csv');
var csv = f.read();
var points = [];
var lines = csv.toString().split("\n");
for (var c=0;c<lines.length;c++)
{
	var line = lines[c];
	var latlong = line.split(",");
	if (latlong.length > 1)
	{
		var lat = latlong[0];
		var lon = latlong[1];
		var entry = {latitude:lat,longitude:lon};
		points[c]=entry;
	}
}

// route object
var route = {
	name:"boston",
	points:points,
	color:"red",
	width:4
};

// add a route
mapview.addRoute(route);

win.add(mapview);

// when you click the logo, remove the route
annotation.addEventListener('click',function()
{
	mapview.removeRoute(route);
});

// map view click event listener
mapview.addEventListener('click',function(evt)
{
	var clickSource = evt.clicksource;
	Ti.API.info('mapview click clicksource = ' + clickSource)
});<|endoftext|>


<commit_before>let Promise = require('bluebird')

let model = require('../connect')

let upload = function (id, table, path, field) {
  return new Promise((resolve, reject) => {
    model.knex(table + id).del().then(() => {
      let query = 'ALTER TABLE ' + table + id + ' AUTO_INCREMENT = 1'
      return model.knex.raw(query)
    }).then(() => {
      let query = "LOAD DATA LOCAL INFILE '" + path + "' INTO TABLE "  + table + id +
      " TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 ROWS (" + field + ")"
      return model.knex.raw(query)
    }).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject()
    })
  })
}

module.exports = {
  upload: upload
}<commit_msg>fix some bugs<commit_after>let Promise = require('bluebird')

let model = require('../connect')

let upload = function (id, table, path, field) {
  return new Promise((resolve, reject) => {
    model.knex(table + id).del().then(() => {
      let query = 'ALTER TABLE ' + table + id + ' AUTO_INCREMENT = 1'
      return model.knex.raw(query)
    }).then(() => {
      let query = "LOAD DATA LOCAL INFILE '" + path + "' INTO TABLE "  + table + id +
      " TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES (" + field + ")"
      return model.knex.raw(query)
    }).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject()
    })
  })
}

module.exports = {
  upload: upload
}<|endoftext|>


<commit_before>/* eslint no-console: 0 */
/* eslint no-confusing-arrow: 0 */
const ran = false; // set to true to exclude migration
const name = 'Fix access rights for teachers on homework submitted files.';

const mongoose = require('mongoose');

const { submissionModel } = require('../src/services/homework/model.js');
const { FileModel } = require('../src/services/fileStorage/model.js');

mongoose.Promise = global.Promise;

const run = async (dry) => {
	mongoose.connect(process.env.DB_URL || 'mongodb://localhost:27017/schulcloud', { user: process.env.DB_USERNAME, pass: process.env.DB_PASSWORD });

	const errorHandler = (e) => {
		console.log('Error', e);
		return undefined;
	};

	const submissionWithFiles = await submissionModel
		.find({ fileIds: { $exists: true, $not: { $size: 0 } } })
		.populate('homeworkId')
		.populate('fileIds')
		.exec()
		.catch(errorHandler);

	if (!submissionWithFiles.length) {
		return Promise.resolve();
	}

	const promises = submissionWithFiles
		.map((sub) => {
			const { teacherId } = sub.homeworkId || {};

			if (!teacherId) {
				return Promise.resolve();
			}

			const buggyFiles = sub.fileIds
				.filter(file => !file.permissions
					.find(perm => perm.refId.toString() === teacherId.toString()));

			if (!buggyFiles.length) {
				return Promise.resolve();
			}

			console.log('Update permissions of files:');
			console.log(buggyFiles.map(file => file._id));
			console.log(`with access rights for teacher: ${teacherId}`);

			const filePromises = buggyFiles.map(file => dry
				? Promise.resolve()
				: FileModel.update({ _id: file._id }, {
					$set: {
						permissions: [...file.permissions, {
							refId: teacherId,
							refPermModel: 'user',
							write: false,
							read: true,
							create: false,
							delete: false,
						}],
					},
				}).exec().catch(errorHandler));

			return Promise.all(filePromises);
		});

	return Promise.all(promises);
};

module.exports = {
	ran,
	name,
	run,
};
<commit_msg>Check if refId exists<commit_after>/* eslint no-console: 0 */
/* eslint no-confusing-arrow: 0 */
const ran = false; // set to true to exclude migration
const name = 'Fix access rights for teachers on homework submitted files.';

const mongoose = require('mongoose');

const { submissionModel } = require('../src/services/homework/model.js');
const { FileModel } = require('../src/services/fileStorage/model.js');

mongoose.Promise = global.Promise;

const run = async (dry) => {
	mongoose.connect(process.env.DB_URL || 'mongodb://localhost:27017/schulcloud', { user: process.env.DB_USERNAME, pass: process.env.DB_PASSWORD });

	const errorHandler = (e) => {
		console.log('Error', e);
		return undefined;
	};

	const submissionWithFiles = await submissionModel
		.find({ fileIds: { $exists: true, $not: { $size: 0 } } })
		.populate('homeworkId')
		.populate('fileIds')
		.exec()
		.catch(errorHandler);

	if (!submissionWithFiles.length) {
		return Promise.resolve();
	}

	const promises = submissionWithFiles
		.map((sub) => {
			const { teacherId } = sub.homeworkId || {};

			if (!teacherId) {
				return Promise.resolve();
			}

			const buggyFiles = sub.fileIds
				.filter(file => !file.permissions
					.find(perm => perm.refId && perm.refId.toString() === teacherId.toString()));

			if (!buggyFiles.length) {
				return Promise.resolve();
			}

			console.log('Update permissions of files:');
			console.log(buggyFiles.map(file => file._id));
			console.log(`with access rights for teacher: ${teacherId}`);

			const filePromises = buggyFiles.map(file => dry
				? Promise.resolve()
				: FileModel.update({ _id: file._id }, {
					$set: {
						permissions: [...file.permissions, {
							refId: teacherId,
							refPermModel: 'user',
							write: false,
							read: true,
							create: false,
							delete: false,
						}],
					},
				}).exec().catch(errorHandler));

			return Promise.all(filePromises);
		});

	return Promise.all(promises);
};

module.exports = {
	ran,
	name,
	run,
};
<|endoftext|>


<commit_before>var input    = require('./digits.js');
var exercise = {};

exercise.one = function(){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 1st function not implementeded';
};

exercise.two = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 2nd function not implemented';
};

exercise.three = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 3rd function not implemented';
};

exercise.four = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 4th function not implemented';
};

exercise.five = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 5th function not implemented';
};

module.exports = exercise;
<commit_msg>Update exercise.js<commit_after>var input    = require('./digits.js');
var exercise = {};

exercise.one = function(){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 1st function not implemented';
};

exercise.two = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 2nd function not implemented';
};

exercise.three = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 3rd function not implemented';
};

exercise.four = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 4th function not implemented';
};

exercise.five = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 5th function not implemented';
};

module.exports = exercise;
<|endoftext|>