<commit_before>
var access_token = "";

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
  console.log('statusChangeCallback');
  console.log(response);
  // The response object is returned with a status field that lets the
  // app know the current login status of the person.
  // Full docs on the response object can be found in the documentation
  // for FB.getLoginStatus().
  if (response.status === 'connected') {
    // Logged into your app and Facebook.
    alert(response.authResponse.accessToken);
    access_token = response.authResponse.accessToken;
    testAPI();
  } else if (response.status === 'not_authorized') {
    // The person is logged into Facebook, but not your app.
    document.getElementById('status').innerHTML = 'Please log ' +
      'into this app.';
  } else {
    // The person is not logged into Facebook, so we're not sure if
    // they are logged into this app or not.
    document.getElementById('status').innerHTML = 'Please log ' +
      'into Facebook.';
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus().  This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide.  They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
//    your app or not.
//
// These three cases are handled in the callback function.

// Here we run a very simple test of the Graph API after login is
// successful.  See statusChangeCallback() for when this call is made.
function testAPI() {
  FB.api('/me?field=name,id', function(response) {
    alert('Successful login for: ' + response.name);
  });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  alert(access_token);

  $.ajax({
    type: "POST",
    crossDomain: true,
    jsonp: false,
    jsonpCallback: "succ"
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    url: "http://127.0.0.1:8000/project-director/facebook",
    data: JSON.stringify(myObject),
    success: function(data)
    {
      var obj = jQuery.parseJSON(data);
      alert(obj.id);
      alert(obj.fist_name);
      alert(obj.image_url);
      // $('body').append(data);
      // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
      //   $('#form-send-message').addClass('form-send-errors')
      // }
      // else {
      //   $('#form-send-message').addClass('form-send-success');
      // }
    }//,
    // error: function(error) {
    //   alert(error);
    // }
  });

}

function succ(data) {
  var obj = jQuery.parseJSON(data);
      alert(obj.id);
      alert(obj.fist_name);
      alert(obj.image_url);
}

<commit_msg>access token managment added<commit_after>
var access_token = "";

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
  console.log('statusChangeCallback');
  console.log(response);
  // The response object is returned with a status field that lets the
  // app know the current login status of the person.
  // Full docs on the response object can be found in the documentation
  // for FB.getLoginStatus().
  if (response.status === 'connected') {
    // Logged into your app and Facebook.
    alert(response.authResponse.accessToken);
    access_token = response.authResponse.accessToken;
    testAPI();
  } else if (response.status === 'not_authorized') {
    // The person is logged into Facebook, but not your app.
    document.getElementById('status').innerHTML = 'Please log ' +
      'into this app.';
  } else {
    // The person is not logged into Facebook, so we're not sure if
    // they are logged into this app or not.
    document.getElementById('status').innerHTML = 'Please log ' +
      'into Facebook.';
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus().  This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide.  They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
//    your app or not.
//
// These three cases are handled in the callback function.

// Here we run a very simple test of the Graph API after login is
// successful.  See statusChangeCallback() for when this call is made.
function testAPI() {
  FB.api('/me?field=name,id', function(response) {
    alert('Successful login for: ' + response.name);
  });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  alert(access_token);

  $.ajax({
    type: "POST",
    crossDomain: true,
    jsonp: false,
    jsonpCallback: "succ",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    url: "http://127.0.0.1:8000/project-director/facebook",
    data: JSON.stringify(myObject),
    success: function(data)
    {
      var obj = jQuery.parseJSON(data);
      alert(obj.id);
      alert(obj.fist_name);
      alert(obj.image_url);
      // $('body').append(data);
      // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
      //   $('#form-send-message').addClass('form-send-errors')
      // }
      // else {
      //   $('#form-send-message').addClass('form-send-success');
      // }
    }//,
    // error: function(error) {
    //   alert(error);
    // }
  });

}

function succ(data) {
  var obj = jQuery.parseJSON(data);
      alert(obj.id);
      alert(obj.fist_name);
      alert(obj.image_url);
}

<|endoftext|>


<commit_before>
//
// Handles the data and animation of a specific shape available to the shapeshifter.
//
pc.script.attribute('movespeed','number',1);
pc.script.attribute('attributesJSON','string','[]'');

pc.script.create('shapeinstance', function (context) {
    // Creates a new Shakeycamera instance
    var ShapeInstance = function (entity) {
        this.entity = entity;
        this.shapeshiftercomponent = null;
        this.animationthunk = null;

        this.shapename = "";
        this.isactive = false;
        this.attributes = [];
    };

    ShapeInstance.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            this.shapename = this.entity.getName();

            this.attributes = JSON.parse(this.attributesJSON);
            if (!_.isArray(this.attributes)) {
                pc.log.warning("Warning: attributesJSON does not parse into an array in object " + this.entity.name);
                pc.log.warning("JSON string: " + this.attributesJSON);
                this.attributes = [];
            }

            // should start off disabled
            this.disableShape();

            // the shapeshifter component should be in the parent node
            this.animationthunk = this.entity.script.animationthunk;
            this.shapeshiftercomponent = this.entity.getParent().script.shapeshifter;
            this.shapeshiftercomponent.addShape(this);
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            if (!this.isactive) { return; }

            var mover = this.shapeshiftercomponent.avatarmovementcomponent;
            var animator = this.animationthunk;

            // use certain available attributes
            if (this.shapeshiftercomponent.isAttributeAvailable('strong') &&
                _.contains(this.attributes, 'strong')) {
                this.shapeshiftercomponent.useAttribute('strong');
            }

            // is an attribute active? if so, we may need to modify the animation and/or
            // movement behavior
            if (this.shapeshiftercomponent.isUsingAttribute('strong')) {
                mover.movementenabled = true;
                if (mover.ismoving) {
                    animator.setDefaultAnimation('push');
                } else  {
                    animator.setDefaultAnimation('idle');
                }
            } else {
                // no active attribute
                // switch between running and idle animations as appropriate
                mover.movementenabled = true;
                if (mover.ismoving) {
                    animator.setDefaultAnimation('run');
                } else {
                    animator.setDefaultAnimation('idle');
                }
            }
        },

        setActiveFlag: function(activeflag) {
            if (activeflag) {
                this.enableShape();
            } else {
                this.disableShape();
            }
        },

        enableShape: function() {
            this.isactive = true;
            this.entity.model.setVisible(true);
        },

        disableShape: function() {
            this.isactive = false;
            this.entity.model.setVisible(false);
        }
    };

    return ShapeInstance;
});<commit_msg>Wrong quote placement<commit_after>
//
// Handles the data and animation of a specific shape available to the shapeshifter.
//
pc.script.attribute('movespeed','number',1);
pc.script.attribute('attributesJSON','string','[]');

pc.script.create('shapeinstance', function (context) {
    // Creates a new Shakeycamera instance
    var ShapeInstance = function (entity) {
        this.entity = entity;
        this.shapeshiftercomponent = null;
        this.animationthunk = null;

        this.shapename = "";
        this.isactive = false;
        this.attributes = [];
    };

    ShapeInstance.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            this.shapename = this.entity.getName();

            this.attributes = JSON.parse(this.attributesJSON);
            if (!_.isArray(this.attributes)) {
                pc.log.warning("Warning: attributesJSON does not parse into an array in object " + this.entity.name);
                pc.log.warning("JSON string: " + this.attributesJSON);
                this.attributes = [];
            }

            // should start off disabled
            this.disableShape();

            // the shapeshifter component should be in the parent node
            this.animationthunk = this.entity.script.animationthunk;
            this.shapeshiftercomponent = this.entity.getParent().script.shapeshifter;
            this.shapeshiftercomponent.addShape(this);
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            if (!this.isactive) { return; }

            var mover = this.shapeshiftercomponent.avatarmovementcomponent;
            var animator = this.animationthunk;

            // use certain available attributes
            if (this.shapeshiftercomponent.isAttributeAvailable('strong') &&
                _.contains(this.attributes, 'strong')) {
                this.shapeshiftercomponent.useAttribute('strong');
            }

            // is an attribute active? if so, we may need to modify the animation and/or
            // movement behavior
            if (this.shapeshiftercomponent.isUsingAttribute('strong')) {
                mover.movementenabled = true;
                if (mover.ismoving) {
                    animator.setDefaultAnimation('push');
                } else  {
                    animator.setDefaultAnimation('idle');
                }
            } else {
                // no active attribute
                // switch between running and idle animations as appropriate
                mover.movementenabled = true;
                if (mover.ismoving) {
                    animator.setDefaultAnimation('run');
                } else {
                    animator.setDefaultAnimation('idle');
                }
            }
        },

        setActiveFlag: function(activeflag) {
            if (activeflag) {
                this.enableShape();
            } else {
                this.disableShape();
            }
        },

        enableShape: function() {
            this.isactive = true;
            this.entity.model.setVisible(true);
        },

        disableShape: function() {
            this.isactive = false;
            this.entity.model.setVisible(false);
        }
    };

    return ShapeInstance;
});<|endoftext|>


<commit_before>(function(window) {
	if (!window.console || !window.console.log) { return; }
	console.log('Sparky      - https://github.com/cruncher/sparky');
})(this);

(function(window) {
	"use strict";

	var DEBUG     = window.DEBUG;

	var Fn        = window.Fn;
	var dom       = window.dom;
	var mount     = window.mount;

	var assign    = Object.assign;

	var debug     = Fn.debug;
	var each      = Fn.each;
	var getPath   = Fn.getPath;
	var id        = Fn.id;
	var isDefined = Fn.isDefined;
	var overload  = Fn.overload;
	var nothing   = Fn.nothing;
	var noop      = Fn.noop;
	var curry     = Fn.curry;
	var get       = Fn.get;
	var set       = Fn.set;
	var each      = Fn.each;

	var append    = dom.append;
	var children  = dom.children;
	var empty     = dom.empty;
	var fragmentFromId = dom.fragmentFromId;
	var fragmentFromTemplate = dom.fragmentFromTemplate;
	var remove    = dom.remove;
	var tag       = dom.tag;

	// Matches:     xxxx: xxx, "xxx", 'xxx'
	var rfn       = /\s*([-\w]+)(?:\s*:\s*((?:"[^"]*"|'[^']*'|[\w-\[\]]*)(?:\s*,\s*(?:"[^"]*"|'[^']*'|[\w-\[\]]*))*))?/;

	var settings = {
		rtokens: /(\{\[)\s*(.*?)(?:\s*\|\s*(.*?))?\s*(\]\})/g,

		mount: function mount(node) {
			var fn       = dom.attribute('data-fn', node);
			var template = dom.attribute('data-template', node);

			if (!fn && !template) { return; }

			var sparky = Sparky(node, undefined, {
				fn: fn,
				template: template
			});

			if (DEBUG) { console.log('mounted:', node); }

			return [{
				token: fn,
				path:  '',
				render: sparky.push
			}];
		}
	};

	function Sparky(node, data, options) {
		if (!Sparky.prototype.isPrototypeOf(this)) {
			return new Sparky(node, data, options);
		}

		node = typeof node === 'string' ? dom(node)[0] : node ;
		data = data && Observable(data);

		var fnstring = options && options.fn || dom.attribute('data-fn', node) || '';
		var calling  = true;

		var sparky   = this;
		var stream   = data ? Stream.of(data) : Stream.of() ;
		var update   = noop;

		// TODO: Fudge.
		if (tag(node) === 'template') {
			var fragment = fragmentFromTemplate(node).cloneNode(true);
			assign(this, fragment.childNodes);
			node = children(fragment)[0];
		}
		else {
			this[0] = node;
		}

		this[0]      = node;
		this.length  = 1;

		this.push    = stream.push;

		this.stop = function stop() {
			stream.stop && stream.stop();
			update(null);
			return sparky;
		};

		this.interrupt = function interrupt() {
			calling = false;
			return { fn: fnstring };
		};

		// Parse the fns and params to execute
		var token, fn, params;

		while (token = fnstring.match(rfn)) {
			fn       = Sparky.fn[token[1]];
			params   = token[2] && JSON.parse('[' + token[2].replace(/'/g, '"') + ']');
			fnstring = fnstring.slice(token[0].length);
			stream   = fn.call(this, node, stream, params) || stream;

			// If fns have been interrupted return the sparky without mounting
			if (!calling) { return this; }
		}

		// TEMP: Find a better way to pass these in
		settings.transforms = Sparky.transforms;
		settings.transformers = Sparky.transformers;

		var template = (options && options.template)
			|| dom.attribute('data-template', node)
			|| '' ;

		stream
		.take(1)
		.each(template ? function(scope) {
			var fragment = fragmentFromId(template);

			if (!fragment) {
				throw new Error('Sparky: data-template="' + template + '" not found in DOM');
			}

			// Replace node content with fragment
			empty(node);
			append(node, fragment);

			// Update
			update = mount(node, settings);
			update(scope);
			stream.each(update);
		} : function(scope) {
			update = mount(node, settings);
			update(scope);
			stream.each(update);
		});
	}

	assign(Sparky.prototype, {
		push: noop,

		remove: function() {
			each(remove, this);
			return this;
		}
	});

	assign(Sparky, {
		fn: {
			get: function(node, stream, params) {
				return stream.map(getPath(params[0]));
			},

			interrupt: function ignore(node, stream) {
				console.log(this.interrupt(), node, stream);
			},

			log: (function(isIE) {
				// Logs nodes, scopes and data.
				return function(node, scopes) {
					var sparky = this;

					// In IE11 and probably below, and possibly Edge, who knows,
					// console.groups can arrive in really weird orders. They
					// are not at all useful for debugging as a result. Rely on
					// console.log.

					function log(scope) {
						console[isIE ? 'log' : 'group']('Sparky: scope', node);
						console.log('data ', sparky.data);
						console.log('scope', scope);
						console.log('fn   ', sparky.fn);
						console[isIE ? 'log' : 'groupEnd']('---');
					}

					console[isIE ? 'log' : 'group']('Sparky: run  ', node);
					console.log('data ', sparky.data);
					console[isIE ? 'log' : 'groupEnd']('---');

					return scopes.tap(log);
				};
			})(
				// Detect IE
				!!(document.all && document.compatMode || window.navigator.msPointerEnabled)
			)
		},

		transforms: {},

		mount:      mount,

		MarkerNode: function MarkerNode(node) {
			// A text node, or comment node in DEBUG mode, for marking a
			// position in the DOM tree so it can be swapped out with some
			// content node.

			if (!DEBUG) {
				return dom.create('text', '');
			}

			var attrScope = node && node.getAttribute('data-scope');
			var attrCtrl  = node && node.getAttribute('data-fn');

			return dom.create('comment',
				(attrScope ? ' data-scope="' + attrScope + '"' : '') +
				(attrCtrl ? ' data-fn="' + attrCtrl + '" ' : '')
			);
		}
	});

	Object.defineProperties(Sparky, {
		rtokens: {
			get: function() { return settings.rtokens; },
			enumerable: true,
			configurable: true
		}
	});

	window.Sparky = Sparky;

})(this);<commit_msg>No need to make everything observable!<commit_after>(function(window) {
	if (!window.console || !window.console.log) { return; }
	console.log('Sparky      - https://github.com/cruncher/sparky');
})(this);

(function(window) {
	"use strict";

	var DEBUG     = window.DEBUG;

	var Fn        = window.Fn;
	var dom       = window.dom;
	var mount     = window.mount;

	var assign    = Object.assign;

	var debug     = Fn.debug;
	var each      = Fn.each;
	var getPath   = Fn.getPath;
	var id        = Fn.id;
	var isDefined = Fn.isDefined;
	var overload  = Fn.overload;
	var nothing   = Fn.nothing;
	var noop      = Fn.noop;
	var curry     = Fn.curry;
	var get       = Fn.get;
	var set       = Fn.set;
	var each      = Fn.each;

	var append    = dom.append;
	var children  = dom.children;
	var empty     = dom.empty;
	var fragmentFromId = dom.fragmentFromId;
	var fragmentFromTemplate = dom.fragmentFromTemplate;
	var remove    = dom.remove;
	var tag       = dom.tag;

	// Matches:     xxxx: xxx, "xxx", 'xxx'
	var rfn       = /\s*([-\w]+)(?:\s*:\s*((?:"[^"]*"|'[^']*'|[\w-\[\]]*)(?:\s*,\s*(?:"[^"]*"|'[^']*'|[\w-\[\]]*))*))?/;

	var settings = {
		rtokens: /(\{\[)\s*(.*?)(?:\s*\|\s*(.*?))?\s*(\]\})/g,

		mount: function mount(node) {
			var fn       = dom.attribute('data-fn', node);
			var template = dom.attribute('data-template', node);

			if (!fn && !template) { return; }

			var sparky = Sparky(node, undefined, {
				fn: fn,
				template: template
			});

			if (DEBUG) { console.log('mounted:', node); }

			return [{
				token: fn,
				path:  '',
				render: sparky.push
			}];
		}
	};

	function Sparky(node, data, options) {
		if (!Sparky.prototype.isPrototypeOf(this)) {
			return new Sparky(node, data, options);
		}

		node = typeof node === 'string' ? dom(node)[0] : node ;

		var fnstring = options && options.fn || dom.attribute('data-fn', node) || '';
		var calling  = true;

		var sparky   = this;
		var stream   = data ? Stream.of(Observable(data) || data) : Stream.of() ;
		var update   = noop;

		// TODO: Fudge.
		if (tag(node) === 'template') {
			var fragment = fragmentFromTemplate(node).cloneNode(true);
			assign(this, fragment.childNodes);
			node = children(fragment)[0];
		}
		else {
			this[0] = node;
		}

		this[0]      = node;
		this.length  = 1;

		this.push    = stream.push;

		this.stop = function stop() {
			stream.stop && stream.stop();
			update(null);
			return sparky;
		};

		this.interrupt = function interrupt() {
			calling = false;
			return { fn: fnstring };
		};

		// Parse the fns and params to execute
		var token, fn, params;
		while (token = fnstring.match(rfn)) {
			fn       = Sparky.fn[token[1]];
			params   = token[2] && JSON.parse('[' + token[2].replace(/'/g, '"') + ']');
			fnstring = fnstring.slice(token[0].length);
			stream   = fn.call(this, node, stream, params) || stream;

			// If fns have been interrupted return the sparky without mounting
			if (!calling) { return this; }
		}

		// TEMP: Find a better way to pass these in
		settings.transforms   = Sparky.transforms;
		settings.transformers = Sparky.transformers;

		var template = (options && options.template)
			|| dom.attribute('data-template', node)
			|| '' ;

		stream
		.take(1)
		.each(template ? function(scope) {
			var fragment = fragmentFromId(template);

			if (!fragment) {
				throw new Error('Sparky: data-template="' + template + '" not found in DOM');
			}

			// Replace node content with fragment
			empty(node);
			append(node, fragment);

			// Update
			update = mount(node, settings);
			update(scope);
			stream.each(update);
		} : function(scope) {
			update = mount(node, settings);
			update(scope);
			stream.each(update);
		});
	}

	assign(Sparky.prototype, {
		push: noop,

		remove: function() {
			each(remove, this);
			return this;
		}
	});

	assign(Sparky, {
		fn: {
			get: function(node, stream, params) {
				return stream.map(getPath(params[0]));
			},

			interrupt: function ignore(node, stream) {
				console.log(this.interrupt(), node, stream);
			},

			log: (function(isIE) {
				// Logs nodes, scopes and data.
				return function(node, scopes) {
					var sparky = this;

					// In IE11 and probably below, and possibly Edge, who knows,
					// console.groups can arrive in really weird orders. They
					// are not at all useful for debugging as a result. Rely on
					// console.log.

					function log(scope) {
						console[isIE ? 'log' : 'group']('Sparky: scope', node);
						console.log('data ', sparky.data);
						console.log('scope', scope);
						console.log('fn   ', sparky.fn);
						console[isIE ? 'log' : 'groupEnd']('---');
					}

					console[isIE ? 'log' : 'group']('Sparky: run  ', node);
					console.log('data ', sparky.data);
					console[isIE ? 'log' : 'groupEnd']('---');

					return scopes.tap(log);
				};
			})(
				// Detect IE
				!!(document.all && document.compatMode || window.navigator.msPointerEnabled)
			)
		},

		transforms: {},

		mount:      mount,

		MarkerNode: function MarkerNode(node) {
			// A text node, or comment node in DEBUG mode, for marking a
			// position in the DOM tree so it can be swapped out with some
			// content node.

			if (!DEBUG) {
				return dom.create('text', '');
			}

			var attrScope = node && node.getAttribute('data-scope');
			var attrCtrl  = node && node.getAttribute('data-fn');

			return dom.create('comment',
				(attrScope ? ' data-scope="' + attrScope + '"' : '') +
				(attrCtrl ? ' data-fn="' + attrCtrl + '" ' : '')
			);
		}
	});

	Object.defineProperties(Sparky, {
		rtokens: {
			get: function() { return settings.rtokens; },
			enumerable: true,
			configurable: true
		}
	});

	window.Sparky = Sparky;

})(this);<|endoftext|>


<commit_before>/**************************************************************
    CLASSES
**************************************************************/
/**
 * A board game with rank information.
 * @class
 * @param {int} id - A unique id.
 * @param {position} - The current position in the ranked list.
 */
var game = function(id, position) {
    this.id = id;
    this.position = position;
    this.wins = 0;
    this.losses = 0;
    this.locked = false;
    this.ranked = false;

    var differential = function() {
        return wins - losses;
    }
}
/**
 * ToString for a game.
 * @method
 */
game.prototype.toString = function() {
    return this.id;
}

/**
 * A collection of games.
 * @class
 * @param {array} list - An array of games.
 */
var games = function(list) {
    // private
    /*var*/ game_matchups = new matchups();

    var compareGames = function(game1, game2) {
        if (game1.position < game2.position)
            return -1;

        if (game1.position > game2.position)
            return 1;

        return 0;
    }

    var isFirstGameBetter = function(game1, game2) {
        // todo: get user input

        console.log('contest: ' + game1 + ' vs ' + game2);

        return game1.id < game2.id;
    }

    var lock = function(games, index) {
        var gameToLock = games[index];
        gameToLock.locked = true;
        games[index] = gameToLock;
        return games;
    }

    var lockAll = function(games) {
        return _.each(games, function(element, index, list) {return lock(list, index);});
    }

    var lockCompletelySortedGames = function(games) {
        for(var i = 0; i <= games.length; i++)
        {
            var gamesRankedLowerCount = game_matchups.getAllRankedLower(games[i].id).length;
            var gamesUnlockedExcludingCurrentGameCount = unlockedList().length - 1;

            if(!games[i].locked && gamesRankedLowerCount == gamesUnlockedExcludingCurrentGameCount)
            {
                games = lock(games, i);
            }
            else
            {
                break;
            }
        }

        for(var i = games.length; i <= 0; i--)
        {
            var gamesRankedHigherCount = game_matchups.getAllRankedHigher(games[i].id).length;
            var gamesUnlockedExcludingCurrentGameCount = unlockedList().length - 1;

            if(!games[i].locked && gamesRankedHigherCount == gamesUnlockedExcludingCurrentGameCount)
            {
                games = lock(games, i);
            }
            else
            {
                break;
            }
        }

        return games;
    }

    var logMatchup = function(winner, loser) {
        var match = new matchup(winner, loser);

        game_matchups.add(match);
    }

    var rankGames = function(games, gameIndex1, gameIndex2) {
        var isFirstBetter = isFirstGameBetter(games[gameIndex1], games[gameIndex2]);

        if(isFirstBetter)
        {
            games[gameIndex1].wins += 1;
            games[gameIndex2].losses += 1;
            logMatchup(games[gameIndex1].id, games[gameIndex2].id);
            games = reposition(games, gameIndex1, gameIndex2);
        }
        else
        {
            games[gameIndex1].losses += 1;
            games[gameIndex2].wins += 1;
            logMatchup(games[gameIndex2].id, games[gameIndex1].id);
            games = reposition(games, gameIndex2, gameIndex1);
        }

        games = lockCompletelySortedGames(games);

        return games;
    }

    var reposition = function(games, winnerIndex, loserIndex) {
        var winnerPosition = games[winnerIndex].position;
        var loserPosition = games[loserIndex].position;

        if(winnerPosition < loserPosition) {
            if(games[winnerIndex].differential() > 0)
            {
                // todo: winner.position increases by differential, as long as it does not move past any games that are locked or that have been ranked above
            }

            if(games[loserIndex].differential() < 0)
            {
                // todo: loser.position decreases by differential, as long as it does not move past any games that are locked or that have been ranked below
            }
        }
        else {
            // todo: Array.prototype.map() only supported in IE9+
            games.map(function(item){
                if(item.position >= loserPosition && item.position < winnerPosition)
                    item.position += 1;
            });

            games[winnerIndex].position = loserPosition;
        }

        return games;
    }

    var unlockedList = function() {
        return _.filter(this.list, function(game) {return !game.locked});
    }

    // public
    this.list = list;

    this.contestAll = function() {
        if(this.list.length <= 1)
        {
            lockList();
            return;
        }

        for(var i = 0; i < this.list.length; i += 2)
        {
            // todo: eliminate redundant sorts
            this.list = rankGames(this.list, i, i + 1);
            //this.sortList();
        }

        console.log(game_matchups.toString());
    }

    this.sortList = function() {
        this.list.sort(compareGames);
    }
}
/**
 * ToString for games.
 * @method
 */
games.prototype.toString = function () {
    return this.list.toString();
}

/**
 * A matchup of two games.
 * @class
 * @param {string} winner - The winner of the matchup.
 * @param {string} loser - The loser of the matchup.
 */
var matchup = function (winner, loser) {
    this.winner = winner;
    this.loser = loser;
}
/**
 * ToString for a matchup.
 * @method
 */
matchup.prototype.toString = function () {
    return this.winner + '>' + this.loser;
}

/**
 * A collection of matchups.
 * @class
 */
var matchups = function () {
    this.list = [];

    this.add = function (matchup) {
        this.list.push(matchup);
    }

    this.getAllRankedLower = function (id, includeId) {
        if (includeId == undefined)
            includeId = false;

        var self = this;

        var losers = self.list.map(function(item){
            if (item.winner == id)
                return item.loser;
        }).filter(function(item){
            return item;
        });

        if (losers.length == 0) {
            return includeId ? [id] : [];
        }
        else {
            var children = losers.map(function(item) {
                return self.getAllRankedLower(item, true);
            });

            losers = losers.concat(_.flatten(children));

            if(includeId)
                losers.push(id);

            return _.uniq(losers);
        }
    }

    this.getAllRankedHigher = function (id, includeId) {
        if (includeId == undefined)
            includeId = false;

        var self = this;

        var winners = self.list.map(function(item){
            if (item.loser == id)
                return item.winner;
        }).filter(function(item){
            return item;
        });

        if (winners.length == 0) {
            return includeId ? [id] : [];
        }
        else {
            var parents = winners.map(function(item) {
                return self.getAllRankedHigher(item, true);
            });

            winners = winners.concat(_.flatten(parents));

            if(includeId)
                winners.push(id);

            return _.uniq(winners);
        }
    }
}
/**
 * ToString for matchups.
 * @method
 */
matchups.prototype.toString = function() {
    return this.list.toString();
}

/**************************************************************
    METHODS
**************************************************************/
var getGames = function() {
    // todo: get user input

    var games = [];
    var i, j;

    for(i = 1, j = 10; i <= 10; i++, j--) {
        games.push(new game(i, j));
    }

    return games;
}

/**************************************************************
    MAIN
**************************************************************/
var games_array = getGames();
var games_object = new games(games_array);
games_object.toString();
games_object.sortList();
games_object.toString();
games_object.contestAll();<commit_msg>Use underscore's map<commit_after>/**************************************************************
    CLASSES
**************************************************************/
/**
 * A board game with rank information.
 * @class
 * @param {int} id - A unique id.
 * @param {position} - The current position in the ranked list.
 */
var game = function(id, position) {
    this.id = id;
    this.position = position;
    this.wins = 0;
    this.losses = 0;
    this.locked = false;
    this.ranked = false;

    var differential = function() {
        return wins - losses;
    }
}
/**
 * ToString for a game.
 * @method
 */
game.prototype.toString = function() {
    return this.id;
}

/**
 * A collection of games.
 * @class
 * @param {array} list - An array of games.
 */
var games = function(list) {
    // private
    /*var*/ game_matchups = new matchups();

    var compareGames = function(game1, game2) {
        if (game1.position < game2.position)
            return -1;

        if (game1.position > game2.position)
            return 1;

        return 0;
    }

    var isFirstGameBetter = function(game1, game2) {
        // todo: get user input

        console.log('contest: ' + game1 + ' vs ' + game2);

        return game1.id < game2.id;
    }

    var lock = function(games, index) {
        var gameToLock = games[index];
        gameToLock.locked = true;
        games[index] = gameToLock;
        return games;
    }

    var lockAll = function(games) {
        return _.each(games, function(element, index, list) {return lock(list, index);});
    }

    var lockCompletelySortedGames = function(games) {
        for(var i = 0; i <= games.length; i++)
        {
            var gamesRankedLowerCount = game_matchups.getAllRankedLower(games[i].id).length;
            var gamesUnlockedExcludingCurrentGameCount = unlockedList().length - 1;

            if(!games[i].locked && gamesRankedLowerCount == gamesUnlockedExcludingCurrentGameCount)
            {
                games = lock(games, i);
            }
            else
            {
                break;
            }
        }

        for(var i = games.length; i <= 0; i--)
        {
            var gamesRankedHigherCount = game_matchups.getAllRankedHigher(games[i].id).length;
            var gamesUnlockedExcludingCurrentGameCount = unlockedList().length - 1;

            if(!games[i].locked && gamesRankedHigherCount == gamesUnlockedExcludingCurrentGameCount)
            {
                games = lock(games, i);
            }
            else
            {
                break;
            }
        }

        return games;
    }

    var logMatchup = function(winner, loser) {
        var match = new matchup(winner, loser);

        game_matchups.add(match);
    }

    var rankGames = function(games, gameIndex1, gameIndex2) {
        var isFirstBetter = isFirstGameBetter(games[gameIndex1], games[gameIndex2]);

        if(isFirstBetter)
        {
            games[gameIndex1].wins += 1;
            games[gameIndex2].losses += 1;
            logMatchup(games[gameIndex1].id, games[gameIndex2].id);
            games = reposition(games, gameIndex1, gameIndex2);
        }
        else
        {
            games[gameIndex1].losses += 1;
            games[gameIndex2].wins += 1;
            logMatchup(games[gameIndex2].id, games[gameIndex1].id);
            games = reposition(games, gameIndex2, gameIndex1);
        }

        games = lockCompletelySortedGames(games);

        return games;
    }

    var reposition = function(games, winnerIndex, loserIndex) {
        var winnerPosition = games[winnerIndex].position;
        var loserPosition = games[loserIndex].position;

        if(winnerPosition < loserPosition) {
            if(games[winnerIndex].differential() > 0)
            {
                // todo: winner.position increases by differential, as long as it does not move past any games that are locked or that have been ranked above
            }

            if(games[loserIndex].differential() < 0)
            {
                // todo: loser.position decreases by differential, as long as it does not move past any games that are locked or that have been ranked below
            }
        }
        else {
            _.map(games, function(item){
                if(item.position >= loserPosition && item.position < winnerPosition)
                    item.position += 1;
            });

            games[winnerIndex].position = loserPosition;
        }

        return games;
    }

    var unlockedList = function() {
        return _.filter(this.list, function(game) {return !game.locked});
    }

    // public
    this.list = list;

    this.contestAll = function() {
        if(this.list.length <= 1)
        {
            lockList();
            return;
        }

        for(var i = 0; i < this.list.length; i += 2)
        {
            // todo: eliminate redundant sorts
            this.list = rankGames(this.list, i, i + 1);
            //this.sortList();
        }

        console.log(game_matchups.toString());
    }

    this.sortList = function() {
        this.list.sort(compareGames);
    }
}
/**
 * ToString for games.
 * @method
 */
games.prototype.toString = function () {
    return this.list.toString();
}

/**
 * A matchup of two games.
 * @class
 * @param {string} winner - The winner of the matchup.
 * @param {string} loser - The loser of the matchup.
 */
var matchup = function (winner, loser) {
    this.winner = winner;
    this.loser = loser;
}
/**
 * ToString for a matchup.
 * @method
 */
matchup.prototype.toString = function () {
    return this.winner + '>' + this.loser;
}

/**
 * A collection of matchups.
 * @class
 */
var matchups = function () {
    this.list = [];

    this.add = function (matchup) {
        this.list.push(matchup);
    }

    this.getAllRankedLower = function (id, includeId) {
        if (includeId == undefined)
            includeId = false;

        var self = this;

        var losers = self.list.map(function(item){
            if (item.winner == id)
                return item.loser;
        }).filter(function(item){
            return item;
        });

        if (losers.length == 0) {
            return includeId ? [id] : [];
        }
        else {
            var children = losers.map(function(item) {
                return self.getAllRankedLower(item, true);
            });

            losers = losers.concat(_.flatten(children));

            if(includeId)
                losers.push(id);

            return _.uniq(losers);
        }
    }

    this.getAllRankedHigher = function (id, includeId) {
        if (includeId == undefined)
            includeId = false;

        var self = this;

        var winners = self.list.map(function(item){
            if (item.loser == id)
                return item.winner;
        }).filter(function(item){
            return item;
        });

        if (winners.length == 0) {
            return includeId ? [id] : [];
        }
        else {
            var parents = winners.map(function(item) {
                return self.getAllRankedHigher(item, true);
            });

            winners = winners.concat(_.flatten(parents));

            if(includeId)
                winners.push(id);

            return _.uniq(winners);
        }
    }
}
/**
 * ToString for matchups.
 * @method
 */
matchups.prototype.toString = function() {
    return this.list.toString();
}

/**************************************************************
    METHODS
**************************************************************/
var getGames = function() {
    // todo: get user input

    var games = [];
    var i, j;

    for(i = 1, j = 10; i <= 10; i++, j--) {
        games.push(new game(i, j));
    }

    return games;
}

/**************************************************************
    MAIN
**************************************************************/
var games_array = getGames();
var games_object = new games(games_array);
games_object.toString();
games_object.sortList();
games_object.toString();
games_object.contestAll();<|endoftext|>


<commit_before>
// This is where our main code will be.

var NIMAGES = 111;
var play                // this is set to stop the playing when paused or stopped
var current_image = 1;  // the image we are looking at.
$('#pause_bttn').hide() // since we are not playing initially

//preload images
var annotate_images={};
for (i=0;i<NIMAGES;i++){
    annotate_images[i] = new Image();
    var fname = sprintf('imgs/cam1logfile1_%05d.jpeg', [i+1]); // Name of the image file.
    annotate_images[i].src = fname
}

//updates the frame details.
function update_image(){
    var fname = sprintf('imgs/cam1logfile1_%05d.jpeg', [current_image]); // Name of the image file.
    $('#to_annotate').attr('src', fname); // Actually load the image.
    var new_text = sprintf('You are currently on frame %d / %d', current_image, NIMAGES);
    $('#info-text').text( new_text ); // Update the text at the top
}

//set frame no to frame_no
function set_frame(frame_no){
    current_image  = frame_no;
    update_image();
}

// moves ahead by no_of_frame --- can take negative no. and go back
function advance_frame(no_of_frame){
    var temp_current_image = current_image + no_of_frame;
    if (temp_current_image > NIMAGES){
        current_image = NIMAGES;
    }else if  (temp_current_image < 1){
        current_image = 1;
    }else{
        current_image = temp_current_image;
    }
    update_image();
    return ;
}

$('#fwd_bttn').click(function () {
    advance_frame(1);
});

//currently playing speed is set to 10fps
$('#play_bttn').click(function () {
    $('#play_bttn').toggle();
    $('#pause_bttn').toggle();
    play = window.setInterval(function() {
        advance_frame(1);
        if (current_image == NIMAGES){
            window.clearInterval(play);
        }
    },100);
});

$('#pause_bttn').click(function () {
    $('#play_bttn').toggle();
    $('#pause_bttn').toggle();
    window.clearInterval(play);
});

$('#stop_bttn').click(function () {
    window.clearInterval(play);
    $('#play_bttn').show();
    $('#pause_bttn').hide();
    set_frame(1);
});

$('#back_bttn').click( function() {
    advance_frame(-1);
});
<commit_msg>Changing path of image<commit_after>
// This is where our main code will be.

var NIMAGES = 100;
var play                // this is set to stop the playing when paused or stopped
var current_image = 1;  // the image we are looking at.
$('#pause_bttn').hide() // since we are not playing initially

var img_path = 'imgs/undercam/cam1logfile1_%05.jpeg';

//preload images
var annotate_images={};
for (i=0;i<NIMAGES;i++){
    annotate_images[i] = new Image();
    var fname = sprintf( img_path, [i+1] ); // Name of the image file.
    annotate_images[i].src = fname
}

//updates the frame details.
function update_image(){
    var fname = sprintf( img_path, [current_image]); // Name of the image file.
    $('#to_annotate').attr('src', fname); // Actually load the image.
    var new_text = sprintf('You are currently on frame %d / %d', current_image, NIMAGES);
    $('#info-text').text( new_text ); // Update the text at the top
}

//set frame no to frame_no
function set_frame(frame_no){
    current_image  = frame_no;
    update_image();
}

// moves ahead by no_of_frame --- can take negative no. and go back
function advance_frame(no_of_frame){
    var temp_current_image = current_image + no_of_frame;
    if (temp_current_image > NIMAGES){
        current_image = NIMAGES;
    }else if  (temp_current_image < 1){
        current_image = 1;
    }else{
        current_image = temp_current_image;
    }
    update_image();
    return ;
}

$('#fwd_bttn').click(function () {
    advance_frame(1);
});

//currently playing speed is set to 10fps
$('#play_bttn').click(function () {
    $('#play_bttn').toggle();
    $('#pause_bttn').toggle();
    play = window.setInterval(function() {
        advance_frame(1);
        if (current_image == NIMAGES){
            window.clearInterval(play);
        }
    },100);
});

$('#pause_bttn').click(function () {
    $('#play_bttn').toggle();
    $('#pause_bttn').toggle();
    window.clearInterval(play);
});

$('#stop_bttn').click(function () {
    window.clearInterval(play);
    $('#play_bttn').show();
    $('#pause_bttn').hide();
    set_frame(1);
});

$('#back_bttn').click( function() {
    advance_frame(-1);
});
<|endoftext|>


<commit_before>const gulp  = require('gulp');
const watch = require('gulp-watch');

const conf = require('../gulpconfig');

//*------------------------------------*\
//     $CSS WATCH
//*------------------------------------*/
gulp.task('watch', ['css:watch', 'images:watch', 'images:watch:svgpartials', 'scripts:watch', 'browser-sync'], function() {
  gulp.watch(`${conf.path.dev.scss}/**/*.scss`, ['css:watch']);
  gulp.watch([`${conf.path.dev.js}/**/!(*.bundle).js`, `${conf.path.dev.js}/**/*.jsx`], ['scripts:lint', 'scripts:watch']);
  gulp.watch(`${conf.path.dev.php}/**/*.php`, ['bs-reload']);
  gulp.watch(`${conf.path.dev.img}/raw/**/*.{jpeg,jpg,png,gif,svg,ico}`, ['images:watch']);
  gulp.watch(`${conf.path.dev.img}/raw/svg/inline-icons/*.svg`, ['images:watch:inlinesvgicons']);
  return gulp.watch(`${conf.path.dev.views}/partials/svg/raw/**/*.svg`, ['images:watch:svgpartials']);
});
<commit_msg>add test watching<commit_after>const gulp  = require('gulp');
const watch = require('gulp-watch');

const conf = require('../gulpconfig');
const devPath = conf.path.dev;

/*------------------------------------*\
     $CSS WATCH
\*------------------------------------*/
gulp.task('watch', ['css:watch', 'images:watch', 'images:watch:svgpartials', 'scripts:watch', 'browser-sync'], function() {
  gulp.watch(`${conf.path.dev.scss}/**/*.scss`, ['css:watch']);
  gulp.watch([`${conf.path.dev.js}/**/!(*.bundle).js`, `${conf.path.dev.js}/**/*.jsx`], ['scripts:lint', 'scripts:watch']);
  gulp.watch(`${conf.path.dev.php}/**/*.php`, ['bs-reload']);
  gulp.watch(`${conf.path.dev.img}/raw/**/*.{jpeg,jpg,png,gif,svg,ico}`, ['images:watch']);
  gulp.watch(`${conf.path.dev.img}/raw/svg/inline-icons/*.svg`, ['images:watch:inlinesvgicons']);
  return gulp.watch(`${conf.path.dev.views}/partials/svg/raw/**/*.svg`, ['images:watch:svgpartials']);
});

/*------------------------------------*\
     $WATCH TESTS
\*------------------------------------*/
gulp.task('watch:tests', function() {
  gulp.watch([`${devPath.js}/**/*.js`])
    .on('change', (file) => {
      const basename = path.basename(file.path);
      const isTestFile = /_test/.test(basename);
      let testFile = file.path;

      if (isTestFile) {
        log(`Running ${basename}`);
      } else {
        try {
          const matchingTestFile = file.path.replace(/\.js$/, '_test.js');

          fs.accessSync(matchingTestFile, fs.F_OK);
          log(`Running ${path.basename(matchingTestFile)}`);
          testFile = matchingTestFile;
        } catch (e) {
          log(`No matching test file for ${basename}.`, 'red');
          log('Running all tests');
          testFile = `${devPath.app}/**/*_test.js`;
        }
      }

      runTest(testFile);
    });

  function log(msg, color = 'green') {
    gutil.log(gutil.colors[color](msg));
  }

  function runTest(glob) {
    return gulp.src('./', { read: false })
      .pipe(shell(`$(which babel-tape-runner) ${glob} | faucet`))
      .on('error', () => {});
  }
});
<|endoftext|>


<commit_before>import request from 'axios';

const API_URL = 'https://webtask.it.auth0.com/api/run/wt-milomord-gmail_com-0/redux-tutorial-backend?webtask_no_cache=1';

export function getTodos() {
  return {
    type: 'GET_TODOS',
    promise: request.get(API_URL)
  }
}

export function createTodo(text) {
  return {
    type: 'CREATE_TODO',
    promise: request.post(API_URL, { time: Date.now(), text })
  };
}

export function editTodo(id, text) {
  return {
    type: 'EDIT_TODO',
    id,
    text,
    date: Date.now()
  };
}

export function deleteTodo(id) {
  return {
    type: 'DELETE_TODO',
    id
  };
}
<commit_msg>Make eslint happier.<commit_after>import request from 'axios';

const API_URL = 'https://webtask.it.auth0.com/api/run/wt-milomord-gmail_com-0/redux-tutorial-backend?webtask_no_cache=1';

export function getTodos() {
  return {
    type:    'GET_TODOS',
    promise: request.get(API_URL)
  }
}

export function createTodo(text) {
  return {
    type:    'CREATE_TODO',
    promise: request.post(API_URL, { time: Date.now(), text })
  };
}

export function editTodo(id, text) {
  return {
    type: 'EDIT_TODO',
    id,
    text,
    date: Date.now()
  };
}

export function deleteTodo(id) {
  return {
    type: 'DELETE_TODO',
    id
  };
}
<|endoftext|>


<commit_before>(function(){
    function cap(low, high) {
	return function(value){ return Math.max(low, Math.min(high, value)); }
    }

    var unit = cap(0,1);

    function scale(range){
	return function(value){ return Math.ceil(range * unit(value)); }
    }

    var x255 = scale(255);

    function integerSupremum(value) {
	return Math.ceil(value);
    }

    function hexValue(value) {
	var hex = (integerSupremum(x255(value))).toString(16);
	return hex.length == 1 ? '0' + hex: hex;
    }

    function toRgb(fraction) {
	hex = hexValue(fraction);
	return '#' + hex  +  hex + hex;
    }

    var Listener = function(){
	this.listeners = [];
    }
    Listener.prototype.addListener = function(listener){
	this.listeners.push(listener);
    }
    Listener.prototype.notifyAll = function(){
	this.listeners.forEach(this.notify.bind(this));
    }
    Listener.prototype.notify = function(listener){
	listener.call(null, this);
    }

    var Vision = function() {
	Listener.call(this);
	this.data = [ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 ];
    }
    Vision.prototype = new Listener();
    Vision.prototype.colorData = function(){
	return this.data.map(toRgb);
    }

    var VisionView = function(canvas, model){
	this.context = canvas.getContext('2d');
	this.width = canvas.width;
	this.height = canvas.height;
	this.model = model;
	this.model.addListener(this.update.bind(this));
	this.update();
    }
    VisionView.prototype.update = function(){
	var context = this.context;
	context.fillStyle = 'black';
	context.fillRect(0, 0, this.width, this.height);

	var colorData = this.model.colorData();
	var offset = (this.width - colorData.length) / 2;
	colorData.forEach(function(color, index){
	    context.strokeStyle = color;
	    context.beginPath();
	    context.moveTo(offset + index, 0);
	    context.lineTo(offset + index, this.height);
	    context.stroke();
	}.bind(this));

    }

    var Radar = function(heading, halfAngle){
	Listener.call(this);
	this.heading = heading;
	this.halfAngle = halfAngle;
	this.delta = Math.PI/50;
    }
    Radar.prototype = new Listener();
    Radar.prototype.left = function(){
	this.heading -= this.delta;
	this.notifyAll();
    }
    Radar.prototype.right = function(){
	this.heading += this.delta;
	this.notifyAll();
    }

    var RadarView = function(canvas, model){
	this.context = canvas.getContext('2d');
	this.width = canvas.width;
	this.height = canvas.height;
	this.model = model;
	this.model.addListener(this.update.bind(this));
	this.update();
    }
    RadarView.prototype.update = function(){
	var context = this.context;
	context.fillStyle = 'black';
	context.fillRect(0, 0, this.width, this.height);

	var heading = this.model.heading;
	var halfAngle = this.model.halfAngle;
	var radius = Math.min(topCanvas.width/2, topCanvas.height/2) - 10;
	var x0 = this.width/2;
	var y0 = this.height/2;
	var x1 = radius * Math.cos(heading + -halfAngle) + x0;
	var y1 = radius * Math.sin(heading + -halfAngle) + y0;
	context.strokeStyle = 'red';
	context.beginPath();
	context.moveTo(x0, y0);
	context.lineTo(x1, y1);
	context.arc(x0, y0, radius, heading - halfAngle, heading + halfAngle);
	context.closePath();
	context.stroke();
    }

    var visionCanvas = document.getElementById('vision');
    var topCanvas = document.getElementById('top');

    var vision = new Vision();
    new VisionView(visionCanvas, vision);

    var radar = new Radar(-Math.PI/6, Math.PI/3);
    new RadarView(topCanvas, radar);

    var body = document.getElementsByTagName('body')[0];
    body.addEventListener('keydown', function(event){
	if (event.keyCode == 37) { // left
	    radar.left();
	}
	if (event.keyCode == 38) { // up
	    console.log(event);
	}
	if (event.keyCode == 39) { // right
	    radar.right();
	}
	if (event.keyCode == 40) { // down
	    console.log(event);
	}
    });
})();
<commit_msg>add location and radius to radar<commit_after>(function(){
    function cap(low, high) {
	return function(value){ return Math.max(low, Math.min(high, value)); }
    }

    var unit = cap(0,1);

    function scale(range){
	return function(value){ return Math.ceil(range * unit(value)); }
    }

    var x255 = scale(255);

    function integerSupremum(value) {
	return Math.ceil(value);
    }

    function hexValue(value) {
	var hex = (integerSupremum(x255(value))).toString(16);
	return hex.length == 1 ? '0' + hex: hex;
    }

    function toRgb(fraction) {
	hex = hexValue(fraction);
	return '#' + hex  +  hex + hex;
    }

    var Listener = function(){
	this.listeners = [];
    }
    Listener.prototype.addListener = function(listener){
	this.listeners.push(listener);
    }
    Listener.prototype.notifyAll = function(){
	this.listeners.forEach(this.notify.bind(this));
    }
    Listener.prototype.notify = function(listener){
	listener.call(null, this);
    }

    var Vision = function() {
	Listener.call(this);
	this.data = [ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 ];
    }
    Vision.prototype = new Listener();
    Vision.prototype.colorData = function(){
	return this.data.map(toRgb);
    }

    var VisionView = function(canvas, model){
	this.context = canvas.getContext('2d');
	this.width = canvas.width;
	this.height = canvas.height;
	this.model = model;
	this.model.addListener(this.update.bind(this));
	this.update();
    }
    VisionView.prototype.update = function(){
	var context = this.context;
	context.fillStyle = 'black';
	context.fillRect(0, 0, this.width, this.height);

	var colorData = this.model.colorData();
	var offset = (this.width - colorData.length) / 2;
	colorData.forEach(function(color, index){
	    context.strokeStyle = color;
	    context.beginPath();
	    context.moveTo(offset + index, 0);
	    context.lineTo(offset + index, this.height);
	    context.stroke();
	}.bind(this));

    }

    var Radar = function(x, y, heading, radius, halfAngle){
	Listener.call(this);
	this.x = x;
	this.y = y;
	this.heading = heading;
	this.radius = radius;
	this.halfAngle = halfAngle;
	this.delta = Math.PI/50;
    }
    Radar.prototype = new Listener();
    Radar.prototype.left = function(){
	this.heading -= this.delta;
	this.notifyAll();
    }
    Radar.prototype.right = function(){
	this.heading += this.delta;
	this.notifyAll();
    }

    var RadarView = function(canvas, model){
	this.context = canvas.getContext('2d');
	this.width = canvas.width;
	this.height = canvas.height;
	this.model = model;
	this.model.addListener(this.update.bind(this));
	this.update();
    }
    RadarView.prototype.update = function(){
	var context = this.context;
	context.fillStyle = 'black';
	context.fillRect(0, 0, this.width, this.height);

	var heading = this.model.heading;
	var halfAngle = this.model.halfAngle;
	var radius = this.model.radius;
	var x0 = this.model.x;
	var y0 = this.model.y;
	var x1 = radius * Math.cos(heading + -halfAngle) + x0;
	var y1 = radius * Math.sin(heading + -halfAngle) + y0;
	context.strokeStyle = 'red';
	context.beginPath();
	context.moveTo(x0, y0);
	context.lineTo(x1, y1);
	context.arc(x0, y0, radius, heading - halfAngle, heading + halfAngle);
	context.closePath();
	context.stroke();
    }

    var visionCanvas = document.getElementById('vision');
    var topCanvas = document.getElementById('top');

    var vision = new Vision();
    new VisionView(visionCanvas, vision);

    var radar = new Radar(topCanvas.width/2, topCanvas.height/2, -Math.PI/6, Math.min(topCanvas.width/2, topCanvas.height/2) - 10, Math.PI/3);
    new RadarView(topCanvas, radar);

    var body = document.getElementsByTagName('body')[0];
    body.addEventListener('keydown', function(event){
	if (event.keyCode == 37) { // left
	    radar.left();
	}
	if (event.keyCode == 38) { // up
	    console.log(event);
	}
	if (event.keyCode == 39) { // right
	    radar.right();
	}
	if (event.keyCode == 40) { // down
	    console.log(event);
	}
    });
})();
<|endoftext|>


<commit_before>import Message from './message';
const ReconnectingWebSocket = require('../node_modules/ReconnectingWebSocket/reconnecting-websocket');

export default class Worker {
  constructor(account) {
    this.account = account;
  }

  postNotification(message) {
    return chrome.notifications.create(
      null,
      {
        type: "basic",
        title: this.account.name,
        message: message.getText(),
        iconUrl: "icon.png"
      },
      (createdId) => {
        chrome.notifications.onClicked.addListener(clickedId => {
          if (createdId === clickedId) {
            window.open(message.getUrl());
          }
        });
      }.bind(this)
    );
  }

  onclose(ev) {
  }

  onerror(ev) {
  }

  onmessage(ev) {
    let message = new Message(this.account, JSON.parse(ev.data));
    if (message.shouldNotify()) {
      this.postNotification(message);
    }
  }

  onopen(ev) {
  }

  setWsHandlers(ws) {
    ws.onclose = this.onclose.bind(this);
    ws.onerror = this.onerror.bind(this);
    ws.onmessage = this.onmessage.bind(this);
    ws.onopen = this.onopen.bind(this);
  }

  createRealTimeSession() {
    let url = "https://slack.com/api/rtm.start?token=" + this.account.token;
    return fetch(url)
      .then(res => res.json())
      .then(json => new ReconnectingWebSocket(json.url))
      .then(this.setWsHandlers.bind(this));
  }

  main() {
    this.createRealTimeSession()
  }
}
<commit_msg>WebSocket reconnecting<commit_after>import Message from './message';

export default class Worker {
  constructor(account) {
    this.account = account;
  }

  postNotification(message) {
    return chrome.notifications.create(
      null,
      {
        type: "basic",
        title: this.account.name,
        message: message.getText(),
        iconUrl: "icon.png"
      },
      createdId => {
        chrome.notifications.onClicked.addListener(clickedId => {
          if (createdId === clickedId) {
            window.open(message.getUrl());
          }
        });
      }.bind(this)
    );
  }

  onclose(ws, ev) {
  }

  onerror(ws, ev) {
    console.log("error. reconnecting...");
    ws.close();
    this.createRealTimeSession();
  }

  onmessage(ws, ev) {
    console.log("onmessage: " + ev.data);
    let json = JSON.parse(ev.data);
    let message = new Message(this.account, json);
    if (message.shouldNotify()) {
      this.postNotification(message);
    }
  }

  onopen(ws, ev) {
    console.log("connected!");
  }

  setWsHandlers(ws) {
    ws.onclose = ev => {
      this.onclose(ws, ev);
    }.bind(this);
    ws.onerror = ev => {
      this.onerror(ws, ev);
    }.bind(this);
    ws.onmessage = ev => {
      this.onmessage(ws, ev);
    }.bind(this);
    ws.onopen = ev => {
      this.onopen(ws, ev);
    }.bind(this);
  }

  createRealTimeSession() {
    let url = "https://slack.com/api/rtm.start?token=" + this.account.token;
    return fetch(url)
      .then(res => res.json())
      .then(json => new WebSocket(json.url))
      .then(this.setWsHandlers.bind(this))
      .catch(e => {
        console.log("failed to create ws session. try 1 mintute after...");
        setTimeout(this.createRealTimeSession.bind(this), 60000);
      }.bind(this));
  }

  main() {
    this.createRealTimeSession()
  }
}
<|endoftext|>


<commit_before>//BEGIN FluidDB REST LIB

fluidDB = new Object();

fluidDB.instance = {
    main : "http://fluiddb.fluidinfo.com/",
    sandbox : "http://sandbox.fluidinfo.com/"
}

fluidDB.choose = function(type){
  if(type === "main" || type === "sandbox"){
    fluidDB.baseURL = fluidDB.instance[type];
  }
}

fluidDB.choose('main'); // main instance as default

fluidDB.config = function(options) {

  // authentication credentials
  if((options.username != undefined) && (options.password != undefined)){
    fluidDB.authenticate = true;
    fluidDB.username     = options.username;
    fluidDB.password     = options.password;
    fluidDB.base64string = Base64.encode(options.username + ":" + options.password);
  }else if(options.auth_token){
    fluidDB.authenticate = true;
    fluidDB.base64string = options.auth_token;
  }

  fluidDB.choose(options.instance);

}

fluidDB.ajax = function(options){
  if((options.username != undefined) && (options.password != undefined)){
    // we can override the authentication defaults
    var authenticate = true;
    var base64string = Base64.encode(options.username + ":" + options.password);
  }else if(options.auth_token){
    var authenticate = true;
    var base64string = options.auth_token;
  }else if(fluidDB.authenticate){
    // there are no credential passed as arguments, but maybe there're in the configuration
    var authenticate = true;
    var base64string = fluidDB.base64string;
  }

  options.url  = fluidDB.baseURL+options.url;
  options.async    = options.async || true;
  options.content_type = options.content_type || "application/json";
  options.opaque = options.opaque || false;
  options.contentType  = options.content_type;
  options.beforeSend   =  function(xhrObj){
                            if(authenticate){
                                xhrObj.setRequestHeader("Authorization","Basic "+ base64string);
                            };
                            xhrObj.setRequestHeader("Content-Type", options.content_type);
                          };
  options.processData  = false;
  options.data  = options.payload;

  $.ajax(options);
}

fluidDB.get = function(options){
  options.type = "GET";
  options.payload = null;

  fluidDB.ajax(options);
}

fluidDB.post = function(options){
  options.type = "POST";

  fluidDB.ajax(options);
}

fluidDB.put = function(options){
  options.type = "PUT";

  if(options.opaque){
    options.content_type = "application/vnd.fluiddb.value+json";
  }

  fluidDB.ajax(options);
}

fluidDB.delete = function(options){
  options.type = "DELETE";
  options.payload = null;

  fluidDB.ajax(options);
}

fluidDB.head = function(options){
  options.type = "HEAD";
  options.payload = null;

  fluidDB.ajax(options);
}

//END FluidDB REST LIB

//BEGIN Base64 LIB
/* Taken from http://www.webtoolkit.info/javascript-base64.html
*  eventually is going to be moved outside this file
*/

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

//END Base64 LIB
<commit_msg>changing option's name from opaque to primitive<commit_after>//BEGIN FluidDB REST LIB

fluidDB = new Object();

fluidDB.instance = {
    main : "http://fluiddb.fluidinfo.com/",
    sandbox : "http://sandbox.fluidinfo.com/"
}

fluidDB.choose = function(type){
  if(type === "main" || type === "sandbox"){
    fluidDB.baseURL = fluidDB.instance[type];
  }
}

fluidDB.choose('main'); // main instance as default

fluidDB.config = function(options) {

  // authentication credentials
  if((options.username != undefined) && (options.password != undefined)){
    fluidDB.authenticate = true;
    fluidDB.username     = options.username;
    fluidDB.password     = options.password;
    fluidDB.base64string = Base64.encode(options.username + ":" + options.password);
  }else if(options.auth_token){
    fluidDB.authenticate = true;
    fluidDB.base64string = options.auth_token;
  }

  fluidDB.choose(options.instance);

}

fluidDB.ajax = function(options){
  if((options.username != undefined) && (options.password != undefined)){
    // we can override the authentication defaults
    var authenticate = true;
    var base64string = Base64.encode(options.username + ":" + options.password);
  }else if(options.auth_token){
    var authenticate = true;
    var base64string = options.auth_token;
  }else if(fluidDB.authenticate){
    // there are no credential passed as arguments, but maybe there're in the configuration
    var authenticate = true;
    var base64string = fluidDB.base64string;
  }

  options.url  = fluidDB.baseURL+options.url;
  options.async    = options.async || true;
  options.content_type = options.content_type || "application/json";
  options.primitive = options.primitive || false;
  options.contentType  = options.content_type;
  options.beforeSend   =  function(xhrObj){
                            if(authenticate){
                                xhrObj.setRequestHeader("Authorization","Basic "+ base64string);
                            };
                            xhrObj.setRequestHeader("Content-Type", options.content_type);
                          };
  options.processData  = false;
  options.data  = options.payload;

  $.ajax(options);
}

fluidDB.get = function(options){
  options.type = "GET";
  options.payload = null;

  fluidDB.ajax(options);
}

fluidDB.post = function(options){
  options.type = "POST";

  fluidDB.ajax(options);
}

fluidDB.put = function(options){
  options.type = "PUT";

  if(options.primitive){
    options.content_type = "application/vnd.fluiddb.value+json";
  }

  fluidDB.ajax(options);
}

fluidDB.delete = function(options){
  options.type = "DELETE";
  options.payload = null;

  fluidDB.ajax(options);
}

fluidDB.head = function(options){
  options.type = "HEAD";
  options.payload = null;

  fluidDB.ajax(options);
}

//END FluidDB REST LIB

//BEGIN Base64 LIB
/* Taken from http://www.webtoolkit.info/javascript-base64.html
*  eventually is going to be moved outside this file
*/

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

//END Base64 LIB
<|endoftext|>


<commit_before>function fractional_part_len(value) {
    const parts = (Number(value) + '').split('.');
    return parts.length < 2 ? 0 : parts[1].length;
}

// FIXME this should be unit tested.. here is one bug: 501,695,.505
export function formatDecimal(value, decPlaces = 2, truncate0s = true) {
    let decSeparator, fl, i, j, sign, thouSeparator, abs_value;
    if (value === null || value === void 0 || isNaN(value)) {
        return 'NaN';
    }
    if (truncate0s) {
        fl = fractional_part_len(value);
        if (fl < 2) fl = 2;
        if (fl < decPlaces) decPlaces = fl;
    }
    decSeparator = '.';
    thouSeparator = ',';
    sign = value < 0 ? '-' : '';
    abs_value = Math.abs(value);
    i = parseInt(abs_value.toFixed(decPlaces), 10) + '';
    j = i.length;
    j = i.length > 3 ? j % 3 : 0;
    const decPart = (decPlaces ? decSeparator + Math.abs(abs_value - i).toFixed(decPlaces).slice(2) : '');
    return [sign + (j ? i.substr(0, j) + thouSeparator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thouSeparator), decPart];
}

export function parsePayoutAmount(amount) {
    return parseFloat(String(amount).replace(/\s[A-Z]*$/, ''));
}

/**
    This is a rough approximation of log10 that works with huge digit-strings.
    Warning: Math.log10(0) === NaN
*/
function log10(str) {
    const leadingDigits = parseInt(str.substring(0, 4));
    const log = Math.log(leadingDigits) / Math.log(10)
    const n = str.length - 1;
    return n + (log - parseInt(log));
}

export const repLog10 = rep2 => {
    if(rep2 == null) return rep2
    let rep = String(rep2)
    const neg = rep.charAt(0) === '-'
    rep = neg ? rep.substring(1) : rep

    let out = log10(rep)
    if(isNaN(out)) out = 0
    out = Math.max(out - 7, 0); // -7 to remove reputation Satoshis
    out = (neg ? -1 : 1) * out
    out = (out + 5) * 5
    // base-line 0 to darken and < 0 to auto hide (grep rephide)
    out = parseInt(out)
    return out
}
<commit_msg>dampen low reps and stretch scale<commit_after>function fractional_part_len(value) {
    const parts = (Number(value) + '').split('.');
    return parts.length < 2 ? 0 : parts[1].length;
}

// FIXME this should be unit tested.. here is one bug: 501,695,.505
export function formatDecimal(value, decPlaces = 2, truncate0s = true) {
    let decSeparator, fl, i, j, sign, thouSeparator, abs_value;
    if (value === null || value === void 0 || isNaN(value)) {
        return 'NaN';
    }
    if (truncate0s) {
        fl = fractional_part_len(value);
        if (fl < 2) fl = 2;
        if (fl < decPlaces) decPlaces = fl;
    }
    decSeparator = '.';
    thouSeparator = ',';
    sign = value < 0 ? '-' : '';
    abs_value = Math.abs(value);
    i = parseInt(abs_value.toFixed(decPlaces), 10) + '';
    j = i.length;
    j = i.length > 3 ? j % 3 : 0;
    const decPart = (decPlaces ? decSeparator + Math.abs(abs_value - i).toFixed(decPlaces).slice(2) : '');
    return [sign + (j ? i.substr(0, j) + thouSeparator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thouSeparator), decPart];
}

export function parsePayoutAmount(amount) {
    return parseFloat(String(amount).replace(/\s[A-Z]*$/, ''));
}

/**
    This is a rough approximation of log10 that works with huge digit-strings.
    Warning: Math.log10(0) === NaN
*/
function log10(str) {
    const leadingDigits = parseInt(str.substring(0, 4));
    const log = Math.log(leadingDigits) / Math.log(10)
    const n = str.length - 1;
    return n + (log - parseInt(log));
}

export const repLog10 = rep2 => {
    if(rep2 == null) return rep2
    let rep = String(rep2)
    const neg = rep.charAt(0) === '-'
    rep = neg ? rep.substring(1) : rep

    let out = log10(rep)
    if(isNaN(out)) out = 0
    out = Math.max(out - 9, 0); // @ -9, $0.50 earned is approx magnitude 1
    out = (neg ? -1 : 1) * out
    out = (out * 10) + 25 // 10 points per magnitude. center at 25
    // base-line 0 to darken and < 0 to auto hide (grep rephide)
    out = parseInt(out)
    return out
}
<|endoftext|>


<commit_before>'use strict'
const slapp = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');
const request = require('request')
const where = require('node-where')

// route functions
const snapsByGeo = require('./routes/snapsByGeoRoute.js').snapsByGeo
const routeFuncs = require('./routes/routesIndex.js')
const yes = require('./routes/yes.js').yes
const addressToGeo = require('./routes/addressToGeo.js').addressToGeo
const appDl = require('./routes/appDlRoute.js').appDl
const teamSettings = require('../teamSettings.js').teamSettings

const notify = require('./notifySlash.js').notify

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users,
      slackDb = firebase.slackDb

let jayBtns={
  text: "",
  attachments: [{
    text: 'How can I help?',
    fallback: 'Where to today?',
    callback_id: 'jaywalk_callback',
    color: 'good',
    actions: [
      {
        name: 'answer',
        text: 'Find deals',
        type: 'button',
        value: 'address'
      },{
        name: 'answer',
        text: 'Settings',
        type: 'button',
        value: 'settings'
      },{
        name: 'answer',
        text: 'Download app',
        type: 'button',
        value: 'app'
      }
    ]
  }]
}

const jaywalk = function() {
  let state = { requested: Date.now() }
  let teamId = ''
  let teamInfo = {}
  let answer

  slapp.command('/jaywalk', (msg, text) => {
    teamInfo = slackDb
      .child(msg.body.team_id)
      .once("value")
      .then(function(obj){
        if(obj.val()==null){
          msg
            .say({text:`Welcome to Jaywalk! To get better results, please enter the address or your buisness name and city.`})
            .route('new_address', state, 60)
        } else{
          teamInfo = obj.val()
            msg
              .say(jayBtns)
              .route('requestToDatabase', state, 60)
        }
      })
  })

// slapp.action('jaywalk_callback', 'answer', (msg, value) => {

  .route('requestToDatabase', (msg, state) => {
    if(msg.body.actions==undefined){      // try callback then remove this
      msg.route('requestToDatabase', state, 60)
    }else{
      answer = msg.body.actions[0].value
      if(answer == 'app'){
        appDl(teamInfo,msg,state)
      }else if(answer == 'address'){
        yes(teamInfo,msg,state)
        //https://jaywalk-geo.herokuapp.com/geoloc.htm
        // .route('handleGeoLoc', state, 60)
      }else if(answer == 'settings'){
        teamSettings(teamInfo,msg,state)
      }else if(answer == 'notifications'){
        notify(teamInfo,msg,state)
      }else{ //handle error
        return msg
          .say("Whoops, you just have to pick a button...")
          .say('Click a button!')
          .route('requestToDatabase', state, 60)
      }
    } //end else(actions undefined checker)
  }) //end .route('requestToDatabase')
  // }) //end callback
  .route('relaventAsk', (msg,state) => {
    routeFuncs.relaventAsk(msg,state)
  })//end .route(relaventAsk)
  .route('address_geo', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    where.is(text,function(err,result){
      /*
        result.get('')=>
        address,streetNumber, street,streetAddress,city,region,
        regionCode, postalCode, country, countryCode, lat, lng
      */
      if (result) {
        let lat = result.get('lat')
        let lng = result.get('lng')
        snapsByGeo(lat,lng,msg,state)
      }
    })
  })
  .route('new_address', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    console.log(text)
  })
}
module.exports = {
  jaywalk:jaywalk(),
  jayBtns:jayBtns
}

<commit_msg>try catch<commit_after>'use strict'
const slapp = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');
const request = require('request')
const where = require('node-where')

// route functions
const snapsByGeo = require('./routes/snapsByGeoRoute.js').snapsByGeo
const routeFuncs = require('./routes/routesIndex.js')
const yes = require('./routes/yes.js').yes
const addressToGeo = require('./routes/addressToGeo.js').addressToGeo
const appDl = require('./routes/appDlRoute.js').appDl
const teamSettings = require('../teamSettings.js').teamSettings

const notify = require('./notifySlash.js').notify

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users,
      slackDb = firebase.slackDb

let jayBtns={
  text: "",
  attachments: [{
    text: 'How can I help?',
    fallback: 'Where to today?',
    callback_id: 'jaywalk_callback',
    color: 'good',
    actions: [
      {
        name: 'answer',
        text: 'Find deals',
        type: 'button',
        value: 'address'
      },{
        name: 'answer',
        text: 'Settings',
        type: 'button',
        value: 'settings'
      },{
        name: 'answer',
        text: 'Download app',
        type: 'button',
        value: 'app'
      }
    ]
  }]
}

const jaywalk = function() {
  let state = { requested: Date.now() }
  let teamId = ''
  let teamInfo = {}
  let answer

  slapp.command('/jaywalk', (msg, text) => {
    try{
      teamInfo = slackDb
        .child(msg.body.team_id)
        .once("value")
        .then(function(obj){
          teamInfo = obj.val()
            msg
              .say(jayBtns)
              .route('requestToDatabase', state, 60)
        })
      }catch(err){
          msg
            .say({text:`Welcome to Jaywalk! To get better results, please enter the address or your buisness name and city.`})
            .route('new_address', state, 60)
      }
  })

// slapp.action('jaywalk_callback', 'answer', (msg, value) => {

  .route('requestToDatabase', (msg, state) => {
    if(msg.body.actions==undefined){      // try callback then remove this
      msg.route('requestToDatabase', state, 60)
    }else{
      answer = msg.body.actions[0].value
      if(answer == 'app'){
        appDl(teamInfo,msg,state)
      }else if(answer == 'address'){
        yes(teamInfo,msg,state)
        //https://jaywalk-geo.herokuapp.com/geoloc.htm
        // .route('handleGeoLoc', state, 60)
      }else if(answer == 'settings'){
        teamSettings(teamInfo,msg,state)
      }else if(answer == 'notifications'){
        notify(teamInfo,msg,state)
      }else{ //handle error
        return msg
          .say("Whoops, you just have to pick a button...")
          .say('Click a button!')
          .route('requestToDatabase', state, 60)
      }
    } //end else(actions undefined checker)
  }) //end .route('requestToDatabase')
  // }) //end callback
  .route('relaventAsk', (msg,state) => {
    routeFuncs.relaventAsk(msg,state)
  })//end .route(relaventAsk)
  .route('address_geo', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    where.is(text,function(err,result){
      /*
        result.get('')=>
        address,streetNumber, street,streetAddress,city,region,
        regionCode, postalCode, country, countryCode, lat, lng
      */
      if (result) {
        let lat = result.get('lat')
        let lng = result.get('lng')
        snapsByGeo(lat,lng,msg,state)
      }
    })
  })
  .route('new_address', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    console.log(text)
  })
}
module.exports = {
  jaywalk:jaywalk(),
  jayBtns:jayBtns
}

<|endoftext|>