<commit_before>var fs = require("fs");
var util = require("util");

var Backbone = require("backbone");
var _ = require("backbone/node_modules/underscore");
var def = require("underscore.deferred");
var $ = require("cheerio");

// Hacky way to get layoutmanager to load with the correct globals
(function() {

  eval(fs.readFileSync(__dirname +
    "/../backbone.layoutmanager.js").toString());

  // Helper function to get a value from a Backbone object as a property
  // or as a function.
  var getValue = function(object, prop) {
    if (!(object && object[prop])) {
      return null;
    }

    return _.isFunction(object[prop]) ? object[prop]() : object[prop];
  };

  // Ensure Backbone doesn't ensureElement
  Backbone.View.prototype._ensureElement = function() {
    var attrs;

    if (!this.el) {
      attrs = getValue(this, "attributes") || {};

      if (this.id) {
        attrs.id = this.id;
      }

      if (this.className) {
        attrs["class"] = this.className;
      }

      this.setElement(this.make(this.tagName, attrs), false);
    } else {
      this.setElement(this.el, false);
    }
  };

  Backbone.View.prototype.make = function(tagName, attributes, content) {
    var el = $("<" + tagName + "/>");
    if (attributes) el.attr(attributes);
    if (content) el.html(content);
    return el;
  };

  Backbone.View.prototype.setElement = function(element, delegate) {
    this.$el = element;
    this.el = element[0];

    return this;
  };

  Backbone.LayoutManager.configure({

    deferred: function() {
      return def.Deferred();
    },

    fetch: function(path) {
      var done = this.async();

      fs.readFile("./" + path, function(err, contents) {
        done(_.template(contents.toString()));
      });
    },

    // This is really the only way you will want to partially apply a view into
    // a layout.  Its entirely possible you'll want to do it differently, so
    // this method is available to change.
    partial: function(root, name, el, append) {
      // If no selector is specified, assume the parent should be added to.
      var $root = name ? $(root).find(name) : $(root);

      // If no root found, return false.
      if (!$root.length) {
        return false;
      }

      // Use the append method if append argument is true.
      this[append ? "append" : "html"]($root, el);

      // If successfully added, return true.
      return true;
    },

    // Override this with a custom HTML method, passed a root element and an
    // element to replace the innerHTML with.
    html: function(root, el) {
      var $root = root[0] ? root : $(root);
      $root.html(_.isString(el) ? el : $(el).html());
    },

    // Very similar to HTML except this one will appendChild.
    append: function(root, el) {
      var $root = root[0] ? root : $(root);
      $root.append(_.isString(el) ? el : $(el).html());
    },

    when: function(promises) {
      return def.when.apply(null, promises);
    },

  });

}).call(_.extend(global, { Backbone: Backbone, _: _ }));

module.exports = Backbone.LayoutManager;
<commit_msg>added better error handling for missing files<commit_after>var fs = require("fs");
var util = require("util");

var Backbone = require("backbone");
var _ = require("backbone/node_modules/underscore");
var def = require("underscore.deferred");
var $ = require("cheerio");

// Hacky way to get layoutmanager to load with the correct globals
(function() {

  eval(fs.readFileSync(__dirname +
    "/../backbone.layoutmanager.js").toString());

  // Helper function to get a value from a Backbone object as a property
  // or as a function.
  var getValue = function(object, prop) {
    if (!(object && object[prop])) {
      return null;
    }

    return _.isFunction(object[prop]) ? object[prop]() : object[prop];
  };

  // Ensure Backbone doesn't ensureElement
  Backbone.View.prototype._ensureElement = function() {
    var attrs;

    if (!this.el) {
      attrs = getValue(this, "attributes") || {};

      if (this.id) {
        attrs.id = this.id;
      }

      if (this.className) {
        attrs["class"] = this.className;
      }

      this.setElement(this.make(this.tagName, attrs), false);
    } else {
      this.setElement(this.el, false);
    }
  };

  Backbone.View.prototype.make = function(tagName, attributes, content) {
    var el = $("<" + tagName + "/>");
    if (attributes) el.attr(attributes);
    if (content) el.html(content);
    return el;
  };

  Backbone.View.prototype.setElement = function(element, delegate) {
    this.$el = element;
    this.el = element[0];

    return this;
  };

  Backbone.LayoutManager.configure({

    deferred: function() {
      return def.Deferred();
    },

    fetch: function(path) {
      var done = this.async();

      fs.readFile("./" + path, function(err, contents) {
        try {
          done(_.template(contents.toString()));
        } catch (ex) {
          console.log("Unable to locate file: " + path);
        }
      });
    },

    // This is really the only way you will want to partially apply a view into
    // a layout.  Its entirely possible you'll want to do it differently, so
    // this method is available to change.
    partial: function(root, name, el, append) {
      // If no selector is specified, assume the parent should be added to.
      var $root = name ? $(root).find(name) : $(root);

      // If no root found, return false.
      if (!$root.length) {
        return false;
      }

      // Use the append method if append argument is true.
      this[append ? "append" : "html"]($root, el);

      // If successfully added, return true.
      return true;
    },

    // Override this with a custom HTML method, passed a root element and an
    // element to replace the innerHTML with.
    html: function(root, el) {
      var $root = root[0] ? root : $(root);
      $root.html(_.isString(el) ? el : $(el).html());
    },

    // Very similar to HTML except this one will appendChild.
    append: function(root, el) {
      var $root = root[0] ? root : $(root);
      $root.append(_.isString(el) ? el : $(el).html());
    },

    when: function(promises) {
      return def.when.apply(null, promises);
    },

  });

}).call(_.extend(global, { Backbone: Backbone, _: _ }));

module.exports = Backbone.LayoutManager;
<|endoftext|>


<commit_before>'use strict';

require('colors');

var Q = require('q');
var read = require('read');
var VFS = require('./vfs').VFS;

var filterQueries = function(list, ignore) {
    Object.keys(list).forEach(function(path){
        //Filter files that don't have a .jq or .xq suffix
        if(
            path.substring(path.length - 3) !== '.jq' &&
            path.substring(path.length - 3) !== '.xq'
        ) {
            delete list[path];
        } else {
            var matched = false;
            ignore.forEach(function(mask){
                if(path.match(mask) !== null) {
                    matched = true;
                    return false;
                }
            });
            if(matched === true) {
                delete list[path];
            }
        }
    });
    return list;
};

var loc = function(isOriginRemote){
    return isOriginRemote ? 'remote' : 'local';
};

var logDiff = function(diff, simulate){
    var msg;
    if(diff.type === 'write') {
        if(diff.isOriginRemote) {
            msg = ('<< '.green) + ('↙ '.blue) + diff.query;
        } else {
            msg = ('>> '.green) + ('↗ '.blue) + diff.query;
        }
    } else {
        msg = ('✗'.red) + ' <' + loc(!diff.isOriginRemote) + '>/' + diff.query;
    }
    if(simulate === true) {
        msg += ' (simulate)';
    }
    if(diff.type === 'write') {
        console.log(msg);
    } else {
        console.log(msg.red);
    }
};

var  Options = {
    OVERWRITE_ALWAYS: 0,
    OVERWRITE_NEVER: 1,
    OVERWRITE_ASK: 2,
    OVERWRITE_IF_NEWER: 3
};
exports.Options = Options;

exports.Client = function($28, projectName, projectToken, localProjectPath){
    var vfs = new VFS($28, projectName, projectToken, localProjectPath);

    var writeLocalQuery = function(diff){
        return vfs.writeLocalQuery(diff.query).then(function(){ logDiff(diff); });
    };

    var writeRemoteQuery = function(diff){
        return vfs.writeRemoteQuery(diff.query)
        .then(function(compileError){
            logDiff(diff);
            if(compileError) {
                throw compileError;
            }
        });
    };

    var deleteLocalQuery = function(diff){
        return vfs.deleteLocalQuery(diff.query).then(function(){ logDiff(diff); });
    };

    var deleteRemoteQuery = function(diff){
        return vfs.deleteRemoteQuery(diff.query).then(function(){ logDiff(diff); });
    };

    var commit = function(simulate, diffs){
        var modulePromises = [];
        var queryPromises = [];
        diffs.forEach(function(diff){
            var container = diff.query.substring(0, 'modules'.length) === 'modules' ? modulePromises : queryPromises;
            if(simulate) {
                logDiff(diff, simulate);
            } else if(diff.type === 'write'){
                if(diff.isOriginRemote) {
                    container.push(writeLocalQuery(diff));
                } else {
                    container.push(writeRemoteQuery(diff));
                }
            } else {
                if(diff.isOriginRemote) {
                    container.push(deleteLocalQuery(diff));
                } else {
                    container.push(deleteRemoteQuery(diff));
                }
            }
        });

        var handler = function(results){
            var errors = [];
            results.forEach(function (result) {
                if (result.state !== 'fulfilled') {
                    errors.push(result.reason);
                }
            });
            if(errors.length > 0) {
                throw errors;
            }
            return results;
        };

        return [
            function(){ return Q.allSettled(modulePromises).then(handler); },
            function(){ return Q.allSettled(queryPromises).then(handler); }
        ].reduce(Q.when, new Q([]));
    };

    var addDiff = function(diff){
        return function(diffs){
            var defered = Q.defer();
            setTimeout(function() {
                diffs.push(diff);
                defered.resolve(diffs);
            }, 1);
            return defered.promise;
        };
    };

    var sync = function(localQueries, remoteQueries, overwrite, deleteOrphaned, simulate, isOriginRemote){
        var promises = [];
        var origin = isOriginRemote ? remoteQueries : localQueries;
        var target = isOriginRemote ? localQueries : remoteQueries;
        Object.keys(origin).forEach(function(query) {
            var targetQuery = target[query];
            var diff = {
                type: 'write',
                query: query,
                isOriginRemote: isOriginRemote
            };
            if(targetQuery) {
                var originLastModified = origin[query].lastModified;
                var targetLastModified = targetQuery.lastModified;
                if(overwrite === Options.OVERWRITE_ALWAYS) {
                    promises.push(addDiff(diff));
                } else if(overwrite === Options.OVERWRITE_IF_NEWER) {
                    if((new Date(originLastModified)).getTime() > (new Date(targetLastModified)).getTime()){
                        promises.push(addDiff(diff));
                    }
                } else if(overwrite === Options.OVERWRITE_ASK) {
                    promises.push(function (diffs) {
                        var defered = Q.defer();
                        read({
                            prompt: 'Overwrite: <' + loc(!isOriginRemote) + '>/' + query + ' (' + targetLastModified + ') with <' + loc(isOriginRemote) + '>/' + query + ' (' + originLastModified + ')? Y/[N]',
                            default: 'N'
                        }, function (er, value) {
                            if (er) {
                                defered.reject(er);
                            }
                            if (value !== undefined && value.toUpperCase() === 'Y') {
                                diffs.push(diff);
                            }
                            defered.resolve(diffs);
                        });
                        return defered.promise;
                    });
                } else if(overwrite === Options.OVERWRITE_NEVER) {
                    //Do nothing
                } else {
                    throw new Error('Invalid overwrite value: ' + overwrite);
                }
            } else {
                promises.push(addDiff(diff));
            }
        });
        if(deleteOrphaned === true) {
            Object.keys(target).forEach(function(query) {
                if(origin[query] === undefined) {
                    promises.push(addDiff({
                        type: 'delete',
                        query: query,
                        isOriginRemote: isOriginRemote
                    }));
                }
            });
        }
        promises.push(function(diffs){ return commit(simulate, diffs); });
        return promises.reduce(Q.when, new Q([]));
    };

    this.sync = function(overwrite, deleteOrphaned, simulate, ignore, isOriginRemote){
        return Q.all([
            vfs.getLocalQueries(),
            vfs.getRemoteQueries()
        ])
        .then(function(queries){
            var localQueries  = filterQueries(queries[0], ignore);
            var remoteQueries = filterQueries(queries[1], ignore);
            return sync(localQueries, remoteQueries, overwrite, deleteOrphaned, simulate, isOriginRemote);
        });
    };

    var that = this;
    this.download = function(overwrite, deleteOrphaned, simulate, ignore){
        return that.sync(overwrite, deleteOrphaned, simulate, ignore, true);
    };

    this.upload = function(overwrite, deleteOrphaned, simulate, ignore){
        return that.sync(overwrite, deleteOrphaned, simulate, ignore, false);
    };

    this.truncate = function(simulate, ignore){
        return vfs.getRemoteQueries().then(function(queries){
            var remoteQueries = filterQueries(queries, ignore);
            return sync({}, remoteQueries, Options.OVERWRITE_ALWAYS, true, simulate, false);
        });
    };
};
<commit_msg>Fix race condition<commit_after>'use strict';

require('colors');

var Q = require('q');
var read = require('read');
var VFS = require('./vfs').VFS;

var filterQueries = function(list, ignore) {
    Object.keys(list).forEach(function(path){
        //Filter files that don't have a .jq or .xq suffix
        if(
            path.substring(path.length - 3) !== '.jq' &&
            path.substring(path.length - 3) !== '.xq'
        ) {
            delete list[path];
        } else {
            var matched = false;
            ignore.forEach(function(mask){
                if(path.match(mask) !== null) {
                    matched = true;
                    return false;
                }
            });
            if(matched === true) {
                delete list[path];
            }
        }
    });
    return list;
};

var loc = function(isOriginRemote){
    return isOriginRemote ? 'remote' : 'local';
};

var logDiff = function(diff, simulate){
    var msg;
    if(diff.type === 'write') {
        if(diff.isOriginRemote) {
            msg = ('<< '.green) + ('↙ '.blue) + diff.query;
        } else {
            msg = ('>> '.green) + ('↗ '.blue) + diff.query;
        }
    } else {
        msg = ('✗'.red) + ' <' + loc(!diff.isOriginRemote) + '>/' + diff.query;
    }
    if(simulate === true) {
        msg += ' (simulate)';
    }
    if(diff.type === 'write') {
        console.log(msg);
    } else {
        console.log(msg.red);
    }
};

var  Options = {
    OVERWRITE_ALWAYS: 0,
    OVERWRITE_NEVER: 1,
    OVERWRITE_ASK: 2,
    OVERWRITE_IF_NEWER: 3
};
exports.Options = Options;

exports.Client = function($28, projectName, projectToken, localProjectPath){
    var vfs = new VFS($28, projectName, projectToken, localProjectPath);

    var writeLocalQuery = function(diff){
        return vfs.writeLocalQuery(diff.query).then(function(){ logDiff(diff); });
    };

    var writeRemoteQuery = function(diff){
        return vfs.writeRemoteQuery(diff.query)
        .then(function(compileError){
            logDiff(diff);
            if(compileError) {
                throw compileError;
            }
        });
    };

    var deleteLocalQuery = function(diff){
        return vfs.deleteLocalQuery(diff.query).then(function(){ logDiff(diff); });
    };

    var deleteRemoteQuery = function(diff){
        return vfs.deleteRemoteQuery(diff.query).then(function(){ logDiff(diff); });
    };

    var commit = function(simulate, diffs){
        var modulePromises = [];
        var queryPromises = [];
        diffs.forEach(function(diff){
            var container = diff.query.substring(0, 'modules'.length) === 'modules' ? modulePromises : queryPromises;
            if(simulate) {
                logDiff(diff, simulate);
            } else if(diff.type === 'write'){
                if(diff.isOriginRemote) {
                    container.push(function(){ return writeLocalQuery(diff) });
                } else {
                    container.push(function(){ return writeRemoteQuery(diff) });
                }
            } else {
                if(diff.isOriginRemote) {
                    container.push(function(){ return deleteLocalQuery(diff) });
                } else {
                    container.push(function(){ return deleteRemoteQuery(diff) });
                }
            }
        });

        var handler = function(results){
            var errors = [];
            results.forEach(function (result) {
                if (result.state !== 'fulfilled') {
                    errors.push(result.reason);
                }
            });
            if(errors.length > 0) {
                throw errors;
            }
            return results;
        };

        return [
            function(){
                var promises = [];
                modulePromises.forEach(function(promise){
                    promises.push(promise());
                });
                return Q.allSettled(promises).then(handler);
            },
            function(){
                var promises = [];
                queryPromises.forEach(function(promise){
                    promises.push(promise());
                });
                return Q.allSettled(promises).then(handler);
            }
        ].reduce(Q.when, new Q([]));
    };

    var addDiff = function(diff){
        return function(diffs){
            var defered = Q.defer();
            setTimeout(function() {
                diffs.push(diff);
                defered.resolve(diffs);
            }, 1);
            return defered.promise;
        };
    };

    var sync = function(localQueries, remoteQueries, overwrite, deleteOrphaned, simulate, isOriginRemote){
        var promises = [];
        var origin = isOriginRemote ? remoteQueries : localQueries;
        var target = isOriginRemote ? localQueries : remoteQueries;
        Object.keys(origin).forEach(function(query) {
            var targetQuery = target[query];
            var diff = {
                type: 'write',
                query: query,
                isOriginRemote: isOriginRemote
            };
            if(targetQuery) {
                var originLastModified = origin[query].lastModified;
                var targetLastModified = targetQuery.lastModified;
                if(overwrite === Options.OVERWRITE_ALWAYS) {
                    promises.push(addDiff(diff));
                } else if(overwrite === Options.OVERWRITE_IF_NEWER) {
                    if((new Date(originLastModified)).getTime() > (new Date(targetLastModified)).getTime()){
                        promises.push(addDiff(diff));
                    }
                } else if(overwrite === Options.OVERWRITE_ASK) {
                    promises.push(function (diffs) {
                        var defered = Q.defer();
                        read({
                            prompt: 'Overwrite: <' + loc(!isOriginRemote) + '>/' + query + ' (' + targetLastModified + ') with <' + loc(isOriginRemote) + '>/' + query + ' (' + originLastModified + ')? Y/[N]',
                            default: 'N'
                        }, function (er, value) {
                            if (er) {
                                defered.reject(er);
                            }
                            if (value !== undefined && value.toUpperCase() === 'Y') {
                                diffs.push(diff);
                            }
                            defered.resolve(diffs);
                        });
                        return defered.promise;
                    });
                } else if(overwrite === Options.OVERWRITE_NEVER) {
                    //Do nothing
                } else {
                    throw new Error('Invalid overwrite value: ' + overwrite);
                }
            } else {
                promises.push(addDiff(diff));
            }
        });
        if(deleteOrphaned === true) {
            Object.keys(target).forEach(function(query) {
                if(origin[query] === undefined) {
                    promises.push(addDiff({
                        type: 'delete',
                        query: query,
                        isOriginRemote: isOriginRemote
                    }));
                }
            });
        }
        promises.push(function(diffs){ return commit(simulate, diffs); });
        return promises.reduce(Q.when, new Q([]));
    };

    this.sync = function(overwrite, deleteOrphaned, simulate, ignore, isOriginRemote){
        return Q.all([
            vfs.getLocalQueries(),
            vfs.getRemoteQueries()
        ])
        .then(function(queries){
            var localQueries  = filterQueries(queries[0], ignore);
            var remoteQueries = filterQueries(queries[1], ignore);
            return sync(localQueries, remoteQueries, overwrite, deleteOrphaned, simulate, isOriginRemote);
        });
    };

    var that = this;
    this.download = function(overwrite, deleteOrphaned, simulate, ignore){
        return that.sync(overwrite, deleteOrphaned, simulate, ignore, true);
    };

    this.upload = function(overwrite, deleteOrphaned, simulate, ignore){
        return that.sync(overwrite, deleteOrphaned, simulate, ignore, false);
    };

    this.truncate = function(simulate, ignore){
        return vfs.getRemoteQueries().then(function(queries){
            var remoteQueries = filterQueries(queries, ignore);
            return sync({}, remoteQueries, Options.OVERWRITE_ALWAYS, true, simulate, false);
        });
    };
};
<|endoftext|>


<commit_before>//<!--  Contains functions to create, draw and modify towers -->

// Image paths

var imgRoundArrow = 'images/icon_5438.svg';

//

function tower(posX,posY,type){
	this.posX=posX;
	this.posY=posY;
	this.direction= 0;
	this.hitPoints=hitPoints;
	this.size= 10;
	this.image = new Image();
	this.image.src = imgRoundArrow;
	this.randomShort = 5;
	this.randomMedium = 5;
	this.randomLong = 5;

	this.drawTower=drawTower;
	function drawTower(ctx){
		ctx.save();
	  ctx.translate(this.posX, this.posY);
	  ctx.rotate(to_rad(this.direction));
		ctx.drawImage(this.image,-50,-50);
	  ctx.restore();
	};
};

<commit_msg>my_tower / Tower driver code<commit_after>//<!--  Contains functions to create, draw and modify towers -->

// Image paths

var imgRoundArrow = 'images/icon_5438.svg';

//

function tower(posX,posY,type){
	this.posX=posX;
	this.posY=posY;
	this.direction= 0;
	this.hitPoints=hitPoints;
	this.size= 10;
	this.image = new Image();
	this.image.src = imgRoundArrow;
	this.randomShort = 5;
	this.randomMedium = 5;
	this.randomLong = 5;

	this.drawTower=drawTower;
	function drawTower(ctx){
		ctx.save();
	  ctx.translate(this.posX, this.posY);
	  ctx.rotate(to_rad(this.direction));
		ctx.drawImage(this.image,-50,-50);
	  ctx.restore();
	};
};

var towers = [];

var my_tower = new tower(500,500,180,10);

towers.push(my_tower)<|endoftext|>


<commit_before>/** @jsx React.DOM */
var React = require('react');

function isTabNode(node) {
	return node.nodeName === 'LI' && node.getAttribute('role') === 'tab';
}

module.exports = React.createClass({
	propTypes: {
		selectedIndex: React.PropTypes.number,
		onSelectedChange: React.PropTypes.func
	},

	getInitialState: function () {
		return {
			selectedIndex: -1
		};
	},

	setSelected: function (index, focus) {
		// Don't do anything if nothing has changed
		if (index === this.getSelectedIndex()) return;
		// Check index boundary
		if (index < 0 || index >= this.getTabs().length) return;

		// Update selected index
		this.__lastSelectedIndex = this.getSelectedIndex();
		this.setState({ selectedIndex: index });
	},

	getSelectedIndex: function () {
		return this.state.selectedIndex;
	},

	getTabs: function () {
		return this.props.children[0].props.children;
	},

	getPanels: function () {
		return this.props.children.slice(1);
	},

	componentDidMount: function () {
		var selectedIndex = this.props.selectedIndex || 0,
			tabs = this.getTabs(),
			panels = this.getPanels();

		// Hook up relation between tabs and panels
		for (var i=0, l=tabs.length; i<l; i++) {
			var tab = tabs[i],
				panel = panels[i];

			tab.setState({
				index: i,
				panel: panel
			});

			panel.setState({
				index: i,
				tab: tab
			});
		}

		this.setSelected(selectedIndex);
	},

	componentDidUpdate: function () {
		var tabs = this.getTabs(),
			panels = this.getPanels(),
			index = this.getSelectedIndex(),
			last = this.__lastSelectedIndex;

		// Reset currently selected
		if (typeof last !== 'undefined' && last > -1) {
			tabs[last].setSelected(false);
			panels[last].setSelected(false);
			delete this.__lastSelectedIndex;
		}

		// Update selected
		tabs[index].setSelected(true, focus);
		panels[index].setSelected(true);

		// Call change event handler
		if (typeof this.props.onSelectedChange === 'function') {
			this.props.onSelectedChange(index, tabs[index], panels[index], this);
		}
	},

	handleClick: function (e) {
		if (isTabNode(e.target)) {
			this.setSelected(e.target.getAttribute('data-index'));
		}
	},

	handleKeyDown: function (e) {
		if (isTabNode(e.target)) {
			var index = this.getSelectedIndex(),
				max = this.getTabs().length - 1;

			// Select next tab to the left
			if (e.keyCode === 37 || e.keyCode === 38) {
				index -= 1;
				// Wrap back to last tab if index is negative
				if (index < 0) {
					index = max;
				}
			}
			// Select next tab to the right
			else if (e.keyCode === 39 || e.keyCode === 40) {
				index += 1;
				// Wrap back to first tab if index exceeds max
				if (index > max) {
					index = 0;
				}
			}

			this.setSelected(index, true);
		}
	},

	render: function () {
		return (

				{this.props.children}

		);
	}
});
<commit_msg>Using default props<commit_after>/** @jsx React.DOM */
var React = require('react');

function isTabNode(node) {
	return node.nodeName === 'LI' && node.getAttribute('role') === 'tab';
}

module.exports = React.createClass({
	propTypes: {
		selectedIndex: React.PropTypes.number,
		onSelectedChange: React.PropTypes.func
	},

	getDefaultProps: function () {
		return {
			selectedIndex: 0
		};
	},

	getInitialState: function () {
		return {
			selectedIndex: -1
		};
	},

	setSelected: function (index, focus) {
		// Don't do anything if nothing has changed
		if (index === this.getSelectedIndex()) return;
		// Check index boundary
		if (index < 0 || index >= this.getTabs().length) return;

		// Update selected index
		this.__lastSelectedIndex = this.getSelectedIndex();
		this.setState({ selectedIndex: index });
	},

	getSelectedIndex: function () {
		return this.state.selectedIndex;
	},

	getTabs: function () {
		return this.props.children[0].props.children;
	},

	getPanels: function () {
		return this.props.children.slice(1);
	},

	componentDidMount: function () {
		var selectedIndex = this.props.selectedIndex,
			tabs = this.getTabs(),
			panels = this.getPanels();

		// Hook up relation between tabs and panels
		for (var i=0, l=tabs.length; i<l; i++) {
			var tab = tabs[i],
				panel = panels[i];

			tab.setState({
				index: i,
				panel: panel
			});

			panel.setState({
				index: i,
				tab: tab
			});
		}

		this.setSelected(selectedIndex);
	},

	componentDidUpdate: function () {
		var tabs = this.getTabs(),
			panels = this.getPanels(),
			index = this.getSelectedIndex(),
			last = this.__lastSelectedIndex;

		// Reset currently selected
		if (typeof last !== 'undefined' && last > -1) {
			tabs[last].setSelected(false);
			panels[last].setSelected(false);
			delete this.__lastSelectedIndex;
		}

		// Update selected
		tabs[index].setSelected(true, focus);
		panels[index].setSelected(true);

		// Call change event handler
		if (typeof this.props.onSelectedChange === 'function') {
			this.props.onSelectedChange(index, tabs[index], panels[index], this);
		}
	},

	handleClick: function (e) {
		if (isTabNode(e.target)) {
			this.setSelected(e.target.getAttribute('data-index'));
		}
	},

	handleKeyDown: function (e) {
		if (isTabNode(e.target)) {
			var index = this.getSelectedIndex(),
				max = this.getTabs().length - 1;

			// Select next tab to the left
			if (e.keyCode === 37 || e.keyCode === 38) {
				index -= 1;
				// Wrap back to last tab if index is negative
				if (index < 0) {
					index = max;
				}
			}
			// Select next tab to the right
			else if (e.keyCode === 39 || e.keyCode === 40) {
				index += 1;
				// Wrap back to first tab if index exceeds max
				if (index > max) {
					index = 0;
				}
			}

			this.setSelected(index, true);
		}
	},

	render: function () {
		return (

				{this.props.children}

		);
	}
});
<|endoftext|>


<commit_before>var MongoClient = require('mongodb').MongoClient;

/**
 * search all talks
 * @param indexpath full-text index path string
 * @param callback  function to execute with the resulting data
 */
exports.search = function(index, q, callback) {
    "use strict";
    var si = require('search-index')({
        indexPath: index
    });
    si.search(q, function(err, results) {
        if (err) {
            throw new Error(err);
        }
        return callback(null, results);
    });
};

/**
 * get all the talks
 * @param dburl     database url string
 * @param callback  function to execute with the resulting data
 */
exports.all = function(dburl, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.
        find({}).
        toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get the latest talks
 * @param dburl     database url string
 * @param quantity  number of results to get
 * @param callback  function to execute with the resulting data
 */
exports.latest = function(dburl, quantity, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.
        find({}).
        sort({
            created: -1
        }).
        limit(quantity).
        toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get the most popular talks
 * @param dburl     database url string
 * @param quantity  number of results to get
 * @param callback  function to execute with the resulting data
 */
exports.popular = function(dburl, quantity, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.
        find({}).
        sort({
            votesCount: -1,
            viewCount: -1
        }).
        limit(quantity).
        toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * create a new talk
 * @param dburl     database url string
 * @param obj       number of results to get
 * @param callback  function to execute with the resulting data
 */
exports.createTalk = function(dburl, obj, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.insert(obj, function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * delete a talk by its id
 * @param dburl     database url string
 * @param id        talk id string
 * @param callback  function to execute with the resulting data
 */
exports.deleteTalk = function(dburl, id, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.remove({
            id: id
        }, function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get a talk by its id
 * @param dburl     database url string
 * @param id        talk id string
 * @param callback  function to execute with the resulting data
 */
exports.get = function(dburl, id, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.findOne({
            id: id
        }, function(err, doc) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, doc);
        });
    });
};

/**
 * upvote a talk
 * @param dburl     database url string
 * @param id        Talk id
 * @param userid    User that upvotes the talk
 * @param callback  function to execute with the resulting data
 */
exports.upvote = function(dburl, id, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.update({
            "id": id,
            "votes": {
                "$ne": userid
            }
        }, {
            "$inc": {
                "voteCount": 1
            },
            "$push": {
                "votes": userid
            }
        }, function(err, talk) {
            if (err) {
                return callback(err, null);
            }
            return callback(null, talk);
        });
    });
};

/**
 * favorite a talk
 * @param dburl     database url string
 * @param id        Talk id
 * @param userid    User that favorites the talk
 * @param callback  function to execute with the resulting data
 */
exports.favorite = function(dburl, id, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.update({
            "id": id,
            "favorites": {
                "$ne": userid
            }
        }, {
            "$inc": {
                "favoriteCount": 1
            },
            "$push": {
                "favorites": userid
            }
        }, function(err, talk) {
            if (err) {
                return callback(err, null);
            }
            return callback(null, talk);
        });
    });
};

/**
 * unfavorite a talk
 * @param dburl     database url string
 * @param id        Talk id
 * @param userid    User that favorites the talk
 * @param callback  function to execute with the resulting data
 */
exports.unfavorite = function(dburl, id, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.update({
            "id": id,
            "favorites": {
                "$in": [userid]
            }
        }, {
            "$inc": {
                "favoriteCount": -1
            },
            "$pull": {
                "favorites": userid
            }
        }, function(err, talk) {
            if (err) {
                return callback(err, null);
            }
            return callback(null, talk);
        });
    });
};

/**
 * rank a a talk
 * Update raking score field
 * @param dburl     database url string
 * @param id        Talk Unique ID
 * @param score     Raking score
 * @param callback  function to execute with the resulting data
 */
exports.rank = function(dburl, id, score, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.update({
            "id": id
        }, {
            $set: {
                "ranking": score
            }
        }, function(err) {
            if (err) {
                return callback(err);
            }
            db.close();
            return callback(null);
        });
    });

};

/**
 * play a talk
 * Updates views field by 1.
 * @param dburl     database url string
 * @param slug      Talk slug
 * @param callback  function to execute with the resulting data
 */
exports.play = function(dburl, slug, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.findOne({
            "slug": slug
        }, function(err, talk) {
            if (err) {
                return callback(err, null);
            }
            talk.viewCount = talk.viewCount + 1;
            talks.update({
                "slug": slug
            }, {
                $inc: {
                    "viewCount": 1
                },
                $set: {
                    updated: Date.now()
                }
            }, function(err) {
                if (err) {
                    return callback(err, null);
                }
                db.close();
                return callback(null, talk);
            });
        });
    });
};

/**
 * get a talk by tag
 * @param dburl     database url string
 * @param tag       talk tag string
 * @param callback  function to execute with the resulting data
 */
exports.getByTag = function(dburl, tag, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            tags: tag
        }).sort({
            viewCount: -1
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
    return true;
};

/**
 * get a talk by its slug field
 * @param dburl     database url string
 * @param slug      talk slug string
 * @param callback  function to execute with the resulting data
 */
exports.getBySlug = function(dburl, slug, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            "slug": slug
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get reltated talks from a list of tags
 * @param dburl     string      database url string
 * @param id        int         referenced talk
 * @param tags      Array       list of tag strings
 * @param callback  function    to execute with the resulting data
 */
exports.related = function(dburl, id, tags, quantity, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
                "tags": {
                    $in: tags
                },
                "id": {
                    "$ne": id
                }
            })
            .limit(quantity)
            .toArray(function(err, docs) {
                if (err) {
                    return callback(err, null);
                }
                db.close();
                return callback(null, docs);
            });
    });
};

/**
 * get a talk by its id
 * @param dburl     database url string
 * @param id        author id string
 * @param callback  function to execute with the resulting data
 */
exports.getByAuthorId = function(dburl, id, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            "author.id": id
        }).sort({
            "created": -1
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get list of talks upvoted by an user
 * @param dburl     database url string
 * @param userid        author id string
 * @param callback  function to execute with the resulting data
 */
exports.getUpvotedByAuthorId = function(dburl, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            "votes": {
                "$in": [userid]
            }
        }).sort({
            "created": -1
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get list of talks favorited by an user
 * @param dburl     database url string
 * @param userid    author id string
 * @param callback  function to execute with the resulting data
 */
exports.getFavoritedByAuthorId = function(dburl, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            "favorites": {
                "$in": [userid]
            }
        }).sort({
            "created": -1
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};
<commit_msg>fixed rank method<commit_after>var MongoClient = require('mongodb').MongoClient;

/**
 * search all talks
 * @param indexpath full-text index path string
 * @param callback  function to execute with the resulting data
 */
exports.search = function(index, q, callback) {
    "use strict";
    var si = require('search-index')({
        indexPath: index
    });
    si.search(q, function(err, results) {
        if (err) {
            throw new Error(err);
        }
        return callback(null, results);
    });
};

/**
 * get all the talks
 * @param dburl     database url string
 * @param callback  function to execute with the resulting data
 */
exports.all = function(dburl, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.
        find({}).
        toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get the latest talks
 * @param dburl     database url string
 * @param quantity  number of results to get
 * @param callback  function to execute with the resulting data
 */
exports.latest = function(dburl, quantity, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.
        find({}).
        sort({
            created: -1
        }).
        limit(quantity).
        toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get the most popular talks
 * @param dburl     database url string
 * @param quantity  number of results to get
 * @param callback  function to execute with the resulting data
 */
exports.popular = function(dburl, quantity, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.
        find({}).
        sort({
            votesCount: -1,
            viewCount: -1
        }).
        limit(quantity).
        toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * create a new talk
 * @param dburl     database url string
 * @param obj       number of results to get
 * @param callback  function to execute with the resulting data
 */
exports.createTalk = function(dburl, obj, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.insert(obj, function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * delete a talk by its id
 * @param dburl     database url string
 * @param id        talk id string
 * @param callback  function to execute with the resulting data
 */
exports.deleteTalk = function(dburl, id, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.remove({
            id: id
        }, function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get a talk by its id
 * @param dburl     database url string
 * @param id        talk id string
 * @param callback  function to execute with the resulting data
 */
exports.get = function(dburl, id, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.findOne({
            id: id
        }, function(err, doc) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, doc);
        });
    });
};

/**
 * upvote a talk
 * @param dburl     database url string
 * @param id        Talk id
 * @param userid    User that upvotes the talk
 * @param callback  function to execute with the resulting data
 */
exports.upvote = function(dburl, id, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.update({
            "id": id,
            "votes": {
                "$ne": userid
            }
        }, {
            "$inc": {
                "voteCount": 1
            },
            "$push": {
                "votes": userid
            }
        }, function(err, talk) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, talk);
        });
    });
};

/**
 * favorite a talk
 * @param dburl     database url string
 * @param id        Talk id
 * @param userid    User that favorites the talk
 * @param callback  function to execute with the resulting data
 */
exports.favorite = function(dburl, id, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.update({
            "id": id,
            "favorites": {
                "$ne": userid
            }
        }, {
            "$inc": {
                "favoriteCount": 1
            },
            "$push": {
                "favorites": userid
            }
        }, function(err, talk) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, talk);
        });
    });
};

/**
 * unfavorite a talk
 * @param dburl     database url string
 * @param id        Talk id
 * @param userid    User that favorites the talk
 * @param callback  function to execute with the resulting data
 */
exports.unfavorite = function(dburl, id, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.update({
            "id": id,
            "favorites": {
                "$in": [userid]
            }
        }, {
            "$inc": {
                "favoriteCount": -1
            },
            "$pull": {
                "favorites": userid
            }
        }, function(err, talk) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, talk);
        });
    });
};

/**
 * rank a a talk
 * Update raking score field
 * @param dburl     database url string
 * @param id        Talk Unique ID
 * @param score     Raking score
 * @param callback  function to execute with the resulting data
 */
exports.rank = function(dburl, id, score, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.update({
            "id": id
        }, {
            $set: {
                "ranking": score
            }
        }, function(err) {
            if (err) {
                return callback(err);
            }
            db.close();
            return callback(null);
        });
    });

};

/**
 * play a talk
 * Updates views field by 1.
 * @param dburl     database url string
 * @param slug      Talk slug
 * @param callback  function to execute with the resulting data
 */
exports.play = function(dburl, slug, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.findOne({
            "slug": slug
        }, function(err, talk) {
            if (err) {
                return callback(err, null);
            }
            talk.viewCount = talk.viewCount + 1;
            talks.update({
                "slug": slug
            }, {
                $inc: {
                    "viewCount": 1
                },
                $set: {
                    updated: Date.now()
                }
            }, function(err) {
                if (err) {
                    return callback(err, null);
                }
                db.close();
                return callback(null, talk);
            });
        });
    });
};

/**
 * get a talk by tag
 * @param dburl     database url string
 * @param tag       talk tag string
 * @param callback  function to execute with the resulting data
 */
exports.getByTag = function(dburl, tag, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            tags: tag
        }).sort({
            viewCount: -1
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
    return true;
};

/**
 * get a talk by its slug field
 * @param dburl     database url string
 * @param slug      talk slug string
 * @param callback  function to execute with the resulting data
 */
exports.getBySlug = function(dburl, slug, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            "slug": slug
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get reltated talks from a list of tags
 * @param dburl     string      database url string
 * @param id        int         referenced talk
 * @param tags      Array       list of tag strings
 * @param callback  function    to execute with the resulting data
 */
exports.related = function(dburl, id, tags, quantity, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
                "tags": {
                    $in: tags
                },
                "id": {
                    "$ne": id
                }
            })
            .limit(quantity)
            .toArray(function(err, docs) {
                if (err) {
                    return callback(err, null);
                }
                db.close();
                return callback(null, docs);
            });
    });
};

/**
 * get a talk by its id
 * @param dburl     database url string
 * @param id        author id string
 * @param callback  function to execute with the resulting data
 */
exports.getByAuthorId = function(dburl, id, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            "author.id": id
        }).sort({
            "created": -1
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get list of talks upvoted by an user
 * @param dburl     database url string
 * @param userid        author id string
 * @param callback  function to execute with the resulting data
 */
exports.getUpvotedByAuthorId = function(dburl, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            "votes": {
                "$in": [userid]
            }
        }).sort({
            "created": -1
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};

/**
 * get list of talks favorited by an user
 * @param dburl     database url string
 * @param userid    author id string
 * @param callback  function to execute with the resulting data
 */
exports.getFavoritedByAuthorId = function(dburl, userid, callback) {
    "use strict";
    MongoClient.connect(dburl, function(err, db) {
        if (err) {
            return callback(err, null);
        }
        var talks = db.collection('talks');
        talks.find({
            "favorites": {
                "$in": [userid]
            }
        }).sort({
            "created": -1
        }).toArray(function(err, docs) {
            if (err) {
                return callback(err, null);
            }
            db.close();
            return callback(null, docs);
        });
    });
};
<|endoftext|>


<commit_before>"use strict";

angular.module('ya.nouislider', [])
  .value('yaNoUiSliderConfig', {})
  .directive('yaNoUiSlider', ['$timeout', '$log', 'yaNoUiSliderConfig', function($timeout, $log, yaNoUiSliderConfig) {
    function toArray(val) {
      return angular.isArray(val) ? val : [val];
    }

    function copy(val) {
      return toArray(val).slice();
    }

    function equals(a, b) {
      a = toArray(a);
      b = toArray(b);

      return a[0] === b[0] && a[1] === b[1];
    }

    function omit(object, property) {
      var keys = Object.keys(object),
        index = -1,
        length = keys.length,
        result = {};

      while (++index < length) {
        var key = keys[index];
        if (key !== property) {
          result[key] = object[key];
        }
      }
      return result;
    }

    return {
      restrict: 'A',
      require: 'yaNoUiSlider',
      scope: {
        yaNoUiSlider: '=',
        yaNoUiSliderDisabled: '=',
        yaNoUiSliderHandle1Disabled: '=',
        yaNoUiSliderHandle2Disabled: '=',
        yaNoUiSliderSlideDebounce: '@'
      },
      controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
        var that = this,
          noUiSliderElement = $element[0],
          noUiSliderEvents = $scope.$parent.$eval($attrs.yaNoUiSliderEvents),
          slideDebounceDelay = $scope.yaNoUiSliderSlideDebounce || 0,
          events = slideDebounceDelay && slideDebounceDelay === 'Infinity' ? ['change'] : ['change', 'slide'],
          noUiSliderInstance,
          origins,
          sliderScope,
          pendingSlideDebounce;

        // allow to get noUiSlider instance from outside of that directive
        that.getNoUiSlider = function() {
          return noUiSliderInstance;
        };

        function toggleDisabled(element, newValue, oldValue) {
          if (newValue !== oldValue) {
            if (newValue) {
              element.setAttribute('disabled', true);
            } else {
              element.removeAttribute('disabled');
            }
          }
        }

        function destroy() {
          sliderScope.$destroy();
          noUiSliderInstance.off('slide change update slide');
          noUiSliderInstance.destroy();
          $timeout.cancel(pendingSlideDebounce);
        }

        function createSlider() {
          function updateValue(newValue) {
            var newValueCopy = copy(newValue);
            if (!equals(newValueCopy, latestValue)) {
              latestValue = newValueCopy;
              $scope.$applyAsync(function() {
                if (angular.isArray(newValue)) {
                  if (angular.isArray($scope.yaNoUiSlider.start)) {
                    $scope.yaNoUiSlider.start[0] = newValue[0];
                    $scope.yaNoUiSlider.start[1] = newValue[1];
                  } else {
                    $scope.yaNoUiSlider.start = newValue[0];
                  }
                } else {
                  $scope.yaNoUiSlider.start = newValue;
                }
              });
            }
          }

          sliderScope = $scope.$new();
          var options = angular.extend({}, yaNoUiSliderConfig, $scope.yaNoUiSlider);
          var latestValue = copy(options.start);
          options.start = copy(options.start);
          noUiSlider.create(noUiSliderElement, options);
          origins = noUiSliderElement.getElementsByClassName('noUi-origin');
          noUiSliderInstance = noUiSliderElement.noUiSlider;

          sliderScope.$watch(function() {
            var modelValue = $scope.yaNoUiSlider.start;
            if (!equals(modelValue, latestValue)) {
              latestValue = copy(modelValue);
              noUiSliderInstance.set(copy(modelValue));
            }
            return latestValue;
          });

          angular.forEach(events, function(eventName) {
            noUiSliderInstance.on(eventName + '.internal', function(values, handle, unencoded) {
              if (eventName === 'slide' && slideDebounceDelay) {
                $timeout.cancel(pendingSlideDebounce);
                pendingSlideDebounce = $timeout(function() {
                  updateValue(unencoded);
                }, slideDebounceDelay);
              } else {
                updateValue(unencoded);
              }
            });
          });

          angular.forEach(noUiSliderEvents, function(handler, event) {
            noUiSliderInstance.on(event + '.noUiSlider', function() {
              var handlerArguments = arguments;
              $scope.$applyAsync(function() {
                handler(handlerArguments);
              });
            });
          });

          sliderScope.$watch('yaNoUiSliderDisabled', toggleDisabled.bind(undefined, noUiSliderElement));
          sliderScope.$watch('yaNoUiSliderHandle1Disabled', toggleDisabled.bind(undefined, origins[0]));
          sliderScope.$watch('yaNoUiSliderHandle2Disabled', function(newValue, oldValue) {
            if (!origins[1]) {
              return $log.warn('Warning: attempt to toggle disabled state of second handle using ya-no-ui-slider-handle2-disabled attribute in one-handle slider, nouislider-angular is ignoring such call.');
            }
            toggleDisabled(origins[1], newValue, oldValue);
          });
        }

        function initialize() {
          $scope.$watch(function() {
            return omit($scope.yaNoUiSlider, 'start');
          }, function() {
            if (noUiSliderInstance) {
              destroy();
            }
            createSlider();
          }, true);

          $scope.$on('$destroy', destroy);
        }

        var initializeWatcher = $scope.$watch('yaNoUiSlider', function(options) {
          if (options) {
            initializeWatcher();
            initialize();
          }
        });
      }]
    }
  }]);
<commit_msg>Updated event handling<commit_after>"use strict";

angular.module('ya.nouislider', [])
  .value('yaNoUiSliderConfig', {})
  .directive('yaNoUiSlider', ['$timeout', '$log', 'yaNoUiSliderConfig', function($timeout, $log, yaNoUiSliderConfig) {
    function toArray(val) {
      return angular.isArray(val) ? val : [val];
    }

    function copy(val) {
      return toArray(val).slice();
    }

    function equals(a, b) {
      a = toArray(a);
      b = toArray(b);

      return a[0] === b[0] && a[1] === b[1];
    }

    function omit(object, property) {
      var keys = Object.keys(object),
        index = -1,
        length = keys.length,
        result = {};

      while (++index < length) {
        var key = keys[index];
        if (key !== property) {
          result[key] = object[key];
        }
      }
      return result;
    }

    return {
      restrict: 'A',
      require: 'yaNoUiSlider',
      scope: {
        yaNoUiSlider: '=',
        yaNoUiSliderDisabled: '=',
        yaNoUiSliderHandle1Disabled: '=',
        yaNoUiSliderHandle2Disabled: '=',
        yaNoUiSliderSlideDebounce: '@'
      },
      controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
        var that = this,
          noUiSliderElement = $element[0],
          noUiSliderEvents = $scope.$parent.$eval($attrs.yaNoUiSliderEvents),
          slideDebounceDelay = $scope.yaNoUiSliderSlideDebounce || 0,
          events = slideDebounceDelay && slideDebounceDelay === 'Infinity' ? ['change'] : ['change', 'slide'],
          noUiSliderInstance,
          origins,
          sliderScope,
          pendingSlideDebounce;

        // allow to get noUiSlider instance from outside of that directive
        that.getNoUiSlider = function() {
          return noUiSliderInstance;
        };

        function toggleDisabled(element, newValue, oldValue) {
          if (newValue !== oldValue) {
            if (newValue) {
              element.setAttribute('disabled', true);
            } else {
              element.removeAttribute('disabled');
            }
          }
        }

        function destroy() {
          sliderScope.$destroy();
          noUiSliderInstance.off('slide change update slide');
          noUiSliderInstance.destroy();
          $timeout.cancel(pendingSlideDebounce);
        }

        function createSlider() {
          function updateValue(newValue) {
            var newValueCopy = copy(newValue);
            if (!equals(newValueCopy, latestValue)) {
              latestValue = newValueCopy;
              $scope.$applyAsync(function() {
                if (angular.isArray(newValue)) {
                  if (angular.isArray($scope.yaNoUiSlider.start)) {
                    $scope.yaNoUiSlider.start[0] = newValue[0];
                    $scope.yaNoUiSlider.start[1] = newValue[1];
                  } else {
                    $scope.yaNoUiSlider.start = newValue[0];
                  }
                } else {
                  $scope.yaNoUiSlider.start = newValue;
                }
              });
            }
          }

          sliderScope = $scope.$new();
          var options = angular.extend({}, yaNoUiSliderConfig, $scope.yaNoUiSlider);
          var latestValue = copy(options.start);
          options.start = copy(options.start);
          noUiSlider.create(noUiSliderElement, options);
          origins = noUiSliderElement.getElementsByClassName('noUi-origin');
          noUiSliderInstance = noUiSliderElement.noUiSlider;

          sliderScope.$watch(function() {
            var modelValue = $scope.yaNoUiSlider.start;
            if (!equals(modelValue, latestValue)) {
              latestValue = copy(modelValue);
              noUiSliderInstance.set(copy(modelValue));
            }
            return latestValue;
          });

          angular.forEach(events, function(eventName) {
            noUiSliderInstance.on(eventName + '.internal', function(values, handle, unencoded) {
              if (eventName === 'slide' && slideDebounceDelay) {
                $timeout.cancel(pendingSlideDebounce);
                pendingSlideDebounce = $timeout(function() {
                  updateValue(unencoded);
                }, slideDebounceDelay);
              } else {
                updateValue(unencoded);
              }
            });
          });

          angular.forEach(noUiSliderEvents, function (handler, event) {
            noUiSliderInstance.on(event + '.noUiSlider', function () {
              var handlerArguments = Array.prototype.slice.call(arguments);
              var self = this;
              $scope.$applyAsync(function () {
                handler.apply(self, handlerArguments);
              });
            });
          });

          sliderScope.$watch('yaNoUiSliderDisabled', toggleDisabled.bind(undefined, noUiSliderElement));
          sliderScope.$watch('yaNoUiSliderHandle1Disabled', toggleDisabled.bind(undefined, origins[0]));
          sliderScope.$watch('yaNoUiSliderHandle2Disabled', function(newValue, oldValue) {
            if (!origins[1]) {
              return $log.warn('Warning: attempt to toggle disabled state of second handle using ya-no-ui-slider-handle2-disabled attribute in one-handle slider, nouislider-angular is ignoring such call.');
            }
            toggleDisabled(origins[1], newValue, oldValue);
          });
        }

        function initialize() {
          $scope.$watch(function() {
            return omit($scope.yaNoUiSlider, 'start');
          }, function() {
            if (noUiSliderInstance) {
              destroy();
            }
            createSlider();
          }, true);

          $scope.$on('$destroy', destroy);
        }

        var initializeWatcher = $scope.$watch('yaNoUiSlider', function(options) {
          if (options) {
            initializeWatcher();
            initialize();
          }
        });
      }]
    }
  }]);
<|endoftext|>


<commit_before>import DataHandlerBase from '../base/DataHandlerBase.js';
import VisualBase from '../base/VisualBase.js';
import TableBase from '../base/TableBase.js';
import d3 from 'd3';
import _ from 'underscore';
import $ from 'jquery';

export function get_years (raw, Stops) {
  let years = d3.set(raw.stops.map((v) => v.year)).values();

  years.filter((v) => (v >= Stops.start_year));
  years.push("Total");

  return years;
}

export function get_totals (a, types) {
  // calculate total for all years by purpose; push to array
  let arr = _.clone(a);

  var purposes = d3.nest()
                   .key((d) => d.purpose)
                   .entries(arr);

  purposes.forEach((v) => {
    // create new totals object, and reset race/ethnicity-values
    var total = _.clone(v.values[0]);

    _.keys(total).forEach((key) => {
      if (_.some(types, (t) => t.indexOf(key) >= 0)) {
        total[key] = 0;
      }
    });

    // sum data from all years
    v.values.forEach((year) => {
      _.keys(year).forEach((key) => {
        if (_.some(types, (t) => t.indexOf(key) >= 0)) {
          total[key] += year[key];
        }
      });
    });

    total["year"] = "Total";
    arr.push(total);
  });

  return arr;
}

export const LikelihoodSearchHandlerBase = DataHandlerBase.extend({
  types: [],
  defaults: {},

  clean_data: function () {
    let raw = this.get("raw_data");
    let years = get_years(raw, this.Stops);

    if (raw.stops.length>0) {
      raw.stops = get_totals(raw.stops, this.types);
    }

    if (raw.searches.length > 0 ) {
      raw.searches = get_totals(raw.searches, this.types);
    }

    // set cleaned-data to handler
    this.set("data", {
      years: years,
      raw: raw
    });
  }
});

export const LikelihoodOfSearchBase = VisualBase.extend({
  defaults: { }, // abstract property, requires override
  _items: function () { throw "abstract method: requires override"; },
  _base: function () { throw "abstract method: requires override"; },
  _defRace: function () { throw "abstract method: requires override"; },
  triggerRaceToggle: function () { throw "abstract method: requires override"; },

  setDefaultChart: function () {
    this.chart = nv.models.multiBarHorizontalChart()
      .x((d) => d.label)
      .y((d) => d.value)
      .width(this.get("width"))
      .height(this.get("height"))
      .margin({top: 20, right: 50, bottom: 20, left: 180})
      .showValues(true)
      .tooltips(true)
      .transitionDuration(350)
      .showControls(false)
      .tooltipContent((key, y, e, graph) => `

${ key }

${ y }

${ e }

      `);

    this.chart.yAxis
        .axisLabel('Additional percentage or search by search-cause')
        .tickFormat(d3.format('%'));

    this.chart.valueFormat(d3.format('%'));
  },

  drawStartup: function () {
    // get year options for pulldown menu
    var selector = $('<select>'),
        year_options = this.data.years,
        opts = year_options.map((v) => `<option value="${v}">${v}</option>`),
        getData = () => {
          var year = selector.val();
          year = parseInt(year, 10) || year;
          this.dataset =  this._getDataset(year);
          this.drawChart();
        };

    selector
      .append(opts)
      .val("Total")
      .on('change', getData)
      .trigger('change');

    $('
')
      .html(selector)
      .appendTo(this.div);

    this.selector = selector;
  },

  drawChart: function () {
    d3.select(this.svg[0])
      .datum(this.dataset)
      .attr('width', "100%")
      .attr('height', "100%")
      .style({ width:  `${this.div.width()}px`
             , height: `${ (this.get('height') / this.get('width')) * this.div.width() }px` })
      .attr('preserveAspectRatio', "xMinYMin")
      .attr('viewBox', `0 0 ${this.get('width')} ${this.get('height')}`)
      .call(this.chart);

    nv.utils.windowResize(this.chart.update);
  },

  _getDataset: function (year) {
    var dataset = [],
        raw = this.data.raw,
        stops_arr = raw.stops.filter((v) => v.year === year),
        searches_arr = raw.searches.filter((v) => v.year === year),
        stops = d3.map(),
        searches = d3.map(),
        items = this._items(),
        base = this._base(),
        defRace = this._defRace(),
        baseUpper = ((d) => d.charAt(0).toUpperCase() + d.slice(1))(base);

    // turn arrays into maps with purpose as the key
    stops_arr.forEach((v) => {
      stops.set(v.purpose, v);
    });
    searches_arr.forEach((v) => {
      searches.set(v.purpose, v);
    });

    // build a set of bars for each race, except for base
    items.forEach((race, i) => {
      if (race === base) return;

      var bar = {
          color: this.Stops.colors[i],
          key: `${this._pprint(race)} vs. ${baseUpper}`,
          values: [],
          disabled: (race !== defRace)
      };

      // build a bar for each violation
      this.Stops.purpose_order.forEach((purpose) => {
        // optional reporting requirement; remove as it's generally unreported
        if (purpose === "Checkpoint") return;

        // calculate percent-difference of stops which led to searches by race,
        // in comparison to base-baseline
        var search = searches.get(purpose),
            stop  = stops.get(purpose);

        if (search && stop){

          var rate, base_rate, r_rate,
              base_se = search[base] || 0,
              base_st = stop[base] || 0,
              r_se = search[race] || 0,
              r_st = stop[race] || 0;

          base_rate = base_se/base_st;
          r_rate = r_se/r_st;
          rate = (r_rate-base_rate)/base_rate;
          if(!r_rate || !isFinite(rate)) rate = 0;

          // add purpose to list of values
          bar.values.push({
            label: purpose,
            value: rate,
            order: this.Stops.purpose_order.get(purpose)
          });
        }
      });

      // sort bars and then push race to list
      bar.values.sort((a,b) => a.order - b.order);
      dataset.push(bar);
    });

    return dataset;
  }
});

export const LikelihoodSearchTableBase = TableBase.extend({
  Stops: { }, // abstract property, requires override
  types: [],
  _get_header_rows: function () { throw "abstract method: requires override"; },

  get_tabular_data: function () {
    var header, row, rows = [];

    // create header
    header = ["Year", "Stop-reason"];
    header.push.apply(header, this._get_header_rows());
    rows.push(header);

    var stop, search, stop_purp, search_purp, v1, v2,
        purposes = this.Stops.purpose_order.keys(),
        stops = this.data.raw.stops,
        searches = this.data.raw.searches,
        get_row = (stops, searches, term) => {
          var stop = (stops !== undefined) ? stops[term] : 0,
              search = (searches !== undefined) ? searches[term] : 0;
          return `${search}/${stop}`;
        };

    // create data rows
    this.data.years.forEach((yr) => {
        stop = stops.filter((d) => d.year == yr);
        search = searches.filter((d) => d.year == yr);
        purposes.forEach((purp) => {
          row = [yr, purp];
          stop_purp = (stop.length > 0) ? stop.filter((d) =>  d.purpose == purp) : undefined;
          search_purp = (search.length > 0) ? search.filter((d) => d.purpose == purp) : undefined;
          stop_purp = (stop_purp && stop_purp.length === 1) ? stop_purp[0] : undefined;
          search_purp = (search_purp && search_purp.length === 1) ? search_purp[0] : undefined;

          this.types.forEach((type) => {
            type.forEach((r) => {
              row.push(get_row(stop_purp, search_purp, r));
            })
          })

          rows.push(row);
        });
    });

    return rows;
  }
});
<commit_msg>Stylistic changes to LikelihoodSearchTableBase to improve readability<commit_after>import DataHandlerBase from '../base/DataHandlerBase.js';
import VisualBase from '../base/VisualBase.js';
import TableBase from '../base/TableBase.js';
import d3 from 'd3';
import _ from 'underscore';
import $ from 'jquery';

export function get_years (raw, Stops) {
  let years = d3.set(raw.stops.map((v) => v.year)).values();

  years.filter((v) => (v >= Stops.start_year));
  years.push("Total");

  return years;
}

export function get_totals (a, types) {
  // calculate total for all years by purpose; push to array
  let arr = _.clone(a);

  var purposes = d3.nest()
                   .key((d) => d.purpose)
                   .entries(arr);

  purposes.forEach((v) => {
    // create new totals object, and reset race/ethnicity-values
    var total = _.clone(v.values[0]);

    _.keys(total).forEach((key) => {
      if (_.some(types, (t) => t.indexOf(key) >= 0)) {
        total[key] = 0;
      }
    });

    // sum data from all years
    v.values.forEach((year) => {
      _.keys(year).forEach((key) => {
        if (_.some(types, (t) => t.indexOf(key) >= 0)) {
          total[key] += year[key];
        }
      });
    });

    total["year"] = "Total";
    arr.push(total);
  });

  return arr;
}

export const LikelihoodSearchHandlerBase = DataHandlerBase.extend({
  types: [],
  defaults: {},

  clean_data: function () {
    let raw = this.get("raw_data");
    let years = get_years(raw, this.Stops);

    if (raw.stops.length>0) {
      raw.stops = get_totals(raw.stops, this.types);
    }

    if (raw.searches.length > 0 ) {
      raw.searches = get_totals(raw.searches, this.types);
    }

    // set cleaned-data to handler
    this.set("data", {
      years: years,
      raw: raw
    });
  }
});

export const LikelihoodOfSearchBase = VisualBase.extend({
  defaults: { }, // abstract property, requires override
  _items: function () { throw "abstract method: requires override"; },
  _base: function () { throw "abstract method: requires override"; },
  _defRace: function () { throw "abstract method: requires override"; },
  triggerRaceToggle: function () { throw "abstract method: requires override"; },

  setDefaultChart: function () {
    this.chart = nv.models.multiBarHorizontalChart()
      .x((d) => d.label)
      .y((d) => d.value)
      .width(this.get("width"))
      .height(this.get("height"))
      .margin({top: 20, right: 50, bottom: 20, left: 180})
      .showValues(true)
      .tooltips(true)
      .transitionDuration(350)
      .showControls(false)
      .tooltipContent((key, y, e, graph) => `

${ key }

${ y }

${ e }

      `);

    this.chart.yAxis
        .axisLabel('Additional percentage or search by search-cause')
        .tickFormat(d3.format('%'));

    this.chart.valueFormat(d3.format('%'));
  },

  drawStartup: function () {
    // get year options for pulldown menu
    var selector = $('<select>'),
        year_options = this.data.years,
        opts = year_options.map((v) => `<option value="${v}">${v}</option>`),
        getData = () => {
          var year = selector.val();
          year = parseInt(year, 10) || year;
          this.dataset =  this._getDataset(year);
          this.drawChart();
        };

    selector
      .append(opts)
      .val("Total")
      .on('change', getData)
      .trigger('change');

    $('
')
      .html(selector)
      .appendTo(this.div);

    this.selector = selector;
  },

  drawChart: function () {
    d3.select(this.svg[0])
      .datum(this.dataset)
      .attr('width', "100%")
      .attr('height', "100%")
      .style({ width:  `${this.div.width()}px`
             , height: `${ (this.get('height') / this.get('width')) * this.div.width() }px` })
      .attr('preserveAspectRatio', "xMinYMin")
      .attr('viewBox', `0 0 ${this.get('width')} ${this.get('height')}`)
      .call(this.chart);

    nv.utils.windowResize(this.chart.update);
  },

  _getDataset: function (year) {
    var dataset = [],
        raw = this.data.raw,
        stops_arr = raw.stops.filter((v) => v.year === year),
        searches_arr = raw.searches.filter((v) => v.year === year),
        stops = d3.map(),
        searches = d3.map(),
        items = this._items(),
        base = this._base(),
        defRace = this._defRace(),
        baseUpper = ((d) => d.charAt(0).toUpperCase() + d.slice(1))(base);

    // turn arrays into maps with purpose as the key
    stops_arr.forEach((v) => {
      stops.set(v.purpose, v);
    });
    searches_arr.forEach((v) => {
      searches.set(v.purpose, v);
    });

    // build a set of bars for each race, except for base
    items.forEach((race, i) => {
      if (race === base) return;

      var bar = {
          color: this.Stops.colors[i],
          key: `${this._pprint(race)} vs. ${baseUpper}`,
          values: [],
          disabled: (race !== defRace)
      };

      // build a bar for each violation
      this.Stops.purpose_order.forEach((purpose) => {
        // optional reporting requirement; remove as it's generally unreported
        if (purpose === "Checkpoint") return;

        // calculate percent-difference of stops which led to searches by race,
        // in comparison to base-baseline
        var search = searches.get(purpose),
            stop  = stops.get(purpose);

        if (search && stop){

          var rate, base_rate, r_rate,
              base_se = search[base] || 0,
              base_st = stop[base] || 0,
              r_se = search[race] || 0,
              r_st = stop[race] || 0;

          base_rate = base_se/base_st;
          r_rate = r_se/r_st;
          rate = (r_rate-base_rate)/base_rate;
          if(!r_rate || !isFinite(rate)) rate = 0;

          // add purpose to list of values
          bar.values.push({
            label: purpose,
            value: rate,
            order: this.Stops.purpose_order.get(purpose)
          });
        }
      });

      // sort bars and then push race to list
      bar.values.sort((a,b) => a.order - b.order);
      dataset.push(bar);
    });

    return dataset;
  }
});

export const LikelihoodSearchTableBase = TableBase.extend({
  Stops: { }, // abstract property, requires override
  types: [],
  _get_header_rows: function () { throw "abstract method: requires override"; },

  get_tabular_data: function () {
    // create row with initial header row
    let rows = [
      ["Year", "Stop-reason"].concat(this._get_header_rows())
    ];

    let purposes = this.Stops.purpose_order.keys();
    let stops = this.data.raw.stops;
    let searches = this.data.raw.searches;

    function create_cell (stop_counts={}, search_counts={}, race) {
      let stop_count = stop_counts[race] || 0;
      let search_count = search_counts[race] || 0;

      return `${search_count}/${stop_count}`;
    }

    // create data rows
    this.data.years.forEach((yr) => {
        let stops_by_yr = stops.filter((d) => d.year == yr);
        let searches_by_yr = searches.filter((d) => d.year == yr);

        purposes.forEach((purp) => {
          let row = [yr, purp];
          let stop_counts = _.find(stops_by_yr, (d) =>  d.purpose == purp);
          let search_counts = _.find(searches_by_yr, (d) => d.purpose == purp);

          this.types.forEach((type) => {
            type.forEach((race) => {
              row.push(create_cell(stop_counts, search_counts, race));
            })
          })

          rows.push(row);
        });
    });

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


<commit_before>function flash(msg, category) {
    var num = window.clear_wallet.last_err++;
    category = category || "success";
    //
{{ message }}

    $err = $('
' + msg + '
');
    $('#flashes').append($err);
    setTimeout(function () {
        $err.slideUp("slow", function() {
            $err.remove();
        });
    }, 1000 * 2);
}

function pull_data() {
    $('#spinner').slideDown();
    $.get('/data.json', function (data) {
        if (data == null || data.coins == null || data.transactions == null) {
            flash(
                "Something went wrong querying the server.
"
                + "Retry by pressing the red RETRY button.",
                "error"
            );
            $('#spinner').slideUp();
            $('#retry-query').slideDown();
            return;
        }
        $('#block-address .my-addr').text(data.coins.addr);
        $('#block-address .my-coins').text(data.coins.amount);
        for (var i = data.transactions.transactions.length - 1; i >= 0; i--) {
            var d = data.transactions.transactions[i];
            var $tr = $('
');
            var $me_span = $('').append($('You'));
            $me_span.click(my_addr_hook);
            if (d.to == window.clear_wallet.addr) {
                $tr.append($('').append($me_span));
            } else {
                $tr.append($('').html(d.to));
            }
            if (d.from == window.clear_wallet.addr) {
                $tr.append($('').append($me_span));
            } else {
                $tr.append($('').html(d.from));
            }
            $tr.append($('').html(d.amount));
            $('#block-transactions-body').append($tr);
        };
        $('#spinner').slideUp();
    });
}

window.clear_wallet = window.clear_wallet || {};
window.clear_wallet.last_id = 0;
window.clear_wallet.last_err = 0;
window.clear_wallet.is_main_page = false;

function my_addr_hook() {
    prompt("Here is your address: (Ctrl-C to copy)", window.clear_wallet.addr);
}

$(document).ready(function() {
	if (!window.clear_wallet.is_main_page) {
		return;
	}
    $('#retry-query').click(function () {
        $(this).slideUp();
        pull_data();
    });
    $('#refresh-query').click(function () {
    	pull_data();
    });
    $(".my-addr").click(my_addr_hook);
    pull_data();
});<commit_msg>Fixed bug with refreshing<commit_after>function flash(msg, category) {
    var num = window.clear_wallet.last_err++;
    category = category || "success";
    //
{{ message }}

    $err = $('
' + msg + '
');
    $('#flashes').append($err);
    setTimeout(function () {
        $err.slideUp("slow", function() {
            $err.remove();
        });
    }, 1000 * 2);
}

function pull_data() {
    $('#spinner').slideDown();
    $.get('/data.json', function (data) {
        if (data == null || data.coins == null || data.transactions == null) {
            flash(
                "Something went wrong querying the server.
"
                + "Retry by pressing the red RETRY button.",
                "error"
            );
            $('#spinner').slideUp();
            $('#retry-query').slideDown();
            return;
        }
        $('#block-address .my-addr').text(data.coins.addr);
        $('#block-address .my-coins').text(data.coins.amount);
        $('#block-transactions-body').empty();
        for (var i = data.transactions.transactions.length - 1; i >= 0; i--) {
            var d = data.transactions.transactions[i];
            var $tr = $('
');
            var $me_span = $('').append($('You'));
            $me_span.click(my_addr_hook);
            if (d.to == window.clear_wallet.addr) {
                $tr.append($('').append($me_span));
            } else {
                $tr.append($('').html(d.to));
            }
            if (d.from == window.clear_wallet.addr) {
                $tr.append($('').append($me_span));
            } else {
                $tr.append($('').html(d.from));
            }
            $tr.append($('').html(d.amount));
            $('#block-transactions-body').append($tr);
        };
        $('#spinner').slideUp();
    });
}

window.clear_wallet = window.clear_wallet || {};
window.clear_wallet.last_id = 0;
window.clear_wallet.last_err = 0;
window.clear_wallet.is_main_page = false;

function my_addr_hook() {
    prompt("Here is your address: (Ctrl-C to copy)", window.clear_wallet.addr);
}

$(document).ready(function() {
	if (!window.clear_wallet.is_main_page) {
		return;
	}
    $('#retry-query').click(function () {
        $(this).slideUp();
        pull_data();
    });
    $('#refresh-query').click(function () {
    	pull_data();
    });
    $(".my-addr").click(my_addr_hook);
    pull_data();
});<|endoftext|>


<commit_before>var searchFavorites = function(query){
    var feedback = [];
    var resultList = localStorage.getItem("results");
    _.each(resultList.businesses, function(x){
        if(x.name.search(query) > -1 || x.tag.search(query) > -1 || x.notes.search(query) > -1){
            feedback.push(x);
        }
    });
    return feedback;
};
var getFavoriteCategories = function(){
    var feedback = [];
    var resultList = localStorage.getItem("results");
    //returns the list of lists (of categories); from here Varun will try to find the broad-level category that this category belongs to
    _.each(resultList.businesses, function(x){
       feedback.push(x.categories);
    }
 );
    return feedback;
};
var getFavoritesWithinCategory = function(query){
    var feedback = [];
    var resultList = localStorage.getItem("results");

   _.each(resultList.businesses, function(x){
        if(x.categories == query){
            feedback.push(x);
        }
    });
    return feedback;
};

function addBusinessToFavorite (business){
    var resultList = [];
    if(typeof localStorage.getItem("results") != 'undefined'){
        resultList = localStorage.getItem("results");
   }
     resultList.push(business);
     localStorage.setItem("results", resultList);
};
function deleteBusinessFromStorage(business){
    var resultList = localStorage.getItem("results");
    resultList.remove(business);
    localStorage.setItem("results", resultList);
};<commit_msg>fixed for loops and remove<commit_after>var searchFavorites = function(query){
    var feedback = [];
    var resultList = localStorage.getItem("results");
    _.each(resultList.businesses, function(x){
        if(x.name.search(query) > -1 || x.tag.search(query) > -1 || x.notes.search(query) > -1){
            feedback.push(x);
        }
    });
    return feedback;
};
var getFavoriteCategories = function(){
    var feedback = [];
    var resultList = localStorage.getItem("results");
    //returns the list of lists (of categories); from here Varun will try to find the broad-level category that this category belongs to
    _.each(resultList.businesses, function(x){
       feedback.push(x.categories);
    }
 );
    return feedback;
};
var getFavoritesWithinCategory = function(query){
    var feedback = [];
    var resultList = localStorage.getItem("results");

   _.each(resultList.businesses, function(x){
        if(x.categories == query){
            feedback.push(x);
        }
    });
    return feedback;
};
function addBusinessToFavorite (business){
    var resultList = [];
    if(typeof localStorage.getItem("results") != 'undefined'){
        resultList = localStorage.getItem("results");
   }
     resultList.push(business);
     localStorage.setItem("results", resultList);
}
function deleteBusinessFromStorage(business){
    var resultList = localStorage.getItem("results");
    removeA(resultList, business)
    localStorage.setItem("results", resultList);
}
function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}<|endoftext|>