<commit_before>"use strict";

var request = require('request');

module.exports = function (RED) {

  function HTTPRequest(n) {
    RED.nodes.createNode(this, n);
    var node           = this;
    var nodeUrl        = n.url;
    var isTemplatedUrl = (nodeUrl || "").indexOf("{{") != -1;
    var nodeMethod     = "POST";

    this.messageType   = n.messageType;
    this.token         = n.token;
    this.device        = n.device;
    this.mode          = n.mode || "sync";

    if (n.tls) {
      var tlsNode = RED.nodes.getNode(n.tls);
    }
    this.ret = n.ret || "txt";
    if (RED.settings.httpRequestTimeout) {
      this.reqTimeout = parseInt(RED.settings.httpRequestTimeout) || 120000;
    } else {
      this.reqTimeout = 120000;
    }

    this.on("input", function (msg) {

	// Check if the payload is a single message or multiple messages in an array,
	// SCP IoT Service always expects and array, so wrap single messages in an array.
      var payload = {};
      payload["mode"] = n.mode || "sync";
      payload["messageType"] = n.messageType;
      payload["Authorization"] = "Bearer " + n.token;
      if (Object.prototype.toString.call(msg.payload) == '[object Array]') {
        payload["messages"] = msg.payload;
      } else {
        payload["messages"] = [];
        payload["messages"][0] = msg.payload;
      }

      msg.payload = payload;

      var preRequestTimestamp = process.hrtime();
      node.status({
        fill: "blue",
        shape: "dot",
        text: "httpin.status.requesting"
      });

      var messageType	= n.messageType || msg.messageType;
      var token         = n.token || msg.token;
      var device        = n.device || msg.device;
      var mode          = n.mode || msg.mode || "sync";

      // concatenate URL with device ID
      var url 			= nodeUrl || msg.url;
      url 				= nodeUrl + device;

      if (msg.url && nodeUrl && (nodeUrl !== msg.url)) { // revert change below when warning is finally removed
        node.warn(RED._("common.errors.nooverride"));
      }
      if (isTemplatedUrl) {
        url = mustache.render(nodeUrl, msg);
      }
      if (!url) {
        node.error(RED._("httpin.errors.no-url"), msg);
        node.status({
          fill: "red",
          shape: "ring",
          text: (RED._("httpin.errors.no-url"))
        });
        return;
      }
      // url must start http:// or https:// so assume http:// if not set
      if (!((url.indexOf("http://") === 0) || (url.indexOf("https://") === 0))) {
        if (tlsNode) {
          url = "https://" + url;
        } else {
          url = "http://" + url;
        }
      }
	// Only post is accepted from the SCP IoT Service
      var method = nodeMethod.toUpperCase() || "POST";
      var opts = {
        method: method,
        url: url,
        timeout: node.reqTimeout,
        headers: {}
      };

      if (msg.headers) {
        for (var v in msg.headers) {
          if (msg.headers.hasOwnProperty(v)) {
            var name = v.toLowerCase();
            if (name !== "content-type" && name !== "content-length") {
              // only normalise the known headers used later in this
              // function. Otherwise leave them alone.
              name = v;
            }
            opts.headers[name] = msg.headers[v];
          }
        }
      }

    // Add the oAuth Token to the header
      opts.headers["Authorization"] = "Bearer " + n.token;

      if (msg.payload && (method == "POST" || method == "PUT" || method == "PATCH")) {
        if (opts.headers['content-type'] == 'application/x-www-form-urlencoded') {
          opts.form = msg.payload;
        } else {
          if (typeof msg.payload === "string" || Buffer.isBuffer(msg.payload)) {
            opts.body = msg.payload;
          } else if (typeof msg.payload == "number") {
            opts.body = msg.payload + "";
          } else {
            opts.body = JSON.stringify(msg.payload);
            if (opts.headers['content-type'] == null) {

              opts.headers['content-type'] = "application/json;charset=utf-8";
            }
          }
        }
      }

      if (this.credentials && this.credentials.user) {
        opts.auth = {
          user: this.credentials.user,
          pass: this.credentials.password,
          sendImmediately: false
        }
      }

      if (tlsNode) {
        tlsNode.addTLSOptions(opts);
      }
      msg["opts"] = opts;
      request(opts, function (error, response, body) {
        node.status({});
        if (error) {
          if (error.code === 'ETIMEDOUT') {
            node.error(RED._("common.notification.errors.no-response"), msg);
            setTimeout(function () {
              node.status({
                fill: "red",
                shape: "ring",
                text: "common.notification.errors.no-response"
              });
            }, 10);
          } else {
            node.error(error, msg);
            msg.payload = error.toString() + " : " + url;
            msg.statusCode = error.code;
            node.send(msg);
            node.status({
              fill: "red",
              shape: "ring",
              text: error.code
            });
          }
        } else {
          msg.payload = body;
          msg.headers = response.headers;
          msg.statusCode = response.statusCode;
          if (node.metric()) {
            // Calculate request time
            var diff = process.hrtime(preRequestTimestamp);
            var ms = diff[0] * 1e3 + diff[1] * 1e-6;
            var metricRequestDurationMillis = ms.toFixed(3);
            node.metric("duration.millis", msg, metricRequestDurationMillis);
            if (response.connection && response.connection.bytesRead) {
              node.metric("size.bytes", msg, response.connection.bytesRead);
            }
          }
          if (node.ret === "bin") {
            msg.payload = new Buffer(msg.payload, "binary");
          } else if (node.ret === "obj") {
            try {
              msg.payload = JSON.parse(msg.payload);
            } catch (e) {
              node.warn(RED._("httpin.errors.json-error"));
            }
          }
          node.send(msg);
        }
      })
    });
  }

  RED.nodes.registerType("scp-iot-http", HTTPRequest, {
    credentials: {
      user: {
        type: "text"
      },
      password: {
        type: "password"
      }
    },
    device: {
      type: "text"
    },
    token: {
      type: "text"
    },
    messageType: {
      type: "text"
    }
  });
}
<commit_msg>Delete scp-iot-http.js<commit_after><|endoftext|>


<commit_before><commit_msg>1.8v jquery that works better with the flot library..<commit_after><|endoftext|>


<commit_before>/* ******* EVENTS ******* */

Mod['Events'] = {
    '_define' : function(){
        var that = this;
        if(!that.data['params']['events']){
            that.data['params']['events'] = {};
        }
        that.extendObject['events'] = that.data['events'];
        that.extendObject['eventsStack'] = {};
        cm.forEach(that.data['events'], function(item){
            that.extendObject['eventsStack'][item] = [];
            that.extendObject[item] = function(handler){
                var that = this;
                that.addEvent(item, handler);
                return that;
            };
        });
    },
    'addEvent' : function(event, handler){
        var that = this;
        that.eventsStack = cm.clone(that.eventsStack);
        if(that.eventsStack[event]){
            if(typeof handler == 'function'){
                that.eventsStack[event].push(handler);
            }else{
                cm.errorLog({
                    'name' : that.className,
                    'message' : ['Handler of event', cm.strWrap(event, '"'), 'must be a function.'].join(' ')
                });
            }
        }else{
            cm.errorLog({
                'name' : that.className,
                'message' : [cm.strWrap(event, '"'), 'does not exists.'].join(' ')
            });
        }
        return that;
    },
    'addEvents' : function(o){
        var that = this;
        if(o){
            that.convertEvents(o);
        }
        return that;
    },
    'removeEvent' : function(event, handler){
        var that = this;
        that.eventsStack = cm.clone(that.eventsStack);
        if(that.eventsStack[event]){
            if(typeof handler == 'function'){
                that.eventsStack[event] = that.eventsStack[event].filter(function(item){
                    return item != handler;
                });
            }else{
                cm.errorLog({
                    'name' : that.className,
                    'message' : ['Handler of event', cm.strWrap(event, '"'), 'must be a function.'].join(' ')
                });
            }
        }else{
            cm.errorLog({
                'name' : that.className,
                'message' : [cm.strWrap(event, '"'), 'does not exists.'].join(' ')
            });
        }
        return that;
    },
    'triggerEvent' : function(event, params){
        var that = this;
        if(that.eventsStack[event]){
            cm.forEach(that.eventsStack[event], function(item){
                item(that, params || {});
            });
        }else{
            cm.errorLog({
                'name' : that.className,
                'message' : [cm.strWrap(event, '"'), 'does not exists.'].join(' ')
            });
        }
        return that;
    },
    'convertEvents' : function(o){
        var that = this;
        cm.forEach(o, function(item, key){
            that.addEvent(key, item);
        });
        return that;
    }
};

/* ******* LANGS ******* */

Mod['Langs'] = {
    '_define' : function(){
        var that = this;
        if(!that.data['params']['langs']){
            that.data['params']['langs'] = {};
        }
    },
    'lang' : function(str){
        var that = this;
        if(!that.params['langs'][str]){
            that.params['langs'][str] = str;
        }
        return that.params['langs'][str];
    }
};

/* ******* DATA CONFIG ******* */

Mod['DataConfig'] = {
    '_define' : function(){
        var that = this;
        if(typeof that.data['params']['configDataMarker'] == 'undefined'){
            that.data['params']['configDataMarker'] = 'data-config';
        }
    },
    'getDataConfig' : function(container, dataMarker){
        var that = this,
            sourceConfig;
        if(cm.isNode(container)){
            dataMarker = dataMarker || that.params['configDataMarker'];
            sourceConfig = container.getAttribute(dataMarker);
            if(sourceConfig && (sourceConfig = JSON.parse(sourceConfig))){
                that.params = cm.merge(that.params, sourceConfig);
            }
        }
        return that;
    },
    'getNodeDataConfig' : function(node, dataMarker){
        var that = this,
            sourceConfig;
        if(cm.isNode(node)){
            dataMarker = dataMarker || that.params['configDataMarker'];
            sourceConfig = node.getAttribute(dataMarker);
            if(sourceConfig && (sourceConfig = JSON.parse(sourceConfig))){
                return cm.merge(that.params, sourceConfig);
            }
        }
        return {};
    }
};

/* ******* DATA NODES ******* */

Mod['DataNodes'] = {
    '_define' : function(){
        var that = this;
        if(!that.data['params']['nodes']){
            that.data['params']['nodes'] = {};
        }
        if(typeof that.data['params']['nodesDataMarker'] == 'undefined'){
            that.data['params']['nodesDataMarker'] = 'data-node';
        }
        if(typeof that.data['params']['nodesMarker'] == 'undefined'){
            that.data['params']['nodesMarker'] = that.classNameShort;
        }
        if(!that.extendObject['nodes']){
            that.extendObject['nodes'] = {};
        }
    },
    'getDataNodes' : function(container, dataMarker, className){
        var that = this,
            sourceNodes = {};
        container = typeof container == 'undefined'? document.body : container;
        if(container){
            dataMarker = typeof dataMarker == 'undefined'? that.params['nodesDataMarker'] : dataMarker;
            className = typeof className == 'undefined'? that.params['nodesMarker'] : className;
            if(className){
                sourceNodes = cm.getNodes(container, dataMarker)[className] || {};
            }else{
                sourceNodes = cm.getNodes(container, dataMarker);
            }
            that.nodes = cm.merge(that.nodes, sourceNodes);
        }
        that.nodes = cm.merge(that.nodes, that.params['nodes']);
        return that;
    }
};

/* ******* LOCAL STORAGE ******* */

Mod['Storage'] = {
    '_define' : function(){
        var that = this;
        if(!that.data['params']['name']){
            that.data['params']['name'] = '';
        }
    },
    'storageRead' : function(key){
        var that = this,
            storage = JSON.parse(cm.storageGet(that.className)) || {};
        if(cm.isEmpty(that.params['name'])){
            cm.errorLog({
                'name' : that.className,
                'message' : 'Storage cannot be read because "name" parameter not provided.'
            });
            return null;
        }
        if(!storage[that.params['name']] || typeof storage[that.params['name']][key] == 'undefined'){
            cm.errorLog({
                'type' : 'attention',
                'name' : that.className,
                'message' : ['Parameter', cm.strWrap(key, '"'), 'does not exist or is not set.'].join(' ')
            });
            return null;
        }
        return storage[that.params['name']][key];
    },
    'storageReadAll' : function(){
        var that = this,
            storage = JSON.parse(cm.storageGet(that.className)) || {};
        if(cm.isEmpty(that.params['name'])){
            cm.errorLog({
                'name' : that.className,
                'message' : 'Storage cannot be read because "name" parameter not provided.'
            });
            return {};
        }
        if(!storage[that.params['name']]){
            cm.errorLog({
                'type' : 'attention',
                'name' : that.className,
                'message' : 'Storage is empty.'
            });
            return {};
        }
        return storage[that.params['name']];
    },
    'storageWrite' : function(key, value){
        var that = this,
            storage = JSON.parse(cm.storageGet(that.className)) || {};
        if(cm.isEmpty(that.params['name'])){
            cm.errorLog({
                'name' : that.className,
                'message' : 'Storage cannot be written because "name" parameter not provided.'
            });
            return {};
        }
        if(!storage[that.params['name']]){
            storage[that.params['name']] = {};
        }
        storage[that.params['name']][key] = value;
        cm.storageSet(that.className, JSON.stringify(storage));
        return storage[that.params['name']];
    },
    'storageWriteAll' : function(data){
        var that = this,
            storage = JSON.parse(cm.storageGet(that.className)) || {};
        if(cm.isEmpty(that.params['name'])){
            cm.errorLog({
                'name' : that.className,
                'message' : 'Storage cannot be written because "name" parameter not provided.'
            });
            return {};
        }
        storage[that.params['name']] = data;
        cm.storageSet(that.className, JSON.stringify(storage));
        return storage[that.params['name']];
    }
};<commit_msg> * JS. Dev. Fix modules.<commit_after>/* ******* EVENTS ******* */

Mod['Events'] = {
    '_define' : function(){
        var that = this;
        if(!that.data['params']['events']){
            that.data['params']['events'] = {};
        }
        that.extendObject['events'] = that.data['events'];
        that.extendObject['eventsStack'] = {};
        cm.forEach(that.data['events'], function(item){
            that.extendObject['eventsStack'][item] = [];
            that.extendObject[item] = function(handler){
                var that = this;
                that.addEvent(item, handler);
                return that;
            };
        });
    },
    'addEvent' : function(event, handler){
        var that = this;
        that.eventsStack = cm.clone(that.eventsStack);
        if(that.eventsStack[event]){
            if(typeof handler == 'function'){
                that.eventsStack[event].push(handler);
            }else{
                cm.errorLog({
                    'name' : that.className,
                    'message' : ['Handler of event', cm.strWrap(event, '"'), 'must be a function.'].join(' ')
                });
            }
        }else{
            cm.errorLog({
                'name' : that.className,
                'message' : [cm.strWrap(event, '"'), 'does not exists.'].join(' ')
            });
        }
        return that;
    },
    'addEvents' : function(o){
        var that = this;
        if(o){
            that.convertEvents(o);
        }
        return that;
    },
    'removeEvent' : function(event, handler){
        var that = this;
        that.eventsStack = cm.clone(that.eventsStack);
        if(that.eventsStack[event]){
            if(typeof handler == 'function'){
                that.eventsStack[event] = that.eventsStack[event].filter(function(item){
                    return item != handler;
                });
            }else{
                cm.errorLog({
                    'name' : that.className,
                    'message' : ['Handler of event', cm.strWrap(event, '"'), 'must be a function.'].join(' ')
                });
            }
        }else{
            cm.errorLog({
                'name' : that.className,
                'message' : [cm.strWrap(event, '"'), 'does not exists.'].join(' ')
            });
        }
        return that;
    },
    'triggerEvent' : function(event, params){
        var that = this;
        if(that.eventsStack[event]){
            cm.forEach(that.eventsStack[event], function(item){
                item(that, params || {});
            });
        }else{
            cm.errorLog({
                'name' : that.className,
                'message' : [cm.strWrap(event, '"'), 'does not exists.'].join(' ')
            });
        }
        return that;
    },
    'convertEvents' : function(o){
        var that = this;
        cm.forEach(o, function(item, key){
            that.addEvent(key, item);
        });
        return that;
    }
};

/* ******* LANGS ******* */

Mod['Langs'] = {
    '_define' : function(){
        var that = this;
        if(!that.data['params']['langs']){
            that.data['params']['langs'] = {};
        }
    },
    'lang' : function(str){
        var that = this;
        if(!that.params['langs'][str]){
            that.params['langs'][str] = str;
        }
        return that.params['langs'][str];
    }
};

/* ******* DATA CONFIG ******* */

Mod['DataConfig'] = {
    '_define' : function(){
        var that = this;
        if(typeof that.data['params']['configDataMarker'] == 'undefined'){
            that.data['params']['configDataMarker'] = 'data-config';
        }
    },
    'getDataConfig' : function(container, dataMarker){
        var that = this,
            sourceConfig;
        if(cm.isNode(container)){
            dataMarker = dataMarker || that.params['configDataMarker'];
            sourceConfig = container.getAttribute(dataMarker);
            if(sourceConfig && (sourceConfig = JSON.parse(sourceConfig))){
                that.params = cm.merge(that.params, sourceConfig);
            }
        }
        return that;
    },
    'getNodeDataConfig' : function(node, dataMarker){
        var that = this,
            sourceConfig;
        if(cm.isNode(node)){
            dataMarker = dataMarker || that.params['configDataMarker'];
            sourceConfig = node.getAttribute(dataMarker);
            if(sourceConfig && (sourceConfig = JSON.parse(sourceConfig))){
                return sourceConfig;
            }
        }
        return {};
    }
};

/* ******* DATA NODES ******* */

Mod['DataNodes'] = {
    '_define' : function(){
        var that = this;
        if(!that.data['params']['nodes']){
            that.data['params']['nodes'] = {};
        }
        if(typeof that.data['params']['nodesDataMarker'] == 'undefined'){
            that.data['params']['nodesDataMarker'] = 'data-node';
        }
        if(typeof that.data['params']['nodesMarker'] == 'undefined'){
            that.data['params']['nodesMarker'] = that.classNameShort;
        }
        if(!that.extendObject['nodes']){
            that.extendObject['nodes'] = {};
        }
    },
    'getDataNodes' : function(container, dataMarker, className){
        var that = this,
            sourceNodes = {};
        container = typeof container == 'undefined'? document.body : container;
        if(container){
            dataMarker = typeof dataMarker == 'undefined'? that.params['nodesDataMarker'] : dataMarker;
            className = typeof className == 'undefined'? that.params['nodesMarker'] : className;
            if(className){
                sourceNodes = cm.getNodes(container, dataMarker)[className] || {};
            }else{
                sourceNodes = cm.getNodes(container, dataMarker);
            }
            that.nodes = cm.merge(that.nodes, sourceNodes);
        }
        that.nodes = cm.merge(that.nodes, that.params['nodes']);
        return that;
    }
};

/* ******* LOCAL STORAGE ******* */

Mod['Storage'] = {
    '_define' : function(){
        var that = this;
        if(!that.data['params']['name']){
            that.data['params']['name'] = '';
        }
    },
    'storageRead' : function(key){
        var that = this,
            storage = JSON.parse(cm.storageGet(that.className)) || {};
        if(cm.isEmpty(that.params['name'])){
            cm.errorLog({
                'name' : that.className,
                'message' : 'Storage cannot be read because "name" parameter not provided.'
            });
            return null;
        }
        if(!storage[that.params['name']] || typeof storage[that.params['name']][key] == 'undefined'){
            cm.errorLog({
                'type' : 'attention',
                'name' : that.className,
                'message' : ['Parameter', cm.strWrap(key, '"'), 'does not exist or is not set.'].join(' ')
            });
            return null;
        }
        return storage[that.params['name']][key];
    },
    'storageReadAll' : function(){
        var that = this,
            storage = JSON.parse(cm.storageGet(that.className)) || {};
        if(cm.isEmpty(that.params['name'])){
            cm.errorLog({
                'name' : that.className,
                'message' : 'Storage cannot be read because "name" parameter not provided.'
            });
            return {};
        }
        if(!storage[that.params['name']]){
            cm.errorLog({
                'type' : 'attention',
                'name' : that.className,
                'message' : 'Storage is empty.'
            });
            return {};
        }
        return storage[that.params['name']];
    },
    'storageWrite' : function(key, value){
        var that = this,
            storage = JSON.parse(cm.storageGet(that.className)) || {};
        if(cm.isEmpty(that.params['name'])){
            cm.errorLog({
                'name' : that.className,
                'message' : 'Storage cannot be written because "name" parameter not provided.'
            });
            return {};
        }
        if(!storage[that.params['name']]){
            storage[that.params['name']] = {};
        }
        storage[that.params['name']][key] = value;
        cm.storageSet(that.className, JSON.stringify(storage));
        return storage[that.params['name']];
    },
    'storageWriteAll' : function(data){
        var that = this,
            storage = JSON.parse(cm.storageGet(that.className)) || {};
        if(cm.isEmpty(that.params['name'])){
            cm.errorLog({
                'name' : that.className,
                'message' : 'Storage cannot be written because "name" parameter not provided.'
            });
            return {};
        }
        storage[that.params['name']] = data;
        cm.storageSet(that.className, JSON.stringify(storage));
        return storage[that.params['name']];
    }
};<|endoftext|>


<commit_before>import Reflux from 'reflux';
import GameActions from '../actions/GameActions';

var GameStore = Reflux.createStore({

  init() {

  getGameFEN() {
    return this.fen;
  },
  getActivePlayer() {
    return this.fen.split(' ')[1] === 'w' ? "White" : "Black";
  },
  getAllValidMoves() {
    return this.valid_moves;
  },
  getValidMoves(pos) {
    var valid = [];
    for (var move in this.valid_moves) {
      var to_from = this.valid_moves[move].Move.substr(1).replace('x','-').split('-');
      if (to_from[0] === pos) {
        valid.push(to_from[1]);
      }
    }
    return valid;
  },
  getGameHistory() {
    return this.history;
  }
});

export default GameStore;
<commit_msg>Add check for castling in valid moves<commit_after>import Reflux from 'reflux';
import GameActions from '../actions/GameActions';

var GameStore = Reflux.createStore({

  init() {

  getGameFEN() {
    return this.fen;
  },
  getActivePlayer() {
    return this.fen.split(' ')[1] === 'w' ? "White" : "Black";
  },
  getAllValidMoves() {
    return this.valid_moves;
  },
  getValidMoves(pos) {
    var valid = [];
    for (var move in this.valid_moves) {
      var to_from = this.valid_moves[move].Move.substr(1).replace('x','-').split('-');
      if (to_from[0] === pos) {
        valid.push(to_from[1]);
      }
      else if (to_from[0] === 'O' && pos[0] === 'e') {
        if (to_from.length === 2) {
          valid.push(this.getActivePlayer() === "White" ? "g1" : "g8");
        }
        else if (to_from.length === 3) {
          valid.push(this.getActivePlayer() === "White" ? "c1" : "c8");
        }
      }
    }
    return valid;
  },
  getGameHistory() {
    return this.history;
  }
});

export default GameStore;
<|endoftext|>


<commit_before>$(function() {
    // Global namespace
	window.fmn = {};

    fmn.Model = Backbone.Model.extend({
        //Default Attributes
        defaults: {
            content: "new empty todo",
            parent: 0,
            indent: 0,
            position: 0,
            done: 0
        },

        initialize: function() {
            if (!this.get("content")) {
              this.set({"content": this.defaults.content});
            }
        },

		done: function() {
		    if (this.get("done") == 0) {
		        this.save({done: 1});
		    } else {
		        this.save({done: 0});
		    }

		},

    });

    // Each Individual Todo Item View
    fmn.TodoView = Backbone.View.extend({
        tagName: "li",
        template: _.template($('#item-template').html()),

        events: {
            "dblclick .display"        :      	"edit",
            //"click .display"        :      	"edit",
            "keydown .edit input"              :      	"keyboardActions",
			"click input.done"  			    : 		"toggleDone",
            "click .display .delete"					   : 	    "deleteTodo"
        },

        initialize: function() {
            _.bindAll(this, 'render', 'deleteTodo', 'close','save', 'keyboardActions');
            this.bind('close', this.render);
            this.el.id = this.model.cid;
            // Give reverse access to a model's view by setting its 'this'
            // to a new attribute on the model
            this.model.view = this;
        },

        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
			this.el.className = 'todo indent-' + this.model.get('indent');
            this.input = this.$(".input");
            this.input.bind('blur', this.close);
            return this;
        },

        edit: function() {
            var content = this.model.get('content');
            $(this.el).addClass("editing");
            this.input.val(content);
            this.input.focus();
            //return false;
        },

        save: function(indent) {
			var $inputVal = this.input.val();
            this.model.save({
				content: ($inputVal == '' ? this.model.defaults.content : $inputVal),
				indent: parseInt(this.model.get('indent') + (indent ? indent : ''))
			});
//			this.model.indentBy(indent);
        },

		close: function() {
			this.save();
			$(this.el).removeClass("editing");
			this.trigger('close');
		},

        deleteTodo: function() {
            this.model.destroy();
            this.remove();
        },

        keyboardActions: function(e) {
			/**
				left arrow		37
				up arrow		38
				right arrow		39
				down arrow		40
			**/
			// Enter button
			if (e.keyCode == 13) {
				this.close();
				fmn.app.newTodo();
				e.preventDefault();
			}
			// Tab key - move todo to right one
			// And make sub todo of parent (if it exists)
			if (e.keyCode == 9 && !e.shiftKey) {
				e.preventDefault();
			}
			// Shift + Tab key - move todo to left one
			// And un-sub it from parent (if it exists)
			if (e.shiftKey && e.keyCode == 9) {
				e.preventDefault();
			}

			// Up key - close current todo and open todo above to edit
			if (e.keyCode == 38) {
				this.editPreviousTodo(e);
			}
			// Down key - close current todo and open todo above to edit
			if (e.keyCode == 40) {
				this.editNextTodo(e);
			}
			// Backspace key
			if (e.keyCode == 8) {
				if (this.input.val() == '') {
					this.editPreviousTodo(e);
					this.deleteTodo();
					e.preventDefault();
				}
			}
        },

		toggleDone: function() {
			this.model.done();
		}
    });

    fmn.Collection = Backbone.Collection.extend({
        model: fmn.Model,
		url: "fmn.php?",

        comparator: function(todo) {
          return todo.get('id');
        }
    });

    fmn.Todos = new fmn.Collection;

    fmn.App = Backbone.View.extend({
        el: $("#todoApp"),

        events: {
            "click #createNew"  :       "newTodo"
        },

        initialize: function() {
            Backbone.emulateJSON = true;
            _.bindAll(this, 'newTodo', 'addOne', 'addAll');
            fmn.Todos.bind('reset', this.addAll);
			fmn.Todos.bind('add', this.addOne);
			fmn.Todos.bind('add', function(model, collection){
				model.view.edit();
			});
            fmn.Todos.fetch();
        },

        addAll: function(collection, r) {
			// If collection is empty add one
			if(!collection.length) {
				var model = collection.create();
			}
            collection.each(this.addOne);
        },

        addOne: function(o, p) {
            var view = new fmn.TodoView({model:o.todo || o});
			this.$("#todoItemsList").append(view.render().el);
            return view;
        },

        newTodo: function(o) {
            fmn.Todos.create();
        }

    });

    fmn.app = new fmn.App;

});<commit_msg>make comparator return right order for single digit IDs<commit_after>$(function() {
    // Global namespace
	window.fmn = {};

    fmn.Model = Backbone.Model.extend({
        //Default Attributes
        defaults: {
            content: "new empty todo",
            parent: 0,
            indent: 0,
            position: 0,
            done: 0
        },

        initialize: function() {
            if (!this.get("content")) {
              this.set({"content": this.defaults.content});
            }
        },

		done: function() {
		    if (this.get("done") == 0) {
		        this.save({done: 1});
		    } else {
		        this.save({done: 0});
		    }

		},

    });

    // Each Individual Todo Item View
    fmn.TodoView = Backbone.View.extend({
        tagName: "li",
        template: _.template($('#item-template').html()),

        events: {
            "dblclick .display"        :      	"edit",
            //"click .display"        :      	"edit",
            "keydown .edit input"              :      	"keyboardActions",
			"click input.done"  			    : 		"toggleDone",
            "click .display .delete"					   : 	    "deleteTodo"
        },

        initialize: function() {
            _.bindAll(this, 'render', 'deleteTodo', 'close','save', 'keyboardActions');
            this.bind('close', this.render);
            this.el.id = this.model.cid;
            // Give reverse access to a model's view by setting its 'this'
            // to a new attribute on the model
            this.model.view = this;
        },

        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
			this.el.className = 'todo indent-' + this.model.get('indent');
            this.input = this.$(".input");
            this.input.bind('blur', this.close);
            return this;
        },

        edit: function() {
            var content = this.model.get('content');
            $(this.el).addClass("editing");
            this.input.val(content);
            this.input.focus();
            //return false;
        },

        save: function(indent) {
			var $inputVal = this.input.val();
            this.model.save({
				content: ($inputVal == '' ? this.model.defaults.content : $inputVal),
				indent: parseInt(this.model.get('indent') + (indent ? indent : ''))
			});
//			this.model.indentBy(indent);
        },

		close: function() {
			this.save();
			$(this.el).removeClass("editing");
			this.trigger('close');
		},

        deleteTodo: function() {
            this.model.destroy();
            this.remove();
        },

        keyboardActions: function(e) {
			/**
				left arrow		37
				up arrow		38
				right arrow		39
				down arrow		40
			**/
			// Enter button
			if (e.keyCode == 13) {
				this.close();
				fmn.app.newTodo();
				e.preventDefault();
			}
			// Tab key - move todo to right one
			// And make sub todo of parent (if it exists)
			if (e.keyCode == 9 && !e.shiftKey) {
				e.preventDefault();
			}
			// Shift + Tab key - move todo to left one
			// And un-sub it from parent (if it exists)
			if (e.shiftKey && e.keyCode == 9) {
				e.preventDefault();
			}

			// Up key - close current todo and open todo above to edit
			if (e.keyCode == 38) {
				this.editPreviousTodo(e);
			}
			// Down key - close current todo and open todo above to edit
			if (e.keyCode == 40) {
				this.editNextTodo(e);
			}
			// Backspace key
			if (e.keyCode == 8) {
				if (this.input.val() == '') {
					this.editPreviousTodo(e);
					this.deleteTodo();
					e.preventDefault();
				}
			}
        },

		toggleDone: function() {
			this.model.done();
		}
    });

    fmn.Collection = Backbone.Collection.extend({
        model: fmn.Model,
		url: "fmn.php?",

        comparator: function(todo) {
			if (todo.get('id').length === 1) {
				return '0'+todo.get('id');
			} else {
				return todo.get('id');
			}
        }
    });

    fmn.Todos = new fmn.Collection;

    fmn.App = Backbone.View.extend({
        el: $("#todoApp"),

        events: {
            "click #createNew"  :       "newTodo"
        },

        initialize: function() {
            Backbone.emulateJSON = true;
            _.bindAll(this, 'newTodo', 'addOne', 'addAll');
            fmn.Todos.bind('reset', this.addAll);
			fmn.Todos.bind('add', this.addOne);
			fmn.Todos.bind('add', function(model, collection){
				model.view.edit();
			});
            fmn.Todos.fetch();
        },

        addAll: function(collection, r) {
			// If collection is empty add one
			if(!collection.length) {
				var model = collection.create();
			}
            collection.each(this.addOne);
        },

        addOne: function(o, p) {
            var view = new fmn.TodoView({model:o.todo || o});
			this.$("#todoItemsList").append(view.render().el);
            return view;
        },

        newTodo: function(o) {
            fmn.Todos.create();
        }

    });

    fmn.app = new fmn.App;

});<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    window.marteladaRefresh = function(){
        $('a.page-scroll').bind('click', function(event) {
            var navHeight = $('.navbar-header').height();
            var $anchor = $(this);
            $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top - navHeight
            }, 1500, 'easeInOutExpo');
            event.preventDefault();
        });
    }

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: $('.navbar-header').height()
    });

    // jQuery to collapse the navbar on scroll
    $(window).scroll(function() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        } else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    });

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });
});
<commit_msg>2 pixels this time<commit_after>/*!
 * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    window.marteladaRefresh = function(){
        $('a.page-scroll').bind('click', function(event) {
            var navHeight = $('.navbar-header').height() + 1;
            var $anchor = $(this);
            $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top - navHeight
            }, 1500, 'easeInOutExpo');
            event.preventDefault();
        });
    }

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: $('.navbar-header').height() + 1
    });

    // jQuery to collapse the navbar on scroll
    $(window).scroll(function() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        } else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    });

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });
});
<|endoftext|>


<commit_before>import moment from 'moment';

Meteor.methods({
  'getAllResidentIds': function () {
    // TODO: determine how to secure this method to prevent client abuse

    // Get all residents
    var residents = Residents.find().fetch();

    // Create an array of resident IDs
    var residentIds = _.map(residents, function (resident) {
      return resident._id;
    });

    return residentIds;
  },
  'getCurrentResidentIds': function () {
    // TODO: determine how to secure this method to prevent client abuse

    // Get all residents
    var residents = Residents.find({departed: false}).fetch();

    // Create an array of resident IDs
    var residentIds = _.map(residents, function (resident) {
      return resident._id;
    });

    return residentIds;
  },
  'getResidentsNameHomeAndLatestActivityByType': function (activityTypeId) {
    // Get all resident IDs
    var residentIds = Meteor.call('getCurrentAllResidentIds');

    // Placeholder for residents latest activity
    var residentsLatestActivityByType = [];

    // Loop through all resident IDs
    residentIds.forEach(function (residentId) {
      // Return resident latest activity
      var residentLatestActivity = Meteor.call('getResidentLatestActivityByType', residentId, activityTypeId);

      // If resident activity exists
      if (residentLatestActivity !== undefined) {
        // Get resident from collection
        var resident = Residents.findOne(residentId);

        // Construct an object with resident name and last activity date
        var residentActivityObject = {
          residentName: resident.fullName(),
          homeName: resident.homeName(),
          activityDate: residentLatestActivity.activityDate
        };

        // Add resident latest activity to residents latest activity array
        residentsLatestActivityByType.push(residentActivityObject);
      }
    });

    return residentsLatestActivityByType;
  },
  'getResidentRecentActivities': function (residentId) {
    // Date two weeks ago
    var twoWeeksAgo = moment().subtract(2, "weeks").toDate();

    // Date today
    var now = new Date();

    // Get all activities involving resident
    // make sure activities are in the past (i.e. not planned)
    //  sort in reverse order by activity date
    return Activities.find({'residentIds': residentId, activityDate: {$gte: twoWeeksAgo, $lte: now}}, {sort : {activityDate:  -1} });
  },
  'getResidentActivitiesByTypeLast30Days': function (residentId, activityTypeId) {
    // Date thirty days ago
    var thirtyDaysAgo = moment().subtract(30, "days").toDate();

    // Date today
    var now = new Date();

    // Get all activities of a specific type involving resident
    // make sure activities are in the past (i.e. not planned)
    //  sort in reverse order by activity date
    var activities = Activities.find({
      'residentIds': residentId,
      'activityTypeId': activityTypeId,
      activityDate: {$gte: thirtyDaysAgo, $lte: now}},
      {sort : {activityDate:  -1}
    }).fetch();

    if (activities) {
      return activities;
    };
  },
  'getSumOfResidentActivitiesByTypeLast30Days': function (residentId, activityTypeId) {
    var activities = Meteor.call('getResidentActivitiesByTypeLast30Days', residentId, activityTypeId);

    // Placeholder for sum of activities
    var sumOfActivities = 0;

    if (activities) {
      // Count each activity
      activities.forEach(function (activity) {
        // Count the resident activity
        sumOfActivities += 1;
      });
    };

    return sumOfActivities;
  },
  'getSumOfAllResidentRecentActivitiesByType': function (residentId) {
    // Get all activity type IDs
    var activityTypeIds = Meteor.call('getAllActivityTypeIds');

    // Placeholder for resident activity sums
    var residentActivitySumsByType = [];

    activityTypeIds.forEach(function (activityTypeId) {
      // Get the activity type
      var activityType = ActivityTypes.findOne(activityTypeId);

      // Get the resident
      var resident = Residents.findOne(residentId);

      // Get sum of activity type for the current resident
      var activitySum = Meteor.call('getSumOfResidentRecentActivitiesByType', residentId, activityTypeId);

      // Create an object with the activity type name and sum
      var activityTypeSum = {
        residentName: resident.fullName(),
        activityTypeName: activityType.name,
        sum: activitySum
      }

      // Add the resident activity type sum to the resident activity sums array
      residentActivitySumsByType.push(activityTypeSum);
    });

    return residentActivitySumsByType;
  },
  'getAllResidentsActivitySumsByType': function () {
    // Get all resident IDs
    var residentIds = Meteor.call('getCurrentResidentIds');

    // Placeholder for all resident activity sums by type
    var allResidentActivitySumsByType = [];

    // Iterate through all residents and get sum of resident recent activities by type
    residentIds.forEach(function (residentId) {
      // Get the sum of all activities by type for a given resident
       var residentActivitiesSumByType = Meteor.call('getSumOfAllResidentRecentActivitiesByType', residentId);

      // Add the resident activity sums to all resident activity sums array
      allResidentActivitySumsByType.push(residentActivitiesSumByType);
    });

    allResidentActivitySumsByTypeFlattened = _.flatten(allResidentActivitySumsByType)

    return allResidentActivitySumsByTypeFlattened;
  },
  getAllResidentSelectOptions () {
    /*
    return an array of resident objects in the form of:
       label: firstName lastInitial
       value: residentId
   */

   // Get all residents
   const residents = Residents.find().fetch();

   // Create array of resident select options
   const residentSelectOptions = _.map(residents, (resident) => {
     return {
       label: `${resident.firstName} ${resident.lastInitial}`,
       value: resident._id,
     }
   });

   return residentSelectOptions;
  },
});
<commit_msg>Lint method definitions<commit_after>import moment from 'moment';

Meteor.methods({
  getAllResidentIds () {
    // TODO: determine how to secure this method to prevent client abuse

    // Get all residents
    var residents = Residents.find().fetch();

    // Create an array of resident IDs
    var residentIds = _.map(residents, function (resident) {
      return resident._id;
    });

    return residentIds;
  },
  getCurrentResidentIds () {
    // TODO: determine how to secure this method to prevent client abuse

    // Get all residents
    var residents = Residents.find({departed: false}).fetch();

    // Create an array of resident IDs
    var residentIds = _.map(residents, function (resident) {
      return resident._id;
    });

    return residentIds;
  },
  getResidentsNameHomeAndLatestActivityByType (activityTypeId) {
    // Get all resident IDs
    var residentIds = Meteor.call('getCurrentAllResidentIds');

    // Placeholder for residents latest activity
    var residentsLatestActivityByType = [];

    // Loop through all resident IDs
    residentIds.forEach(function (residentId) {
      // Return resident latest activity
      var residentLatestActivity = Meteor.call('getResidentLatestActivityByType', residentId, activityTypeId);

      // If resident activity exists
      if (residentLatestActivity !== undefined) {
        // Get resident from collection
        var resident = Residents.findOne(residentId);

        // Construct an object with resident name and last activity date
        var residentActivityObject = {
          residentName: resident.fullName(),
          homeName: resident.homeName(),
          activityDate: residentLatestActivity.activityDate
        };

        // Add resident latest activity to residents latest activity array
        residentsLatestActivityByType.push(residentActivityObject);
      }
    });

    return residentsLatestActivityByType;
  },
  getResidentRecentActivities (residentId) {
    // Date two weeks ago
    var twoWeeksAgo = moment().subtract(2, "weeks").toDate();

    // Date today
    var now = new Date();

    // Get all activities involving resident
    // make sure activities are in the past (i.e. not planned)
    //  sort in reverse order by activity date
    return Activities.find({'residentIds': residentId, activityDate: {$gte: twoWeeksAgo, $lte: now}}, {sort : {activityDate:  -1} });
  },
  getResidentActivitiesByTypeLast30Days (residentId, activityTypeId) {
    // Date thirty days ago
    var thirtyDaysAgo = moment().subtract(30, "days").toDate();

    // Date today
    var now = new Date();

    // Get all activities of a specific type involving resident
    // make sure activities are in the past (i.e. not planned)
    //  sort in reverse order by activity date
    var activities = Activities.find({
      'residentIds': residentId,
      'activityTypeId': activityTypeId,
      activityDate: {$gte: thirtyDaysAgo, $lte: now}},
      {sort : {activityDate:  -1}
    }).fetch();

    if (activities) {
      return activities;
    };
  },
  getSumOfResidentActivitiesByTypeLast30Days (residentId, activityTypeId) {
    var activities = Meteor.call('getResidentActivitiesByTypeLast30Days', residentId, activityTypeId);

    // Placeholder for sum of activities
    var sumOfActivities = 0;

    if (activities) {
      // Count each activity
      activities.forEach(function (activity) {
        // Count the resident activity
        sumOfActivities += 1;
      });
    };

    return sumOfActivities;
  },
  getSumOfAllResidentRecentActivitiesByType (residentId) {
    // Get all activity type IDs
    var activityTypeIds = Meteor.call('getAllActivityTypeIds');

    // Placeholder for resident activity sums
    var residentActivitySumsByType = [];

    activityTypeIds.forEach(function (activityTypeId) {
      // Get the activity type
      var activityType = ActivityTypes.findOne(activityTypeId);

      // Get the resident
      var resident = Residents.findOne(residentId);

      // Get sum of activity type for the current resident
      var activitySum = Meteor.call('getSumOfResidentRecentActivitiesByType', residentId, activityTypeId);

      // Create an object with the activity type name and sum
      var activityTypeSum = {
        residentName: resident.fullName(),
        activityTypeName: activityType.name,
        sum: activitySum
      }

      // Add the resident activity type sum to the resident activity sums array
      residentActivitySumsByType.push(activityTypeSum);
    });

    return residentActivitySumsByType;
  },
  getAllResidentsActivitySumsByType () {
    // Get all resident IDs
    var residentIds = Meteor.call('getCurrentResidentIds');

    // Placeholder for all resident activity sums by type
    var allResidentActivitySumsByType = [];

    // Iterate through all residents and get sum of resident recent activities by type
    residentIds.forEach(function (residentId) {
      // Get the sum of all activities by type for a given resident
       var residentActivitiesSumByType = Meteor.call('getSumOfAllResidentRecentActivitiesByType', residentId);

      // Add the resident activity sums to all resident activity sums array
      allResidentActivitySumsByType.push(residentActivitiesSumByType);
    });

    allResidentActivitySumsByTypeFlattened = _.flatten(allResidentActivitySumsByType)

    return allResidentActivitySumsByTypeFlattened;
  },
  getAllResidentSelectOptions () {
    /*
    return an array of resident objects in the form of:
       label: firstName lastInitial
       value: residentId
   */

   // Get all residents
   const residents = Residents.find().fetch();

   // Create array of resident select options
   const residentSelectOptions = _.map(residents, (resident) => {
     return {
       label: `${resident.firstName} ${resident.lastInitial}`,
       value: resident._id,
     }
   });

   return residentSelectOptions;
  },
});
<|endoftext|>


<commit_before>'use strict';

var require2 = require('require_optional');
var chalk = require2('chalk');
if (chalk.styles) {
  console.log('ok');
}
<commit_msg>fix require_optional test<commit_after>'use strict';

var require2 = require('require_optional');
var chalk = require2('chalk');
if (typeof chalk === 'function') {
  console.log('ok');
}
<|endoftext|>


<commit_before>/** @jsx jsx */
import { jsx } from '@emotion/core';
import { colors } from '@voussoir/ui/src/theme';
import { lighten, darken } from '@voussoir/ui/src/theme/color-utils';

function getToolbarItemStyles(isActive) {
  return {
    color: isActive ? colors.primary : 'white',
    ':hover,:focus': {
      color: isActive ? darken(colors.primary, 10) : lighten(colors.primary, 40),
    },
    ':active': {
      color: darken(colors.primary, 25),
    },
  };
}

export let ToolbarButton = ({ isActive, ...props }) => {
  return (
    <button
      type="button"
      // prevent the text from being deselected when the user clicks the button
      onMouseDown={e => {
        e.stopPropagation();
      }}
      css={[
        {
          backgroundColor: 'transparent',
          border: 0,
          cursor: 'pointer',
        },
        getToolbarItemStyles(isActive),
      ]}
      {...props}
    />
  );
};

export let ToolbarCheckbox = ({ isActive, onChange, id, children }) => {
  return (

      <input
        type="checkbox"
        id={id}
        onMouseDown={e => {
          e.preventDefault();
        }}
        value={isActive}
        css={{
          flex: 0,
          backgroundColor: 'transparent',
          border: 0,
          position: 'absolute',
          opacity: 0,
          cursor: 'pointer',
          height: 0,
          width: 0,
        }}
        onChange={() => {
          onChange();
        }}
      />
      {children}

  );
};
<commit_msg>Change styles<commit_after>/** @jsx jsx */
import { jsx } from '@emotion/core';
import { colors } from '@voussoir/ui/src/theme';
import { lighten, darken } from '@voussoir/ui/src/theme/color-utils';

function getToolbarItemStyles(isActive) {
  return {
    color: isActive ? colors.primary : 'white',
    ':hover,:focus': {
      color: isActive ? darken(colors.primary, 10) : lighten(colors.primary, 40),
    },
    ':active': {
      color: isActive ? darken(colors.primary, 25) : lighten(colors.primary, 10),
    },
  };
}

export let ToolbarButton = ({ isActive, ...props }) => {
  return (
    <button
      type="button"
      // prevent the text from being deselected when the user clicks the button
      onMouseDown={e => {
        e.stopPropagation();
      }}
      css={[
        {
          backgroundColor: 'transparent',
          border: 0,
          cursor: 'pointer',
        },
        getToolbarItemStyles(isActive),
      ]}
      {...props}
    />
  );
};

export let ToolbarCheckbox = ({ isActive, onChange, id, children }) => {
  return (

      <input
        type="checkbox"
        id={id}
        onMouseDown={e => {
          e.preventDefault();
        }}
        value={isActive}
        css={{
          flex: 0,
          backgroundColor: 'transparent',
          border: 0,
          position: 'absolute',
          opacity: 0,
          cursor: 'pointer',
          height: 0,
          width: 0,
        }}
        onChange={() => {
          onChange();
        }}
      />
      {children}

  );
};
<|endoftext|>


<commit_before>(function() {
  var answersCorrect = 0;
  var answersIncorrect = 0;
  var conversionProblem;

  prepNewProblem();
  attachEventHandlers();

  function prepNewProblem() {
    var maxValueBox = document.getElementById('maxValue'),
     userAnswer = document.getElementById('userAnswer'),
     problemText = document.getElementById('problem'),
     indicator = document.getElementById('indicator'),
     maxValue = maxValueBox.value,
     problemType = getProblemType();

    if (parseInt(maxValue))
  	{
      userAnswer.value = "";
  		conversionProblem = problemType == 'hex' ? ConversionProblemGenerator.getHexProblem(maxValue) : ConversionProblemGenerator.getDecProblem(maxValue);
  		problemText.innerHTML = conversionProblem.getProblem();
  	}
  	else
  	{
  		indicator.innerHTML = "You must enter an integer for Max Value.";
  		indicator.className = "incorrect";
  	}
  }

  function getProblemType() {
      var probTypes = document.getElementsByName('probType');
      for (var i = 0, len = probTypes.length; i < len; i++) {
          if (probTypes[i].checked == true) return probTypes[i].value;
      }
  }

  function attachEventHandlers(){
    var probTypes = document.getElementsByName('probType'),
      submit = document.getElementById('submit'),
      maxValueBox = document.getElementById('maxValue');

    submit.onclick = function () {
        submitAnswer();
        prepNewProblem();
        return false;
    };

    for(i=0, len = probTypes.length; i<len; i++)
    {
    	probTypes[i].onclick = prepNewProblem;
    }

    maxValueBox.onchange = prepNewProblem;
  }

  function submitAnswer(){
    var userAnswer = document.getElementById('userAnswer'),
      answerIsCorrect = conversionProblem.checkAnswer(userAnswer.value);
    showAnswerResult(answerIsCorrect);
  }

  function showAnswerResult(answerIsCorrect) {
      if (answerIsCorrect) {
          indicateCorrectAnswer();
      } else {
          indicateIncorrectAnswer();
      }
      updatePercentCorrect();
  }

  function indicateCorrectAnswer(){
    var indicator = document.getElementById('indicator');
    var numCorrectDisplay = document.getElementById('numCorrectDisplay');
    indicator.innerHTML = "Correct!";
    indicator.className = "correct";
    answersCorrect++;
    numCorrectDisplay.innerHTML = answersCorrect;
  }

  function indicateIncorrectAnswer(){
    var indicator = document.getElementById('indicator');
    var numIncorrectDisplay = document.getElementById('numIncorrectDisplay');
    var userAnswer = document.getElementById('userAnswer').value;
    indicator.innerHTML = "Incorrect. " + conversionProblem.getProblem() + " = " + conversionProblem.getSolution() + ", not \"" + userAnswer + "\"";
    indicator.className = "incorrect";
    answersIncorrect++;
    numIncorrectDisplay.innerHTML = answersIncorrect;
  }

  function updatePercentCorrect(){
    var percentDisplay = document.getElementById('percentCorrect');
    var percentCorrect = Math.round((answersCorrect / (answersCorrect + answersIncorrect)) * 100);
  	percentDisplay.innerHTML = percentCorrect  + "%";
  	document.body.style.backgroundColor = getColor(percentCorrect/100);
  }

  function getColor(value){
      //value from 0 to 1
      var hue = ((value)*120).toString(10);
      return ["hsl(",hue,",95%,80%)"].join("");
  }
})();
<commit_msg>Improved error messaging<commit_after>(function() {
  var answersCorrect = 0;
  var answersIncorrect = 0;
  var conversionProblem;

  prepNewProblem();
  attachEventHandlers();

  function prepNewProblem() {
    var maxValueBox = document.getElementById('maxValue'),
     userAnswer = document.getElementById('userAnswer'),
     problemText = document.getElementById('problem'),
     indicator = document.getElementById('indicator'),
     maxValue = maxValueBox.value,
     problemType = getProblemType(),
     errorMessage = "You must enter an integer for Max Value.";

    if (parseInt(maxValue))
  	{
      userAnswer.value = "";
  		conversionProblem = problemType == 'hex' ? ConversionProblemGenerator.getHexProblem(maxValue) : ConversionProblemGenerator.getDecProblem(maxValue);
  		problemText.innerHTML = conversionProblem.getProblem();
      if (indicator.innerHTML == errorMessage)
      {
        indicator.innerHTML = "";
      }
  	}
  	else
  	{
  		indicator.innerHTML = errorMessage;
  		indicator.className = "incorrect";
  	}
  }

  function getProblemType() {
      var probTypes = document.getElementsByName('probType');
      for (var i = 0, len = probTypes.length; i < len; i++) {
          if (probTypes[i].checked == true) return probTypes[i].value;
      }
  }

  function attachEventHandlers(){
    var probTypes = document.getElementsByName('probType'),
      submit = document.getElementById('submit'),
      maxValueBox = document.getElementById('maxValue');

    submit.onclick = function () {
        submitAnswer();
        prepNewProblem();
        return false;
    };

    for(i=0, len = probTypes.length; i<len; i++)
    {
    	probTypes[i].onclick = prepNewProblem;
    }

    maxValueBox.onchange = prepNewProblem;
  }

  function submitAnswer(){
    var userAnswer = document.getElementById('userAnswer'),
      answerIsCorrect = conversionProblem.checkAnswer(userAnswer.value);
    showAnswerResult(answerIsCorrect);
  }

  function showAnswerResult(answerIsCorrect) {
      if (answerIsCorrect) {
          indicateCorrectAnswer();
      } else {
          indicateIncorrectAnswer();
      }
      updatePercentCorrect();
  }

  function indicateCorrectAnswer(){
    var indicator = document.getElementById('indicator');
    var numCorrectDisplay = document.getElementById('numCorrectDisplay');
    indicator.innerHTML = "Correct!";
    indicator.className = "correct";
    answersCorrect++;
    numCorrectDisplay.innerHTML = answersCorrect;
  }

  function indicateIncorrectAnswer(){
    var indicator = document.getElementById('indicator');
    var numIncorrectDisplay = document.getElementById('numIncorrectDisplay');
    var userAnswer = document.getElementById('userAnswer').value;
    indicator.innerHTML = "Incorrect. " + conversionProblem.getProblem() + " = " + conversionProblem.getSolution() + ", not \"" + userAnswer + "\"";
    indicator.className = "incorrect";
    answersIncorrect++;
    numIncorrectDisplay.innerHTML = answersIncorrect;
  }

  function updatePercentCorrect(){
    var percentDisplay = document.getElementById('percentCorrect');
    var percentCorrect = Math.round((answersCorrect / (answersCorrect + answersIncorrect)) * 100);
  	percentDisplay.innerHTML = percentCorrect  + "%";
  	document.body.style.backgroundColor = getColor(percentCorrect/100);
  }

  function getColor(value){
      //value from 0 to 1
      var hue = ((value)*120).toString(10);
      return ["hsl(",hue,",95%,80%)"].join("");
  }
})();
<|endoftext|>


<commit_before>iD.validate = function(changes, graph) {
    var warnings = [], change;

    // https://github.com/openstreetmap/josm/blob/mirror/src/org/
    // openstreetmap/josm/data/validation/tests/UnclosedWays.java#L80
    function tagSuggestsArea(change) {
        if (_.isEmpty(change.tags)) return false;
        var tags = change.tags;
        var presence = ['landuse', 'amenities', 'tourism', 'shop'];
        for (var i = 0; i < presence.length; i++) {
            if (tags[presence[i]] !== undefined) {
                return presence[i] + '=' + tags[presence[i]];
            }
        }
        if (tags.building && tags.building === 'yes') return 'building=yes';
    }

    if (changes.deleted.length > 100) {
        warnings.push({
            message: t('validations.many_deletions', { n: changes.deleted.length })
        });
    }

    for (var i = 0; i < changes.created.length; i++) {
        change = changes.created[i];

        if (change.geometry(graph) === 'point' && _.isEmpty(change.tags)) {
            warnings.push({
                message: t('validations.untagged_point'),
                entity: change
            });
        }

        if (change.geometry(graph) === 'line' && _.isEmpty(change.tags)) {
            warnings.push({ message: t('validations.untagged_line'), entity: change });
        }

        var deprecatedTags = change.deprecatedTags();
        if (!_.isEmpty(deprecatedTags)) {
            warnings.push({
                message: t('validations.deprecated_tags', {
                    tags: iD.util.tagText({ tags: deprecatedTags })
                }), entity: change });
        }

        if (change.geometry(graph) === 'area' && _.isEmpty(change.tags)) {
            warnings.push({ message: t('validations.untagged_area'), entity: change });
        }

        if (change.geometry(graph) === 'line' && tagSuggestsArea(change)) {
            warnings.push({
                message: t('validations.tag_suggests_area', {tag: tagSuggestsArea(change)}),
                entity: change
            });
        }
    }

    return warnings.length ? [warnings] : [];
};
<commit_msg>avoid untagged line warning for lines in relations<commit_after>iD.validate = function(changes, graph) {
    var warnings = [], change;

    // https://github.com/openstreetmap/josm/blob/mirror/src/org/
    // openstreetmap/josm/data/validation/tests/UnclosedWays.java#L80
    function tagSuggestsArea(change) {
        if (_.isEmpty(change.tags)) return false;
        var tags = change.tags;
        var presence = ['landuse', 'amenities', 'tourism', 'shop'];
        for (var i = 0; i < presence.length; i++) {
            if (tags[presence[i]] !== undefined) {
                return presence[i] + '=' + tags[presence[i]];
            }
        }
        if (tags.building && tags.building === 'yes') return 'building=yes';
    }

    if (changes.deleted.length > 100) {
        warnings.push({
            message: t('validations.many_deletions', { n: changes.deleted.length })
        });
    }

    for (var i = 0; i < changes.created.length; i++) {
        change = changes.created[i];

        if (change.geometry(graph) === 'point' && _.isEmpty(change.tags)) {
            warnings.push({
                message: t('validations.untagged_point'),
                entity: change
            });
        }

        if (change.geometry(graph) === 'line' && _.isEmpty(change.tags) &&
                graph.parentRelations(change).length === 0) {
            warnings.push({ message: t('validations.untagged_line'), entity: change });
        }

        var deprecatedTags = change.deprecatedTags();
        if (!_.isEmpty(deprecatedTags)) {
            warnings.push({
                message: t('validations.deprecated_tags', {
                    tags: iD.util.tagText({ tags: deprecatedTags })
                }), entity: change });
        }

        if (change.geometry(graph) === 'area' && _.isEmpty(change.tags)) {
            warnings.push({ message: t('validations.untagged_area'), entity: change });
        }

        if (change.geometry(graph) === 'line' && tagSuggestsArea(change)) {
            warnings.push({
                message: t('validations.tag_suggests_area', {tag: tagSuggestsArea(change)}),
                entity: change
            });
        }
    }

    return warnings.length ? [warnings] : [];
};
<|endoftext|>


<commit_before>// Inflates a given data based on its format
// buffer is a Uint8Array
// format is a InflatedFormat
// Returns an Array or throws in case of error
function inflateData(buffer, format) {
	var data = []
	if (inflateData.readElement(buffer, 0, data, format) != buffer.length)
		throw new Error("Unable to read data in the given format")
	return format.length>1 ? data : (format.length ? data[0] : null)
}

// Extracts a unsigned integer from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error (RangeError means there isn't enough data in the buffer)
inflateData.readUint = function (buffer, offset, data) {
	var firstByte, u, length, i, shifts

	// Get the first byte
	if (offset >= buffer.length)
		throw new RangeError("Unable to extract unsigned integer from index "+offset)
	firstByte = buffer[offset]

	// Get the total length and the first bits
	if (firstByte < Data.OFFSET_2_B) {
		// Fast path
		data.push(firstByte)
		return offset+1
	} else if (firstByte < Data.OFFSET_3_B) {
		length = 1
		u = firstByte&Data.MASK_6_B
	} else if (firstByte < Data.OFFSET_4_B) {
		length = 2
		u = firstByte&Data.MASK_5_B
	} else if (firstByte < Data.OFFSET_5_B) {
		length = 3
		u = firstByte&Data.MASK_4_B
	} else if (firstByte < Data.OFFSET_6_B) {
		length = 4
		u = firstByte&Data.MASK_3_B
	} else if (firstByte < Data.OFFSET_7_B) {
		length = 5
		u = firstByte&Data.MASK_2_B
	} else if (firstByte < Data.OFFSET_8_B) {
		length = 6
		u = firstByte&Data.MASK_1_B
	} else if (firstByte == Data.OFFSET_8_B) {
		length = 7
		u = 0
	} else
		throw new Error("Unable to extract unsigned integer from index "+offset)

	// Get the remaining bytes
	if (offset+length >= buffer.length)
		throw new RangeError("Unable to extract unsigned integer from index "+offset)
	shifts = 7-length
	for (i=1; i<=length; i++) {
		u += (shifts < 24) ? (buffer[offset+i] << shifts) : (buffer[offset+i] * _POWS2[shifts])
		shifts += 8
	}

	data.push(u)
	return offset+1+length
}

// Extracts a signed integer from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error
inflateData.readInt = function (buffer, offset, data) {
	var firstByte, i, length, j, shifts

	// Get the first byte
	if (offset >= buffer.length)
		throw new Error("Unable to extract signed integer from index "+offset)
	firstByte = buffer[offset]

	// Get the total length and the first bits
	if (firstByte < Data.OFFSET_2_B) {
		// Fast path
		data.push(firstByte+Data.MIN_INT_1_B)
		return offset+1
	} else if (firstByte < Data.OFFSET_3_B) {
		length = 1
		i = (firstByte&Data.MASK_6_B)+Data.MIN_INT_2_B
	} else if (firstByte < Data.OFFSET_4_B) {
		length = 2
		i = (firstByte&Data.MASK_5_B)+Data.MIN_INT_3_B
	} else if (firstByte < Data.OFFSET_5_B) {
		length = 3
		i = (firstByte&Data.MASK_4_B)+Data.MIN_INT_4_B
	} else if (firstByte < Data.OFFSET_6_B) {
		length = 4
		i = (firstByte&Data.MASK_3_B)+Data.MIN_INT_5_B
	} else if (firstByte < Data.OFFSET_7_B) {
		length = 5
		i = (firstByte&Data.MASK_2_B)+Data.MIN_INT_6_B
	} else if (firstByte < Data.OFFSET_8_B) {
		length = 6
		i = (firstByte&Data.MASK_1_B)+Data.MIN_INT_7_B
	} else
		throw new Error("Unable to extract signed integer from index "+offset)

	// Get the remaining bytes
	if (offset+length >= buffer.length)
		throw new Error("Unable to extract signed integer from index "+offset)
	shifts = 7-length
	for (j=1; j<=length; j++) {
		i += (shifts < 24) ? (buffer[offset+j] << shifts) : (buffer[offset+j] * _POWS2[shifts])
		shifts += 8
	}

	data.push(i)
	return offset+1+length
}

// Extracts a float from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error
inflateData.readFloat = function (buffer, offset, data) {
	if (offset+4 > buffer.length)
		throw new Error("Unable to extract float from index "+offset)

	data.push(new DataView(buffer.buffer).getFloat32(offset, true))
	return offset+4
}

// Extracts a token from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error
inflateData.readToken = function (buffer, offset, data) {
	if (offset+16 > buffer.length)
		throw new Error("Unable to extract token from index "+offset)

	data.push(new Token(buffer.subarray(offset, offset+16)))
	return offset+16
}

// Extracts a string from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error
inflateData.readString = function (buffer, offset, data) {
	var length, str, i, c

	// Gets the string length
	offset = inflateData.readUint(buffer, offset, data)
	length = data.pop()

	if (offset+length > buffer.length)
		throw new Error("Unable to extract string from index "+offset)

	// Read from UTF-8 bytes
	str = ""
	for (i=0; i<buffer.length; i++) {
		c = buffer[i]
		if (c < 128)
			str += c==0x25 ? "%25" : String.fromCharCode(c)
		else
			str += "%"+c.toString(16).toUpperCase()
	}
	data.push(decodeURIComponent(str))

	return offset+length
}

// Extracts an array from the buffer (an Uint8Array) from the position offset to the data Array
// format is an Array (or sub-Array) returned by inflateFormat()
// Returns the new offset value or throws in case of error
inflateData.readArray = function (buffer, offset, data, format) {
	var length, i, subdata

	// Gets the array length
	offset = inflateData.readUint(buffer, offset, data)
	length = data.pop()

	// Extracts all elements
	array = []
	for (i=0; i<length; i++) {
		if (format.length == 1)
			offset = inflateData.readElement(buffer, offset, array, format)
		else {
			subdata = []
			offset = inflateData.readElement(buffer, offset, subdata, format)
			array.push(subdata)
		}
	}
	data.push(array)

	return offset
}

// Extracts an element from the buffer (an Uint8Array) from the position offset to the data Array
// format is an Array (or sub-Array) returned by inflateFormat()
// Returns the new offset value or throws in case of error
inflateData.readElement = function (buffer, offset, data, format) {
	var i
	for (i=0; i<format.length; i++) {
		if (typeof format[i] == "object")
			offset = inflateData.readArray(buffer, offset, data, format[i])
		else if (format[i] == "u")
			offset = inflateData.readUint(buffer, offset, data)
		else if (format[i] == "i")
			offset = inflateData.readInt(buffer, offset, data)
		else if (format[i] == "f")
			offset = inflateData.readFloat(buffer, offset, data)
		else if (format[i] == "t")
			offset = inflateData.readToken(buffer, offset, data)
		else
			offset = inflateData.readString(buffer, offset, data)
	}
	return offset
}

// Stores 2^i from i=0 to i=56
var _POWS2 = (function () {
	var r = [], i, n = 1
	for (i=0; i<=56; i++) {
		r.push(n)
		n *= 2
	}
	return r
})()
<commit_msg>Bug in reading floats (browser-js)<commit_after>// Inflates a given data based on its format
// buffer is a Uint8Array
// format is a InflatedFormat
// Returns an Array or throws in case of error
function inflateData(buffer, format) {
	var data = []
	if (inflateData.readElement(buffer, 0, data, format) != buffer.length)
		throw new Error("Unable to read data in the given format")
	return format.length>1 ? data : (format.length ? data[0] : null)
}

// Extracts a unsigned integer from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error (RangeError means there isn't enough data in the buffer)
inflateData.readUint = function (buffer, offset, data) {
	var firstByte, u, length, i, shifts

	// Get the first byte
	if (offset >= buffer.length)
		throw new RangeError("Unable to extract unsigned integer from index "+offset)
	firstByte = buffer[offset]

	// Get the total length and the first bits
	if (firstByte < Data.OFFSET_2_B) {
		// Fast path
		data.push(firstByte)
		return offset+1
	} else if (firstByte < Data.OFFSET_3_B) {
		length = 1
		u = firstByte&Data.MASK_6_B
	} else if (firstByte < Data.OFFSET_4_B) {
		length = 2
		u = firstByte&Data.MASK_5_B
	} else if (firstByte < Data.OFFSET_5_B) {
		length = 3
		u = firstByte&Data.MASK_4_B
	} else if (firstByte < Data.OFFSET_6_B) {
		length = 4
		u = firstByte&Data.MASK_3_B
	} else if (firstByte < Data.OFFSET_7_B) {
		length = 5
		u = firstByte&Data.MASK_2_B
	} else if (firstByte < Data.OFFSET_8_B) {
		length = 6
		u = firstByte&Data.MASK_1_B
	} else if (firstByte == Data.OFFSET_8_B) {
		length = 7
		u = 0
	} else
		throw new Error("Unable to extract unsigned integer from index "+offset)

	// Get the remaining bytes
	if (offset+length >= buffer.length)
		throw new RangeError("Unable to extract unsigned integer from index "+offset)
	shifts = 7-length
	for (i=1; i<=length; i++) {
		u += (shifts < 24) ? (buffer[offset+i] << shifts) : (buffer[offset+i] * _POWS2[shifts])
		shifts += 8
	}

	data.push(u)
	return offset+1+length
}

// Extracts a signed integer from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error
inflateData.readInt = function (buffer, offset, data) {
	var firstByte, i, length, j, shifts

	// Get the first byte
	if (offset >= buffer.length)
		throw new Error("Unable to extract signed integer from index "+offset)
	firstByte = buffer[offset]

	// Get the total length and the first bits
	if (firstByte < Data.OFFSET_2_B) {
		// Fast path
		data.push(firstByte+Data.MIN_INT_1_B)
		return offset+1
	} else if (firstByte < Data.OFFSET_3_B) {
		length = 1
		i = (firstByte&Data.MASK_6_B)+Data.MIN_INT_2_B
	} else if (firstByte < Data.OFFSET_4_B) {
		length = 2
		i = (firstByte&Data.MASK_5_B)+Data.MIN_INT_3_B
	} else if (firstByte < Data.OFFSET_5_B) {
		length = 3
		i = (firstByte&Data.MASK_4_B)+Data.MIN_INT_4_B
	} else if (firstByte < Data.OFFSET_6_B) {
		length = 4
		i = (firstByte&Data.MASK_3_B)+Data.MIN_INT_5_B
	} else if (firstByte < Data.OFFSET_7_B) {
		length = 5
		i = (firstByte&Data.MASK_2_B)+Data.MIN_INT_6_B
	} else if (firstByte < Data.OFFSET_8_B) {
		length = 6
		i = (firstByte&Data.MASK_1_B)+Data.MIN_INT_7_B
	} else
		throw new Error("Unable to extract signed integer from index "+offset)

	// Get the remaining bytes
	if (offset+length >= buffer.length)
		throw new Error("Unable to extract signed integer from index "+offset)
	shifts = 7-length
	for (j=1; j<=length; j++) {
		i += (shifts < 24) ? (buffer[offset+j] << shifts) : (buffer[offset+j] * _POWS2[shifts])
		shifts += 8
	}

	data.push(i)
	return offset+1+length
}

// Extracts a float from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error
inflateData.readFloat = function (buffer, offset, data) {
	if (offset+4 > buffer.length)
		throw new Error("Unable to extract float from index "+offset)

	data.push(new DataView(buffer.buffer).getFloat32(buffer.byteOffset+offset, true))
	return offset+4
}

// Extracts a token from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error
inflateData.readToken = function (buffer, offset, data) {
	if (offset+16 > buffer.length)
		throw new Error("Unable to extract token from index "+offset)

	data.push(new Token(buffer.subarray(offset, offset+16)))
	return offset+16
}

// Extracts a string from the buffer (an Uint8Array) from the position offset to the data Array
// Returns the new offset value or throws in case of error
inflateData.readString = function (buffer, offset, data) {
	var length, str, i, c

	// Gets the string length
	offset = inflateData.readUint(buffer, offset, data)
	length = data.pop()

	if (offset+length > buffer.length)
		throw new Error("Unable to extract string from index "+offset)

	// Read from UTF-8 bytes
	str = ""
	for (i=0; i<buffer.length; i++) {
		c = buffer[i]
		if (c < 128)
			str += c==0x25 ? "%25" : String.fromCharCode(c)
		else
			str += "%"+c.toString(16).toUpperCase()
	}
	data.push(decodeURIComponent(str))

	return offset+length
}

// Extracts an array from the buffer (an Uint8Array) from the position offset to the data Array
// format is an Array (or sub-Array) returned by inflateFormat()
// Returns the new offset value or throws in case of error
inflateData.readArray = function (buffer, offset, data, format) {
	var length, i, subdata

	// Gets the array length
	offset = inflateData.readUint(buffer, offset, data)
	length = data.pop()

	// Extracts all elements
	array = []
	for (i=0; i<length; i++) {
		if (format.length == 1)
			offset = inflateData.readElement(buffer, offset, array, format)
		else {
			subdata = []
			offset = inflateData.readElement(buffer, offset, subdata, format)
			array.push(subdata)
		}
	}
	data.push(array)

	return offset
}

// Extracts an element from the buffer (an Uint8Array) from the position offset to the data Array
// format is an Array (or sub-Array) returned by inflateFormat()
// Returns the new offset value or throws in case of error
inflateData.readElement = function (buffer, offset, data, format) {
	var i
	for (i=0; i<format.length; i++) {
		if (typeof format[i] == "object")
			offset = inflateData.readArray(buffer, offset, data, format[i])
		else if (format[i] == "u")
			offset = inflateData.readUint(buffer, offset, data)
		else if (format[i] == "i")
			offset = inflateData.readInt(buffer, offset, data)
		else if (format[i] == "f")
			offset = inflateData.readFloat(buffer, offset, data)
		else if (format[i] == "t")
			offset = inflateData.readToken(buffer, offset, data)
		else
			offset = inflateData.readString(buffer, offset, data)
	}
	return offset
}

// Stores 2^i from i=0 to i=56
var _POWS2 = (function () {
	var r = [], i, n = 1
	for (i=0; i<=56; i++) {
		r.push(n)
		n *= 2
	}
	return r
})()
<|endoftext|>


<commit_before>// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

// Place any jQuery/helper plugins in here.
<commit_msg>Remove console support<commit_after><|endoftext|>


<commit_before>// Copyright 2013-2016, University of Colorado Boulder

/**
 * A Scenery Event is an abstraction over incoming user DOM events.
 *
 * It provides more information (particularly Scenery-related information), and handles a single pointer at a time
 * (DOM TouchEvents can include information for multiple touches at the same time, so the TouchEvent can be passed to
 * multiple Scenery events). Thus it is not save to assume that the DOM event is unique, as it may be shared.
 *
 * NOTE: While the event is being dispatched, its currentTarget may be changed. It is not fully immutable.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var scenery = require( 'SCENERY/scenery' );
  var Trail = require( 'SCENERY/util/Trail' );
  var Pointer = require( 'SCENERY/input/Pointer' );

  /**
   * @constructor
   *
   * @param {Trail} trail - The trail to the node picked/hit by this input event.
   * @param {string} type - Type of the event, e.g. 'string'
   * @param {Pointer} pointer - The pointer that triggered this event
   * @param {DOM Event} domEvent - The original DOM Event that caused this Event to fire.
   */
  function Event( trail, type, pointer, domEvent ) {
    assert && assert( trail instanceof Trail, 'Event\'s trail parameter should be a {Trail}' );
    assert && assert( typeof type === 'string', 'Event\'s type should be a {string}' );
    assert && assert( pointer instanceof Pointer, 'Event\'s pointer parameter should be a {Pointer}' );
    // TODO: add domEvent type assertion -- will browsers support this?

    // @public {boolean} - Whether this Event has been 'handled'. If so, it will not bubble further.
    this.handled = false;

    // @public {boolean} - Whether this Event has been 'aborted'. If so, no further listeners with it will fire.
    this.aborted = false;

    // @public {Trail} - Path to the leaf-most node "hit" by the event, ordered list, from root to leaf
    this.trail = trail;

    // @public {string} - What event was triggered on the listener, e.g. 'move'
    this.type = type;

    // @public {Pointer} - The pointer that triggered this event
    this.pointer = pointer;

    // @public {DOM Event} - Raw DOM InputEvent (TouchEvent, PointerEvent, MouseEvent,...)
    this.domEvent = domEvent;

    // @public {Node|null} - whatever node you attached the listener to, or null when firing events on a Pointer
    this.currentTarget = null;

    // @public {Node} - Leaf-most node in trail
    this.target = trail.lastNode();

    // @public {boolean} - Whether this is the 'primary' mode for the pointer. Always true for touches, and will be true
    // for the mouse if it is the primary (left) mouse button.
    // TODO: don't require check on domEvent (seems sometimes this is passed as null as a hack?)
    this.isPrimary = !pointer.isMouse || !domEvent || domEvent.button === 0;
  }

  scenery.register( 'Event', Event );

  inherit( Object, Event, {
    // like DOM Event.stopPropagation(), but named differently to indicate it doesn't fire that behavior on the underlying DOM event
    handle: function() {
      this.handled = true;
    },

    // like DOM Event.stopImmediatePropagation(), but named differently to indicate it doesn't fire that behavior on the underlying DOM event
    abort: function() {
      this.handled = true;
      this.aborted = true;
    },

    /**
     * Returns whether a typical PressListener (that isn't already attached) could start a drag with this event.
     * @public
     *
     * This can typically be used for patterns where no action should be taken if a press can't be started, e.g.:
     *
     *   down: function( event ) {
     *     if ( !event.canStartPress() ) { return; }
     *
     *     // ... Do stuff to create a node with some type of PressListener
     *
     *     dragListener.press( event );
     *   }
     *
     * NOTE: This ignores non-left mouse buttons (as this is the typical behavior). Custom checks should be done if this
     *       is not suitable.
     *
     * @returns {boolean}
     */
    canStartPress: function() {
      // If the pointer is already attached (some other press probably), it can't start a press.
      // Additionally, we generally want to ignore non-left mouse buttons.
      return !this.pointer.isAttached() && ( !this.pointer.isMouse || this.domEvent.button === 0 );
    }
  } );

  return Event;
} );
<commit_msg>Don't handle on abort, as they are different things<commit_after>// Copyright 2013-2016, University of Colorado Boulder

/**
 * A Scenery Event is an abstraction over incoming user DOM events.
 *
 * It provides more information (particularly Scenery-related information), and handles a single pointer at a time
 * (DOM TouchEvents can include information for multiple touches at the same time, so the TouchEvent can be passed to
 * multiple Scenery events). Thus it is not save to assume that the DOM event is unique, as it may be shared.
 *
 * NOTE: While the event is being dispatched, its currentTarget may be changed. It is not fully immutable.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var scenery = require( 'SCENERY/scenery' );
  var Trail = require( 'SCENERY/util/Trail' );
  var Pointer = require( 'SCENERY/input/Pointer' );

  /**
   * @constructor
   *
   * @param {Trail} trail - The trail to the node picked/hit by this input event.
   * @param {string} type - Type of the event, e.g. 'string'
   * @param {Pointer} pointer - The pointer that triggered this event
   * @param {DOM Event} domEvent - The original DOM Event that caused this Event to fire.
   */
  function Event( trail, type, pointer, domEvent ) {
    assert && assert( trail instanceof Trail, 'Event\'s trail parameter should be a {Trail}' );
    assert && assert( typeof type === 'string', 'Event\'s type should be a {string}' );
    assert && assert( pointer instanceof Pointer, 'Event\'s pointer parameter should be a {Pointer}' );
    // TODO: add domEvent type assertion -- will browsers support this?

    // @public {boolean} - Whether this Event has been 'handled'. If so, it will not bubble further.
    this.handled = false;

    // @public {boolean} - Whether this Event has been 'aborted'. If so, no further listeners with it will fire.
    this.aborted = false;

    // @public {Trail} - Path to the leaf-most node "hit" by the event, ordered list, from root to leaf
    this.trail = trail;

    // @public {string} - What event was triggered on the listener, e.g. 'move'
    this.type = type;

    // @public {Pointer} - The pointer that triggered this event
    this.pointer = pointer;

    // @public {DOM Event} - Raw DOM InputEvent (TouchEvent, PointerEvent, MouseEvent,...)
    this.domEvent = domEvent;

    // @public {Node|null} - whatever node you attached the listener to, or null when firing events on a Pointer
    this.currentTarget = null;

    // @public {Node} - Leaf-most node in trail
    this.target = trail.lastNode();

    // @public {boolean} - Whether this is the 'primary' mode for the pointer. Always true for touches, and will be true
    // for the mouse if it is the primary (left) mouse button.
    // TODO: don't require check on domEvent (seems sometimes this is passed as null as a hack?)
    this.isPrimary = !pointer.isMouse || !domEvent || domEvent.button === 0;
  }

  scenery.register( 'Event', Event );

  inherit( Object, Event, {
    // like DOM Event.stopPropagation(), but named differently to indicate it doesn't fire that behavior on the underlying DOM event
    handle: function() {
      this.handled = true;
    },

    // like DOM Event.stopImmediatePropagation(), but named differently to indicate it doesn't fire that behavior on the underlying DOM event
    abort: function() {
      this.aborted = true;
    },

    /**
     * Returns whether a typical PressListener (that isn't already attached) could start a drag with this event.
     * @public
     *
     * This can typically be used for patterns where no action should be taken if a press can't be started, e.g.:
     *
     *   down: function( event ) {
     *     if ( !event.canStartPress() ) { return; }
     *
     *     // ... Do stuff to create a node with some type of PressListener
     *
     *     dragListener.press( event );
     *   }
     *
     * NOTE: This ignores non-left mouse buttons (as this is the typical behavior). Custom checks should be done if this
     *       is not suitable.
     *
     * @returns {boolean}
     */
    canStartPress: function() {
      // If the pointer is already attached (some other press probably), it can't start a press.
      // Additionally, we generally want to ignore non-left mouse buttons.
      return !this.pointer.isAttached() && ( !this.pointer.isMouse || this.domEvent.button === 0 );
    }
  } );

  return Event;
} );
<|endoftext|>