<commit_before>'use strict';

var expertBoxLanguage = angular.module('expert-box-language', ['ngResource']);

//language service
expertBoxLanguage.service('ebLanguage', ['$log', '$q', '$resource',
                                         function($log, $q, $resource) {
  var self = this;

  //function to load a set of translations for language code
  self.load = function(code) {
    $log.debug('language.load ' + code);

    //create language file resource
    var languageFilePath = 'translation/' + code.toLowerCase() + '.json';
    //$log.debug('languageFilePath is '+languageFilePath);
    var resource = $resource(languageFilePath,null, {
      'query': {
          method:'GET',
          isArray:false,
          cache:true
      }
    });

    //translations is a promise
    var defer = $q.defer();
    self.translations = resource.query(function(data) {
      self.translations = data;
      //$log.debug('ebLanguage.load.query.callback : self.translations = ...');
      //$log.debug(self.translations);
    }).$promise;

    //return promise to resolve after translations is recieved and stored
    //$log.debug('ebLanguage.load : self.translations = ...');
    //$log.debug(self.translations);
    return self.translations;
  };

  //form a noun as singular or plural according to a number
  //return promise until translations are resolved
  self.formNoun = function (number, singular, plural) {
      //$log.debug('formNoun requested for '+number+' '+singular+' '+plural);

      var defer = $q.defer();
      $q.when(self.translations).then(function (translations) {
        if (angular.isUndefined(number) || angular.isUndefined(singular) || angular.isUndefined(plural)) {
            var msg = 'formNoun input validation failed'
            $log.error(msg);
            defer.reject(msg);
        }
        else if (number<2) {
          var res = translations[singular];
          //$log.debug('formNoun '+number+' resolves as '+res);
          defer.resolve(res);
        }
        else {
          var res = translations[plural];
          //$log.debug('formNoun '+number+' resolves as '+res);
          defer.resolve(res);
        }
      });
      return defer.promise;
  };

  //translates a measurement with formed noun (singular/plural) units
  //use: measurements that contain a number and a formed noun
  //  example: 1 gram, 500 grams
  //  example: 1 person, 2 people
  //  example: 1 hour, 2 hours
  //  example: 1 beer, 2 beers
  //arguments:
  //  singular: translation key for singulat form of the noun/unit
  //  plural: translation key for plural form of the noun/unit
  //return promise until translations are resolved
  self.measurement = function (number, singular, plural) {
    //$log.debug('requesting measurement '+number+' '+singular+' '+plural);
    var defer = $q.defer();
    $q.when(self.translations).then(function () {
      //$log.debug('translation resolved');
      if (angular.isUndefined(number) || angular.isUndefined(singular) || angular.isUndefined(plural)) {
          defer.reject('measurement input validation failed');
      }
      $q.when(self.formNoun(number, singular, plural)).then(function(noun) {
          //$log.debug('measurement formNoun '+number+' '+singular+' '+plural+' resolved to '+noun);
          defer.resolve(number+' '+noun);
      });
    });
    return defer.promise;
  };

  //creates a comma seperated list of translated items, with last item joined by conjective add translation
  //argument items should be an array of strings
  self.list = function (items) {
      var defer = $q.defer();
      $q.when(translations).then(function () {
          var strings = _.map(items, function (item) {
              var translation = translations[item];
              return angular.isDefined(translation) ? translation : item;
          });

          var firstString = _.first(strings);

          var midString = '';
          var lastString = '';
          if (items.length > 1) {
              var midStrings = strings.slice(1, -1);
              midString = _.reduce(midStrings, function (memo, str) {
                  return memo + ', ' + str;
              }, '');
              lastString = ' ' + translations.AND + ' ' + _.last(strings);
          }

          defer.resolve(firstString + midString + lastString);
      });
      return defer.promise;
  };

  self.getTranslation = function(key) {
      var deferred = $q.defer();
      $q.when(translations).then(function () {
          deferred.resolve(translations[key]);
      });
      return deferred.promise;
  };

  //init language service
  //$log.debug('init language service');
  var deferred = $q.defer();
  self.translations = deferred.promise;
}]);

//translates collections and keys in the loaded language
expertBoxLanguage.filter('translated', ['$log', '_', 'ebLanguage', '$q',
                                        function ($log, _, ebLanguage, $q) {
    var filterFn = function (items) {
        //$log.debug('translated filter not available yet');
        return undefined;
    };

    $q.when(ebLanguage.translations).then(function (translations) {
        //$log.debug('translated filter is available');
        filterFn = function (items) {
            //$log.debug('using translated filter');
            if (_.isArray(items) || _.isObject(items)) {
                //$log.debug('translated filter: array or object');
                return _.map(items, function (item) {
                    return translations[item];
                });
            }
            else if (_.isString(items)) {
                //$log.debug('translated filter: string');
                var item = items;
                return translations[item];
            }
            else
                return items;
        };
    });

    return function (items) {
        return filterFn(items);
    };
}]);<commit_msg>Remove debug logging<commit_after>'use strict';

var expertBoxLanguage = angular.module('expert-box-language', ['ngResource']);

//language service
expertBoxLanguage.service('ebLanguage', ['$log', '$q', '$resource',
                                         function($log, $q, $resource) {
  var self = this;

  //function to load a set of translations for language code
  self.load = function(code) {
    //create language file resource
    var languageFilePath = 'translation/' + code.toLowerCase() + '.json';
    //$log.debug('languageFilePath is '+languageFilePath);
    var resource = $resource(languageFilePath,null, {
      'query': {
          method:'GET',
          isArray:false,
          cache:true
      }
    });

    //translations is a promise
    var defer = $q.defer();
    self.translations = resource.query(function(data) {
      self.translations = data;
      //$log.debug('ebLanguage.load.query.callback : self.translations = ...');
      //$log.debug(self.translations);
    }).$promise;

    //return promise to resolve after translations is recieved and stored
    //$log.debug('ebLanguage.load : self.translations = ...');
    //$log.debug(self.translations);
    return self.translations;
  };

  //form a noun as singular or plural according to a number
  //return promise until translations are resolved
  self.formNoun = function (number, singular, plural) {
      //$log.debug('formNoun requested for '+number+' '+singular+' '+plural);

      var defer = $q.defer();
      $q.when(self.translations).then(function (translations) {
        if (angular.isUndefined(number) || angular.isUndefined(singular) || angular.isUndefined(plural)) {
            var msg = 'formNoun input validation failed'
            $log.error(msg);
            defer.reject(msg);
        }
        else if (number<2) {
          var res = translations[singular];
          //$log.debug('formNoun '+number+' resolves as '+res);
          defer.resolve(res);
        }
        else {
          var res = translations[plural];
          //$log.debug('formNoun '+number+' resolves as '+res);
          defer.resolve(res);
        }
      });
      return defer.promise;
  };

  //translates a measurement with formed noun (singular/plural) units
  //use: measurements that contain a number and a formed noun
  //  example: 1 gram, 500 grams
  //  example: 1 person, 2 people
  //  example: 1 hour, 2 hours
  //  example: 1 beer, 2 beers
  //arguments:
  //  singular: translation key for singulat form of the noun/unit
  //  plural: translation key for plural form of the noun/unit
  //return promise until translations are resolved
  self.measurement = function (number, singular, plural) {
    //$log.debug('requesting measurement '+number+' '+singular+' '+plural);
    var defer = $q.defer();
    $q.when(self.translations).then(function () {
      //$log.debug('translation resolved');
      if (angular.isUndefined(number) || angular.isUndefined(singular) || angular.isUndefined(plural)) {
          defer.reject('measurement input validation failed');
      }
      $q.when(self.formNoun(number, singular, plural)).then(function(noun) {
          //$log.debug('measurement formNoun '+number+' '+singular+' '+plural+' resolved to '+noun);
          defer.resolve(number+' '+noun);
      });
    });
    return defer.promise;
  };

  //creates a comma seperated list of translated items, with last item joined by conjective add translation
  //argument items should be an array of strings
  self.list = function (items) {
      var defer = $q.defer();
      $q.when(translations).then(function () {
          var strings = _.map(items, function (item) {
              var translation = translations[item];
              return angular.isDefined(translation) ? translation : item;
          });

          var firstString = _.first(strings);

          var midString = '';
          var lastString = '';
          if (items.length > 1) {
              var midStrings = strings.slice(1, -1);
              midString = _.reduce(midStrings, function (memo, str) {
                  return memo + ', ' + str;
              }, '');
              lastString = ' ' + translations.AND + ' ' + _.last(strings);
          }

          defer.resolve(firstString + midString + lastString);
      });
      return defer.promise;
  };

  self.getTranslation = function(key) {
      var deferred = $q.defer();
      $q.when(translations).then(function () {
          deferred.resolve(translations[key]);
      });
      return deferred.promise;
  };

  //init language service
  //$log.debug('init language service');
  var deferred = $q.defer();
  self.translations = deferred.promise;
}]);

//translates collections and keys in the loaded language
expertBoxLanguage.filter('translated', ['$log', '_', 'ebLanguage', '$q',
                                        function ($log, _, ebLanguage, $q) {
    var filterFn = function (items) {
        //$log.debug('translated filter not available yet');
        return undefined;
    };

    $q.when(ebLanguage.translations).then(function (translations) {
        //$log.debug('translated filter is available');
        filterFn = function (items) {
            //$log.debug('using translated filter');
            if (_.isArray(items) || _.isObject(items)) {
                //$log.debug('translated filter: array or object');
                return _.map(items, function (item) {
                    return translations[item];
                });
            }
            else if (_.isString(items)) {
                //$log.debug('translated filter: string');
                var item = items;
                return translations[item];
            }
            else
                return items;
        };
    });

    return function (items) {
        return filterFn(items);
    };
}]);<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var StartupTab = {
  LOADING_URI: 'startuptab-loaded-uri',

  get prefs() {
    var { prefs } = Cu.import('resource://startuptab-modules/prefs.js', {});
    delete this.prefs;
    return this.prefs = prefs;
  },

  get tabmail() {
    return document.getElementById('tabmail');
  },

  get mode() {
    var mode = this.prefs.getPref('extensions.startuptab@clear-code.com.startup.mode');
    var defaultMode = this.MODE_OPEN_APPLICATION_STARTUP_PAGE;
    return mode === null ? defaultMode : mode;
  },
  MODE_NONE:                          -1,
  MODE_OPEN_APPLICATION_STARTUP_PAGE: 0,
  MODE_OPEN_SPECIFIED_PAGE:           1,
  MODE_OPEN_SPECIFIED_PAGES:          2,

  get pages() {
    switch (this.mode) {
      case this.MODE_OPEN_APPLICATION_STARTUP_PAGE:
        return this._getPagesFromPref('mailnews.start_page.url');
      case this.MODE_OPEN_SPECIFIED_PAGE:
        return this._getPagesFromPref('extensions.startuptab@clear-code.com.startup.page');
      case this.MODE_OPEN_SPECIFIED_PAGES:
        let (pages = this.prefs.getPref('extensions.startuptab@clear-code.com.startup.pages')) {
          try {
            return JSON.parse(pages || '[]');
          } catch(e) {
            return [];
          }
        }
      default:
        return [];
    }
  },
  _getPagesFromPref: function(aKey) {
    var uris = this.prefs.getPref(aKey);
    uris = (uris || '').split('|').filter(function(aURI) {
      return Boolean(aURI);
    });
    return uris.map(function(aURI) {
      return {
        uri:        aURI,
        background: this.background
      };
    });
  },
  get background() {
    return this.prefs.getPref('extensions.startuptab@clear-code.com.startup.loadInBackground');
  },

  observe: function StartupTab_observe(aSubject, aTopic, aData) {
    switch (aTopic) {
      case 'mail-tabs-session-restored':
        return this.init();
    }
  },

  init: function StartupTab_init() {
    Services.obs.removeObserver(this, 'mail-tabs-session-restored');

    if (this.mode >= this.MODE_OPEN_APPLICATION_STARTUP_PAGE) {
      this.pages.forEach(function(aPage) {
        let background = this.loadInBackground;
        if ('background' in aPage)
          background = aPage.background;
        let canClose = true;
        if ('canClose' in aPage)
          canClose = aPage.canClose;
        if (this.shouldOpen(aPage.uri)) {
          this.tabmail.openTab('contentTab', {
            contentPage: aPage.uri,
            background:  background,
            canClose:    canClose
          })
        }
      }
    }
  },
  preInit: function StartupTab_preInit() {
    try {
      specialTabs.contentTabType.__startuptab__openTab = specialTabs.contentTabType.openTab;
      specialTabs.contentTabType.openTab = this.newOpenTab;
      Services.obs.addObserver(this, 'mail-tabs-session-restored', false);
    }
    catch(error) {
      Cu.reportError(error);
    }
  },

  newOpenTab: function StartupTab_openTab(aTab, aArgs) {
    this.__startuptab__openTab.apply(this, arguments);
    aTab.tabNode.setAttribute(StartupTab.LOADING_URI, aArgs.contentPage);
  },

  shouldOpen: function StartupTab_shouldOpen(aURI) {
    if (!aURI)
      return false;

    var tabs = document.querySelectorAll('tab.tabmail-tab');
    return Array.every(tabs, function checkTabOpened(aTab) {
      return aTab.getAttribute(this.LOADING_URI) != aURI;
    }, this);
  }
};
StartupTab.preInit();
<commit_msg>Specify parameters as an object<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var StartupTab = {
  LOADING_URI: 'startuptab-loaded-uri',

  get prefs() {
    var { prefs } = Cu.import('resource://startuptab-modules/prefs.js', {});
    delete this.prefs;
    return this.prefs = prefs;
  },

  get tabmail() {
    return document.getElementById('tabmail');
  },

  get mode() {
    var mode = this.prefs.getPref('extensions.startuptab@clear-code.com.startup.mode');
    var defaultMode = this.MODE_OPEN_APPLICATION_STARTUP_PAGE;
    return mode === null ? defaultMode : mode;
  },
  MODE_NONE:                          -1,
  MODE_OPEN_APPLICATION_STARTUP_PAGE: 0,
  MODE_OPEN_SPECIFIED_PAGE:           1,
  MODE_OPEN_SPECIFIED_PAGES:          2,

  get pages() {
    switch (this.mode) {
      case this.MODE_OPEN_APPLICATION_STARTUP_PAGE:
        return this._getPagesFromPref('mailnews.start_page.url');
      case this.MODE_OPEN_SPECIFIED_PAGE:
        return this._getPagesFromPref('extensions.startuptab@clear-code.com.startup.page');
      case this.MODE_OPEN_SPECIFIED_PAGES:
        let (pages = this.prefs.getPref('extensions.startuptab@clear-code.com.startup.pages')) {
          try {
            return JSON.parse(pages || '[]');
          } catch(e) {
            return [];
          }
        }
      default:
        return [];
    }
  },
  _getPagesFromPref: function(aKey) {
    var uris = this.prefs.getPref(aKey);
    uris = (uris || '').split('|').filter(function(aURI) {
      return Boolean(aURI);
    });
    return uris.map(function(aURI) {
      return {
        uri:        aURI,
        background: this.background
      };
    });
  },
  get background() {
    return this.prefs.getPref('extensions.startuptab@clear-code.com.startup.loadInBackground');
  },

  observe: function StartupTab_observe(aSubject, aTopic, aData) {
    switch (aTopic) {
      case 'mail-tabs-session-restored':
        return this.init();
    }
  },

  init: function StartupTab_init() {
    Services.obs.removeObserver(this, 'mail-tabs-session-restored');

    if (this.mode >= this.MODE_OPEN_APPLICATION_STARTUP_PAGE) {
      this.pages.forEach(function(aPage) {
        let background = this.loadInBackground;
        if ('background' in aPage)
          background = aPage.background;
        let canClose = true;
        if ('canClose' in aPage)
          canClose = aPage.canClose;
        if (this.shouldOpen(aPage)) {
          this.tabmail.openTab('contentTab', {
            contentPage: aPage.uri,
            background:  background,
            canClose:    canClose
          })
        }
      }
    }
  },
  preInit: function StartupTab_preInit() {
    try {
      specialTabs.contentTabType.__startuptab__openTab = specialTabs.contentTabType.openTab;
      specialTabs.contentTabType.openTab = this.newOpenTab;
      Services.obs.addObserver(this, 'mail-tabs-session-restored', false);
    }
    catch(error) {
      Cu.reportError(error);
    }
  },

  newOpenTab: function StartupTab_openTab(aTab, aArgs) {
    this.__startuptab__openTab.apply(this, arguments);
    aTab.tabNode.setAttribute(StartupTab.LOADING_URI, aArgs.contentPage);
  },

  shouldOpen: function StartupTab_shouldOpen(aPage) {
    if (!aPage.uri)
      return false;

    var tabs = document.querySelectorAll('tab.tabmail-tab');
    return Array.every(tabs, function checkTabOpened(aTab) {
      return aTab.getAttribute(this.LOADING_URI) != aPage.uri;
    }, this);
  }
};
StartupTab.preInit();
<|endoftext|>


<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function(){
  "use strict";

  AFRAME.registerComponent('assign-slot', {
    init: function() {
      let id = document.querySelectorAll(".tower").length;
      var newpos = document.getElementById("slot"+id).getAttribute("position");
      this.el.setAttribute("position", newpos);
    }
  });

})()
},{}],2:[function(require,module,exports){
(function(){
  "use strict";

  AFRAME.registerComponent('enemy', {
    init: function() {
	var el = this.el;
    	el.addEventListener('mouseenter', function () {
		el.setAttribute('visible', false);
		el.emit('kill')
	});
    }
  });

  AFRAME.registerComponent('enemy-pool', {
    init: function() {
	var el = this.el;
	for (var i=0; i<7; i++){
		var enemy = document.createElement("a-obj-model")
		enemy.setAttribute("src", "#monster-obj")
		enemy.setAttribute("mtl", "#monster-mtl")
		enemy.setAttribute("rotation", "0 180 0")
		var scaleFactor = Math.random()+5
		enemy.setAttribute("scale", scaleFactor + " " + scaleFactor + " " + scaleFactor)
		var dur = Math.random()*20000
		var delay = 5000 + Math.random()*5000
		enemy.setAttribute("alongpath", "curve: #monster-track; delay:" + delay + "; dur:"+dur+";")
		enemy.setAttribute("enemy", "")
		enemy.addEventListener('movingended', function () {
			if (enemy.getAttribute("visible"))
				document.querySelector("[goal]").emit("hit")
			});
		enemy.setAttribute("sound", "on: kill; src: url(http://vatelier.net/MyDemo/WebVRDefender/public/assets/sounds/Zombie_In_Pain-SoundBible.com-134322253.mp3)")
		this.el.appendChild(enemy)
	}
    }
  });

})()

},{}],3:[function(require,module,exports){
(function(){
  "use strict";

  AFRAME.registerComponent('goal', {
    init: function() {
	var el = this.el;
	var life = document.createElement("a-cylinder")
	life.setAttribute("color", "green")
	life.setAttribute("height", "10")
	life.setAttribute("position", "0 0 -30")
	el.appendChild(life)

	// could have also used a component function
    	el.addEventListener('hit', function () {
		var height = parseInt( life.getAttribute("height") )
		height -= 1
		life.setAttribute("height", height)
		if (height < 5)
			life.setAttribute("color", "red")
	});
    },
  });

})()

},{}],4:[function(require,module,exports){
(function(){
  "use strict";

  AFRAME.registerComponent('presentation-display', {
    init: function() {
	var el = this.el;
	var text = document.createElement("a-text")
	var content = "The terrible vikings are attacking our village, we need to defend. Look at them and laser them to Valhala!"
	text.setAttribute("color", "brown")
	text.setAttribute("value", content)
	text.setAttribute("position", "-0.5 1 -3")
	el.appendChild(text)
    },
  });

})()

},{}],5:[function(require,module,exports){
// Use of this source code is governed by an Apache license that can be
// found in the LICENSE file.
(function(){
	"use strict";
  var Util         = require("./util.js");
  require("./components/assign_slot.js");
  require("./components/enemy.js");
  require("./components/goal.js");
  require("./components/presentation.js");

  window.onConnectCB = function(data){
    let player = document.createElement("a-entity");
    player.id = "player";
    player.setAttribute("networked", {
      template          : "#tower-template",
      showLocalTemplate : false
    });
    player.setAttribute("assign-slot", {});
    player.setAttribute("camera", {});
    player.setAttribute("look-controls", {});
    player.setAttribute("presentation-display", {});
    var cursor = document.createElement("a-cursor");
    player.appendChild(cursor);

    document.querySelector("a-scene").appendChild(player);
  }

  window.onload = function(){
    function onSceneLoaded(){
      document.getElementById("loaderDiv").classList.remove('make-container--visible');
    }
    (document.querySelector("a-scene").hasLoaded ? onSceneLoaded() : document.querySelector("a-scene").addEventListener("loaded", onSceneLoaded));
  };
})();

},{"./components/assign_slot.js":1,"./components/enemy.js":2,"./components/goal.js":3,"./components/presentation.js":4,"./util.js":6}],6:[function(require,module,exports){
var Util = {};
(function(){
  "use strict";
  /**
   * Generate an Unique ID
   * @return {string} Unique ID of length 4
   */
  Util.guid = function(){
    function s4() {
      return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
    }
    return s4();
  }
})()

module.exports = Util;

},{}]},{},[5]);
<commit_msg>bundled<commit_after>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function(){
  "use strict";

  AFRAME.registerComponent('assign-slot', {
    init: function() {
      let id = document.querySelectorAll(".tower").length;
      var newpos = document.getElementById("slot"+id).getAttribute("position");
      this.el.setAttribute("position", newpos);
    }
  });

})()
},{}],2:[function(require,module,exports){
(function(){
  "use strict";

  AFRAME.registerComponent('enemy', {
    init: function() {
	var el = this.el;
    	el.addEventListener('mouseenter', function () {
		el.setAttribute('visible', false);
		el.emit('kill')
	});
    }
  });

  AFRAME.registerComponent('enemy-pool', {
    init: function() {
	var el = this.el;
	for (var i=0; i<7; i++){
		var enemy = document.createElement("a-obj-model")
		enemy.setAttribute("src", "#monster-obj")
		enemy.setAttribute("mtl", "#monster-mtl")
		enemy.setAttribute("rotation", "0 180 0")
		var scaleFactor = Math.random()+5
		enemy.setAttribute("scale", scaleFactor + " " + scaleFactor + " " + scaleFactor)
		var dur = Math.random()*20000
		var delay = 5000 + Math.random()*5000
		enemy.setAttribute("alongpath", "curve: #monster-track; delay:" + delay + "; dur:"+dur+";")
		enemy.setAttribute("enemy", "")
		enemy.addEventListener('movingended', function () {
			if (enemy.getAttribute("visible"))
				document.querySelector("[goal]").emit("hit")
			});
		enemy.setAttribute("sound", "on: kill; src: url(http://vatelier.net/MyDemo/WebVRDefender/public/assets/sounds/Zombie_In_Pain-SoundBible.com-134322253.mp3)")
		this.el.appendChild(enemy)
	}
    }
  });

})()

},{}],3:[function(require,module,exports){
(function(){
  "use strict";

  AFRAME.registerComponent('goal', {
    init: function() {
	var el = this.el;
	var life = document.createElement("a-cylinder")
	life.setAttribute("color", "green")
	life.setAttribute("height", "10")
	life.setAttribute("position", "0 0 -30")
	el.appendChild(life)

	// could have also used a component function
    	el.addEventListener('hit', function () {
		var height = parseInt( life.getAttribute("height") )
		height -= 1
		life.setAttribute("height", height)
		if (height < 5)
			life.setAttribute("color", "red")
	});
    },
  });

})()

},{}],4:[function(require,module,exports){
(function(){
  "use strict";

  AFRAME.registerComponent('presentation-display', {
    init: function() {
	var el = this.el;
	var text = document.createElement("a-text")
	var content = "The terrible vikings are attacking our village, we need to defend. Look at them and laser them to Valhala!"
	text.setAttribute("color", "brown")
	text.setAttribute("value", content)
	text.setAttribute("position", "-1 0.5 -0.3")
	el.appendChild(text)
    },
  });

})()

},{}],5:[function(require,module,exports){
// Use of this source code is governed by an Apache license that can be
// found in the LICENSE file.
(function(){
	"use strict";
  var Util         = require("./util.js");
  require("./components/assign_slot.js");
  require("./components/enemy.js");
  require("./components/goal.js");
  require("./components/presentation.js");

  window.onConnectCB = function(data){
    let player = document.createElement("a-entity");
    player.id = "player";
    player.setAttribute("networked", {
      template          : "#tower-template",
      showLocalTemplate : false
    });
    player.setAttribute("assign-slot", {});
    player.setAttribute("camera", {});
    player.setAttribute("look-controls", {});
    player.setAttribute("presentation-display", {});
    var cursor = document.createElement("a-cursor");
    player.appendChild(cursor);

    document.querySelector("a-scene").appendChild(player);
  }

  window.onload = function(){
    function onSceneLoaded(){
      document.getElementById("loaderDiv").classList.remove('make-container--visible');
    }
    (document.querySelector("a-scene").hasLoaded ? onSceneLoaded() : document.querySelector("a-scene").addEventListener("loaded", onSceneLoaded));
  };
})();

},{"./components/assign_slot.js":1,"./components/enemy.js":2,"./components/goal.js":3,"./components/presentation.js":4,"./util.js":6}],6:[function(require,module,exports){
var Util = {};
(function(){
  "use strict";
  /**
   * Generate an Unique ID
   * @return {string} Unique ID of length 4
   */
  Util.guid = function(){
    function s4() {
      return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
    }
    return s4();
  }
})()

module.exports = Util;

},{}]},{},[5]);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 */

//This is used for our jest tests see https://facebook.github.io/jest/docs/tutorial-react.html
var ReactTools = require('react-tools');
module.exports = {
  process: function(src) {
    return ReactTools.transform(src);
  }
};<commit_msg>remove preprocessor for old Jest tests<commit_after><|endoftext|>


<commit_before>import fs from "fs";
import babelPreset from '../../../../babel-preset';

// we check which babel config file exists in the project root
const readBabelConfig = (root) => {
  const babelFiles = [`${root}/.babelrc`, `${root}/.babelrc.js`,`${root}/.babel.config.js`];

  let extendsFile = {};

  babelFiles.forEach(file => {
    try {
      fs.statSync(file);
      extendsFile = {extends: file}
    }
    catch(err) {
      // dont do anything
    }
  });

  return extendsFile;
}

export default function({ config, stage }) {
  let babelFile = {};

  const isRelativePath = config.paths.DIST.startsWith(config.paths.ROOT);

  if (!isRelativePath) {
    babelFile = readBabelConfig(config.paths.ROOT);
  }

  return {
    test: /\.(js|jsx|mjs)$/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          ...babelFile,
          root: config.paths.ROOT,
          presets: [[babelPreset, { modules: false }]],
          cacheDirectory: isRelativePath ? stage !== 'prod' : config.paths.TEMP,
          compact: stage === 'prod',
          highlightCode: true,
        },
      },
    ],
  }
}
<commit_msg>.babel.config.js -> babel.config.js (#770)<commit_after>import fs from "fs";
import babelPreset from '../../../../babel-preset';

// we check which babel config file exists in the project root
const readBabelConfig = (root) => {
  const babelFiles = [`${root}/.babelrc`, `${root}/.babelrc.js`,`${root}/babel.config.js`];

  let extendsFile = {};

  babelFiles.forEach(file => {
    try {
      fs.statSync(file);
      extendsFile = {extends: file}
    }
    catch(err) {
      // dont do anything
    }
  });

  return extendsFile;
}

export default function({ config, stage }) {
  let babelFile = {};

  const isRelativePath = config.paths.DIST.startsWith(config.paths.ROOT);

  if (!isRelativePath) {
    babelFile = readBabelConfig(config.paths.ROOT);
  }

  return {
    test: /\.(js|jsx|mjs)$/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          ...babelFile,
          root: config.paths.ROOT,
          presets: [[babelPreset, { modules: false }]],
          cacheDirectory: isRelativePath ? stage !== 'prod' : config.paths.TEMP,
          compact: stage === 'prod',
          highlightCode: true,
        },
      },
    ],
  }
}
<|endoftext|>


<commit_before>var request = require('request');
var url = require('url');
var fs = require('fs');
var minimist = require('minimist');
var _ = require('underscore');
var yaml = require('js-yaml');
var colors = require('colors');
var Ftp = require('ftp');
var Step = require('step');

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
var argv = require('minimist')(process.argv.slice(2));

var downloadHTTP = function(address, test, callback) {
    callback = callback || function() {};
    var options = {
        url: address.data,
        timeout: 7000
    };
    (test ? request.head : request.get)(options, function(err, res) {
        if (err) {
            console.log(("ERROR\t" + err + " " + address.data).red);
            return callback();
        }
        res.statusCode == 200 ?
            console.log(res.statusCode + " OK\t" + address.data) :
            console.log((res.statusCode + " ERROR\t" + address.data).red);
        callback();
    }).setMaxListeners(20);
};

var downloadFTP = function(address, test, callback) {
    callback = callback || function() {};
    var ftp = new Ftp();
    var opt = url.parse(address.data);
    opt.user = (opt.auth || ':').split(':')[0];
    opt.password = (opt.auth || ':').split(':')[1];
    opt.connTimeout = 5000;
    ftp.on('ready', function() {
        ftp.get(opt.path, function(err, stream) {
            if (err) {
                console.log(("FTP\t" + err + " " + address.data).red);
                ftp.destroy();
                return callback();
            }
            console.log("FTP OK\t" + address.data);
            if (test) {
                stream.unref();
                stream.destroy();
                ftp.destroy();
            }
            callback();
        });
    });
    ftp.on('error', function(err) {
        console.log(("FTP\t" + err + " " + address.data).red);
        ftp.destroy();
        callback();
    });
    ftp.connect(opt);
};

var download = function(address, test, callback) {
    callback = callback || function() {};
    if (!address.data) {
        console.log(("NOTICE: No data URL for " + address.website).yellow);
        return callback();
    }
    var options = url.parse(address.data);
    options.protocol == 'ftp:' ?
        downloadFTP(address, test, callback) :
        downloadHTTP(address, test, callback);
};

var downloadFile = function(file, test, callback) {
    callback = callback || function() {};
    fs.readFile(file, 'utf8', function(err, data) {
        if (err) {
            return callback();
        }
        Step(
            function() {
                var parallel = this.parallel;
                var addresses = yaml.safeLoad(data);
                _(addresses).each(function(address) {
                    download(address, test, parallel());
                });
            },
            callback
        );
    });
};

_(['us', 'canada']).each(function(dir) {
    fs.readdir('../us', function(err, files) {
        var steps = [];
        Step(
            function() {
                var parallel = this.parallel;
                _(files).each(function(file) {
                    downloadFile('../us/' + file, argv['test'], parallel());
                });
            },
            function() {
                process.exit(0);
            }
        );
    });
});
<commit_msg>Use tap format for tests.<commit_after>var request = require('request');
var url = require('url');
var fs = require('fs');
var minimist = require('minimist');
var _ = require('underscore');
var yaml = require('js-yaml');
var colors = require('colors');
var Ftp = require('ftp');
var Step = require('step');

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
var argv = require('minimist')(process.argv.slice(2));

var tapCount = 0;
var tapOK = function(message) {
    console.log('ok ' + (++tapCount) + '\t' + message);
};
var tapNotOK = function(message, diagnostics) {
    console.log(('not ok ' + (++tapCount) + '\t' + message).red);
    diagnostics && console.log(('# ' + diagnostics).red);
};
var tapPlan = function(num, comment) {
    tapCount = 0;
    console.log('1..' + num);
    comment && console.log('# ' + comment);
};

var downloadHTTP = function(address, test, callback) {
    callback = callback || function() {};
    var options = {
        url: address.data,
        timeout: 7000
    };
    (test ? request.head : request.get)(options, function(err, res) {
        if (err) {
            tapNotOK(address.data, err);
            return callback();
        }
        res.statusCode == 200 ?
            tapOK(address.data) :
            tapNotOK(address.data, "HTTP Status " + res.statusCode);
        callback();
    }).setMaxListeners(20);
};

var downloadFTP = function(address, test, callback) {
    callback = callback || function() {};
    var ftp = new Ftp();
    var opt = url.parse(address.data);
    opt.user = (opt.auth || ':').split(':')[0];
    opt.password = (opt.auth || ':').split(':')[1];
    opt.connTimeout = 5000;
    ftp.on('ready', function() {
        ftp.get(opt.path, function(err, stream) {
            if (err) {
                tapNotOK(address.data, err);
                ftp.destroy();
                return callback();
            }
            tapOK(address.data);
            if (test) {
                stream.unref();
                stream.destroy();
                ftp.destroy();
            }
            callback();
        });
    });
    ftp.on('error', function(err) {
        tapNotOK(address.data, err);
        ftp.destroy();
        callback();
    });
    ftp.connect(opt);
};

var download = function(address, test, callback) {
    callback = callback || function() {};
    if (!address.data) {
        tapOK("# SKIP - no data URL for " + address.website);
        return callback();
    }
    var options = url.parse(address.data);
    options.protocol == 'ftp:' ?
        downloadFTP(address, test, callback) :
        downloadHTTP(address, test, callback);
};

var steps = [];
_(['us', 'canada']).each(function(dir) {
    steps.push(function() {
        var callback = this;
        Step(
            function() {
                fs.readdir('../' + dir, this);
            },
            function(err, files) {
                var group = this.group();
                _(files).each(function(file) {
                    var cb = group();
                    fs.readFile('../' + dir + '/' + file, 'utf8', function(err, data) {
                        cb(err, yaml.safeLoad(data));
                    });
                });
            },
            function(err, addresses) {
                var parallel = this.parallel;
                addresses = _(addresses).reduce(function(memo, address) {
                    memo = memo.concat(address);
                    return memo;
                }, []);
                tapPlan(addresses.length, 'Testing directory ../' + dir);
                _(addresses).each(function(address) {
                    download(address, argv['test'], parallel());
                });
            },
            callback
        );
    });
});
steps.push(function() {
    process.exit(0);
})
Step.apply(this, steps);
<|endoftext|>


<commit_before>$('document').ready(function() {
	console.log(isLoggedIn());
});<commit_msg>Renamed script.js to scripts.js<commit_after><|endoftext|>


<commit_before>import candela from './../../src/candela';
import indexContent from './index.jade';
import 'javascript-detect-element-resize/detect-element-resize';
import './index.styl';

function showPage () {
  [...document.getElementsByClassName('page')].forEach(el => {
    el.classList.add('hidden');
  });
  let pageId = 'main';
  if (window.location.hash.length > 1) {
    pageId = window.location.hash.slice(1);
  }
  document.getElementById(pageId).classList.remove('hidden');
}

window.addEventListener('load', () => {
  document.getElementsByTagName('body')[0].innerHTML = indexContent();
  showPage();
  window.addEventListener('hashchange', showPage, false);

  let data = [];
  for (let i = 0; i < 100; i += 1) {
    data.push({x: Math.random(), y: Math.random()});
  }

  [...document.getElementsByClassName('vis-element')].forEach(el => {
    let vis = new candela.components.Scatter(
      el,
      {
        data,
        x: 'x',
        y: 'y'
      }
    );
    vis.render();
    window.addResizeListener(el, () => vis.render());
  });

  window.setInterval(() => {
    document.getElementById('containing-table').style.width = (500 + Math.floor(Math.random() * 500)) + 'px';
  }, 1000);
});
<commit_msg>Reorganize whitespace for readability<commit_after>import candela from './../../src/candela';
import indexContent from './index.jade';
import 'javascript-detect-element-resize/detect-element-resize';
import './index.styl';

function showPage () {
  [...document.getElementsByClassName('page')].forEach(el => {
    el.classList.add('hidden');
  });
  let pageId = 'main';
  if (window.location.hash.length > 1) {
    pageId = window.location.hash.slice(1);
  }
  document.getElementById(pageId).classList.remove('hidden');
}

window.addEventListener('load', () => {
  document.getElementsByTagName('body')[0].innerHTML = indexContent();
  showPage();
  window.addEventListener('hashchange', showPage, false);

  let data = [];
  for (let i = 0; i < 100; i += 1) {
    data.push({x: Math.random(), y: Math.random()});
  }

  [...document.getElementsByClassName('vis-element')].forEach(el => {
    let vis = new candela.components.Scatter(el, {
      data,
      x: 'x',
      y: 'y'
    });
    vis.render();
    window.addResizeListener(el, () => vis.render());
  });

  window.setInterval(() => {
    document.getElementById('containing-table').style.width = (500 + Math.floor(Math.random() * 500)) + 'px';
  }, 1000);
});
<|endoftext|>


<commit_before>(function() {
  var eyex;
  var eyetribe;
  var mygaze;

  try {
    eyex = require('eyex');
  } catch(e) { }
  try {
    eyetribe = require('eyetribe');
  } catch(e) { }
  try {
    mygaze = require('mygaze');
  } catch(e) { }
  if(eyex) {
    try {
      eyex.setup();
    } catch(e) {
      eyex = null;
    }
  }
  if(eyetribe) {
    try {
      eyetribe.setup();
    } catch(e) {
      eyetribe = null;
    }
  }
  if(mygaze) {
    // TODO...
  }

  var poll = null;
  var lasts = {};
  var gaze_history = [];
  var callbacks = [];
  var any_averaged = false;
  var run_callbacks = function(message) {
    callbacks.forEach(function(obj) {
      if(message.type == 'over' && obj.level == 'noisy') {
        obj.callback(message);
      } else if(message.type == 'linger' && obj.level == 'averaged') {
        obj.callback(message);
      }
    });
  };
  var gazelinger = {
    listen: function(callback, level) {
      level = level || 'noisy';
      if(level == 'averaged') { any_averaged = true; }
      if(eyetribe && eyetribe.listen) {
        // idempotent
        eyetribe.listen();
      }
      if(!poll) {
        var poll = function() {
          if(callbacks.length == 0) { return; }
          var data = {};
          if(eyex && eyex.ping) {
            data.eyex = eyex.ping();
            if(data.eyex && (data.eyex.gaze_ts == 0 || lasts.eyex == data.eyex.gaze_ts)) {
              data.eyex = null;
            } else if(data.eyex) {
              lasts.eyex = data.eyex.gaze_ts;
            }
          }
          if(eyetribe && eyetribe.ping) {
            data.eyetribe = eyetribe.ping();
            if(data.eyetribe && (data.eyetribe.gaze_ts == 0 || lasts.eyetribe == data.eyetribe.gaze_ts)) {
              data.eyetribe = null;
            } else if(data.eyetribe){
              lasts.eyetribe = data.eyetribe.gaze_ts
            }
          }
          if(mygaze && mygaze.ping) {
            // TODO ...
          }
          data.result = data.eyex || data.eyetribe || data.mygaze || {};
          data = data.result;

          var message = { raw: data };
          message.ts = (new Date()).getTime();

          if(data.end_ts && data.begin_ts && data.end_ts > data.begin_ts && data.end_ts != lasts.linger) {
//             console.log("linger duration " + (data.end_ts - data.begin_ts));
//             console.log("time since last " + (data.end_ts - lasts.linger));
            lasts.linger = data.end_ts;

            message = { raw: data};
            message.ts = (new Date()).getTime();
            message.screenX = data.data_x; //(data.data_x / ratio) - (window.screenInnerOffsetX || window.screenX);
            message.screenY = data.data_y; // = (data.data_y / ratio) - (window.screenInnerOffsetY || window.screenY);
            message.duration = (data.end_ts - data.begin_ts);
            message.type = 'linger';
//            run_callbacks(message);
          }
          if(data.gaze_ts && data.gaze_ts != lasts.gaze && any_averaged) {
            lasts.gaze = data.gaze_ts;
            message = { raw: data};
            message.ts = (new Date()).getTime();
            message.screenX = data.gaze_x; //(data.gaze_x / ratio) - (window.screenInnerOffsetX || window.screenX);
            message.screenY = data.gaze_y; //(data.gaze_y / ratio) - (window.screenInnerOffsetY || window.screenY);
            message.type = 'over';
            message.ts = data.gaze_ts;
            run_callbacks(message);

            gaze_history.push({
              x: message.screenX,
              y: message.screenY,
              ts: message.ts
            });

            // prune based on distance from latest timestamp
            var new_history = [];
            gaze_history.forEach(function (e) { if (lasts.gaze - e.ts < 200) { new_history.push(e); } });
            gaze_history = new_history;

            // find a quick median
            var xs = gaze_history.sort(function (a, b) { return b.x - a.x });
            var midx = xs[Math.ceil(xs.length / 2)];
            var ys = gaze_history.sort(function (a, b) { return b.y - a.y });
            var midy = ys[Math.ceil(ys.length / 2)];

            // temporarily remove outliers
            if (midx && midy) {
              midx = midx.x;
              midy = midy.y;

              var filtered_history = gaze_history.filter(function (e) { return (Math.abs(e.x - midx) < 50) && (Math.abs(e.y - midy) < 50); });
              if (filtered_history.length > 0) {
                var biggest_dist = 0;
                lasts.history = gaze_history[0].ts;
                filtered_history.forEach(function (e) { biggest_dist = Math.max(biggest_dist, e.ts - lasts.history); lasts.history - e.ts; });

                // if there are no significant time gaps, compute a new middle and trigger a linger event
                if (biggest_dist <= 50) {
                  var mean_x = 0;
                  var mean_y = 0;
                  filtered_history.forEach(function (e) { mean_x = mean_x + e.x; mean_y = mean_y + e.y; });
                  mean_x = mean_x / filtered_history.length;
                  mean_y = mean_y / filtered_history.length;

                  message = { raw: data};
                  message.ts = (new Date()).getTime();
                  message.screenX = mean_x;
                  message.screenY = mean_y;
                  message.type = 'linger';
                  message.duration = filtered_history[filtered_history.length - 1].ts - filtered_history[0].ts;
                  run_callbacks(message);
                  gaze_history = gaze_history.slice(4, 50);
                }
              }
            }
          }
          // I was using setInterval, but it was causing a queue backlog, I thought this would help.
          setTimeout(poll, 50);
        };
        setTimeout(poll, 50);
      }
      callbacks.push({callback: callback, level: level});
    },
    stop_listening: function() {
      // TODO: support multiple listeners
      callbacks = [];
      any_averaged = false;
      clearTimeout(poll);
      poll = null;
      if(eyetribe && eyetribe.stop_listening) {
        eyetribe.stop_listening();
      }
    }
  };
  module.exports = gazelinger;
})();
<commit_msg>fix averaged check<commit_after>(function() {
  var eyex;
  var eyetribe;
  var mygaze;

  try {
    eyex = require('eyex');
  } catch(e) { }
  try {
    eyetribe = require('eyetribe');
  } catch(e) { }
  try {
    mygaze = require('mygaze');
  } catch(e) { }
  if(eyex) {
    try {
      eyex.setup();
    } catch(e) {
      eyex = null;
    }
  }
  if(eyetribe) {
    try {
      eyetribe.setup();
    } catch(e) {
      eyetribe = null;
    }
  }
  if(mygaze) {
    // TODO...
  }

  var poll = null;
  var lasts = {};
  var gaze_history = [];
  var callbacks = [];
  var any_averaged = false;
  var run_callbacks = function(message) {
    callbacks.forEach(function(obj) {
      if(message.type == 'over' && obj.level == 'noisy') {
        obj.callback(message);
      } else if(message.type == 'linger' && obj.level == 'averaged') {
        obj.callback(message);
      }
    });
  };
  var gazelinger = {
    listen: function(callback, level) {
      level = level || 'noisy';
      if(level == 'averaged') { any_averaged = true; }
      if(eyetribe && eyetribe.listen) {
        // idempotent
        eyetribe.listen();
      }
      if(!poll) {
        var poll = function() {
          if(callbacks.length == 0) { return; }
          var data = {};
          if(eyex && eyex.ping) {
            data.eyex = eyex.ping();
            if(data.eyex && (data.eyex.gaze_ts == 0 || lasts.eyex == data.eyex.gaze_ts)) {
              data.eyex = null;
            } else if(data.eyex) {
              lasts.eyex = data.eyex.gaze_ts;
            }
          }
          if(eyetribe && eyetribe.ping) {
            data.eyetribe = eyetribe.ping();
            if(data.eyetribe && (data.eyetribe.gaze_ts == 0 || lasts.eyetribe == data.eyetribe.gaze_ts)) {
              data.eyetribe = null;
            } else if(data.eyetribe){
              lasts.eyetribe = data.eyetribe.gaze_ts
            }
          }
          if(mygaze && mygaze.ping) {
            // TODO ...
          }
          data.result = data.eyex || data.eyetribe || data.mygaze || {};
          data = data.result;

          var message = { raw: data };
          message.ts = (new Date()).getTime();

          if(data.end_ts && data.begin_ts && data.end_ts > data.begin_ts && data.end_ts != lasts.linger) {
//             console.log("linger duration " + (data.end_ts - data.begin_ts));
//             console.log("time since last " + (data.end_ts - lasts.linger));
            lasts.linger = data.end_ts;

            message = { raw: data};
            message.ts = (new Date()).getTime();
            message.screenX = data.data_x; //(data.data_x / ratio) - (window.screenInnerOffsetX || window.screenX);
            message.screenY = data.data_y; // = (data.data_y / ratio) - (window.screenInnerOffsetY || window.screenY);
            message.duration = (data.end_ts - data.begin_ts);
            message.type = 'linger';
//            run_callbacks(message);
          }
          if(data.gaze_ts && data.gaze_ts != lasts.gaze) {
            lasts.gaze = data.gaze_ts;
            message = { raw: data};
            message.ts = (new Date()).getTime();
            message.screenX = data.gaze_x; //(data.gaze_x / ratio) - (window.screenInnerOffsetX || window.screenX);
            message.screenY = data.gaze_y; //(data.gaze_y / ratio) - (window.screenInnerOffsetY || window.screenY);
            message.duration = 50;
            message.type = 'over';
            message.ts = data.gaze_ts;
            run_callbacks(message);

            if(any_averaged) {
              gaze_history.push({
                x: message.screenX,
                y: message.screenY,
                ts: message.ts
              });

              // prune based on distance from latest timestamp
              var new_history = [];
              gaze_history.forEach(function (e) { if (lasts.gaze - e.ts < 200) { new_history.push(e); } });
              gaze_history = new_history;

              // find a quick median
              var xs = gaze_history.sort(function (a, b) { return b.x - a.x });
              var midx = xs[Math.ceil(xs.length / 2)];
              var ys = gaze_history.sort(function (a, b) { return b.y - a.y });
              var midy = ys[Math.ceil(ys.length / 2)];

              // temporarily remove outliers
              if (midx && midy) {
                midx = midx.x;
                midy = midy.y;

                var filtered_history = gaze_history.filter(function (e) { return (Math.abs(e.x - midx) < 50) && (Math.abs(e.y - midy) < 50); });
                if (filtered_history.length > 0) {
                  var biggest_dist = 0;
                  lasts.history = gaze_history[0].ts;
                  filtered_history.forEach(function (e) { biggest_dist = Math.max(biggest_dist, e.ts - lasts.history); lasts.history - e.ts; });

                  // if there are no significant time gaps, compute a new middle and trigger a linger event
                  if (biggest_dist <= 50) {
                    var mean_x = 0;
                    var mean_y = 0;
                    filtered_history.forEach(function (e) { mean_x = mean_x + e.x; mean_y = mean_y + e.y; });
                    mean_x = mean_x / filtered_history.length;
                    mean_y = mean_y / filtered_history.length;

                    message = { raw: data};
                    message.ts = (new Date()).getTime();
                    message.screenX = mean_x;
                    message.screenY = mean_y;
                    message.type = 'linger';
                    message.duration = filtered_history[filtered_history.length - 1].ts - filtered_history[0].ts;
                    run_callbacks(message);
                    // slicing at index 3 means you will get at most a linger event every 150ms
                    gaze_history = gaze_history.slice(3, 50);
                  }
                }
              }
            }
          }
          // I was using setInterval, but it was causing a queue backlog, I thought this would help.
          setTimeout(poll, 50);
        };
        setTimeout(poll, 50);
      }
      callbacks.push({callback: callback, level: level});
    },
    stop_listening: function() {
      // TODO: support multiple listeners
      callbacks = [];
      any_averaged = false;
      clearTimeout(poll);
      poll = null;
      if(eyetribe && eyetribe.stop_listening) {
        eyetribe.stop_listening();
      }
    }
  };
  module.exports = gazelinger;
})();
<|endoftext|>


<commit_before>import io from 'socket.io-client'

var socket = io.connect('/');

socket.on('unauthenticated', function() {
   if (!App.airplane) {
      window.location.reload();
   }
});

socket.on('connect', function() {
   var token = App.socketToken;
   socket.emit('authenticate', token);
});

export default socket;
<commit_msg>[minor] Whitespace<commit_after>import io from 'socket.io-client'

var socket = io.connect('/');

socket.on('unauthenticated', function() {
   if (!App.airplane) {
      window.location.reload();
   }
});

socket.on('connect', function() {
   var token = App.socketToken;
   socket.emit('authenticate', token);
});

export default socket;
<|endoftext|>


<commit_before>Rubpocalypse.Sounds = (function() {

  var soundForName = function(name) {
    return $("#" + name + "-sound").get(0);
  };

  return {
    play: function(name) {
      if (!Modernizr.audio) return
      var sound = soundForName(name);
      sound.pause()
      sound.currentTime = 0;
      sound.play();
    },
    pause: function(name) {
      if (!Modernizr.audio) return;
      soundForName(name).pause();
    }
  }

})();

<commit_msg>Remove call to pause<commit_after>Rubpocalypse.Sounds = (function() {

  var soundForName = function(name) {
    return $("#" + name + "-sound").get(0);
  };

  return {
    play: function(name) {
      if (!Modernizr.audio) return
      var sound = soundForName(name);
      sound.currentTime = 0;
      sound.play();
    },
    pause: function(name) {
      if (!Modernizr.audio) return;
      soundForName(name).pause();
    }
  }

})();

<|endoftext|>


<commit_before>'use strict';

var User = require('../models/users');
var Poll = require('../models/polls');
var Choice = require('../models/choices');
var d3 = require('d3');

//var path = __dirname;
var path = process.cwd();
//var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var PollHandler = require(path + '/app/controllers/pollHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	//var clickHandler = new ClickHandler();
	var pollHandler = new PollHandler();

	app.route('/')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
				res.render('index',{poll:poll});
			})
		});

	app.route('/login')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
			res.render('login',{poll:poll, layout:'loggedout'});
			})
		});

	/*app.route('/poll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('poll');
			})
		});*/

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile/:id')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				console.log(user);
				res.render('profile',{user:user, time:Date.now()});
			})
		});

	app.route('/createpoll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('createpoll');
			})
		});

	app.route('/poll')
		.post(isLoggedIn, function (req, res) {
			console.log(req.body);
			var newpoll = {question : req.body.question};
			newpoll.choices = {};
			var choices = req.body.choices.split(',');
			choices.forEach(function(item) {
				newpoll.choices[item]=0;
			})
			newpoll.creator = req.user._id;
			console.log(newpoll);
			Poll.create(newpoll, function(err, poll) {
				if (err) {
					console.log(err)
				}
			User.findById(req.user._id, function(err, user){
				console.log(user);
				user.polls.push(poll._id);
    			user.save();
				res.redirect('/poll/' + poll._id)
			});
			});
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render("profile",{user:req.user});
		});

	app.route('/poll/:id')
		.get(function (req, res) {
			Poll.findById(req.params.id, function(err, poll){
				console.log(poll.choices);
				//poll.poll.choices.count++;
				res.render("poll",{
					poll:poll,
					helpers: {
						chart: function(poll){
							var chart = d3.select(".chart")
							.selectAll("div")
    						.data(poll)
							.enter().append("div")
							.style("width", function(d) { return d * 10 + "px"; })
    						.text(function(d) { return d; });
						}
					}
				});
			})
		})
		.delete(function (req, res) {
			console.log(req.params);
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll);
				if (poll) {
					poll.remove();
				};
			User.findById(req.user._id, function(err, user){
				console.log(user);
				var index = user.polls.indexOf(req.params.id);
				console.log(index);
				if (index > -1) {
    				user.polls.splice(index, 1);
    				user.save();
				}
				res.redirect('/profile');
			})
			})
		})
		.post(function (req, res) {
			console.log(req.body);
			if (req.body.choice) {
				Poll.findOne({"_id": req.params.id}, function(err, poll) {
					poll.choices[req.body.choice]++;
					console.log(poll);
					poll.markModified('choices');
					poll.save();
					res.redirect('/poll/' + poll._id);
				})
			}
		});

	/*app.route('/poll/:id/:choice')
		.post(function (req, res) {
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				Choice.findOneAndUpdate({"_id": req.params.choice}, {$inc : {'count' : 1}});
				res.redirect('/poll');
				})
				//console.log(poll.poll.choices);
			});*/

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/auth/twitter')
		.get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	/*app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);*/

//	app.route('/createpoll')
	//	.post(pollHandler.addPoll);

	app.route('/success')
		.get(function (req, res) {
		//console.dir(req.body);
		res.render('success');
		});
//agasg

};
<commit_msg>displaying polls<commit_after>'use strict';

var User = require('../models/users');
var Poll = require('../models/polls');
var Choice = require('../models/choices');
var d3 = require('d3');

//var path = __dirname;
var path = process.cwd();
//var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var PollHandler = require(path + '/app/controllers/pollHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	//var clickHandler = new ClickHandler();
	var pollHandler = new PollHandler();

	app.route('/')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
				res.render('index',{poll:poll});
			})
		});

	app.route('/login')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
			res.render('login',{poll:poll, layout:'loggedout'});
			})
		});

	/*app.route('/poll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('poll');
			})
		});*/

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile/:id')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				console.log(user);
				res.render('profile',{user:user, time:Date.now()});
			})
		});

	app.route('/createpoll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('createpoll');
			})
		});

	app.route('/poll')
		.post(isLoggedIn, function (req, res) {
			console.log(req.body);
			var newpoll = {question : req.body.question};
			newpoll.choices = {};
			var choices = req.body.choices.split(',');
			choices.forEach(function(item) {
				newpoll.choices[item]=0;
			})
			newpoll.creator = req.user._id;
			console.log(newpoll);
			Poll.create(newpoll, function(err, poll) {
				if (err) {
					console.log(err)
				}
			User.findById(req.user._id, function(err, user){
				console.log(user);
				user.polls.push(poll._id);
    			user.save();
				res.redirect('/poll/' + poll._id)
			});
			});
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render("profile",{user:req.user});
		});

	app.route('/poll/:id')
		.get(function (req, res) {
			Poll.findById(req.params.id, function(err, poll){
				console.log(poll.choices);
				//poll.poll.choices.count++;
				res.render("poll",{
					poll:poll,
					helpers: {
						chart: function(poll){
							var chart = d3.select(".chart")
							.selectAll("div")
    						.data(poll.choices)
							.enter().append("div")
							.style("width", function(d) { return d * 10 + "px"; })
    						.text(function(d) { return d; });
						}
					}
				});
			})
		})
		.delete(function (req, res) {
			console.log(req.params);
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll);
				if (poll) {
					poll.remove();
				};
			User.findById(req.user._id, function(err, user){
				console.log(user);
				var index = user.polls.indexOf(req.params.id);
				console.log(index);
				if (index > -1) {
    				user.polls.splice(index, 1);
    				user.save();
				}
				res.redirect('/profile');
			})
			})
		})
		.post(function (req, res) {
			console.log(req.body);
			if (req.body.choice) {
				Poll.findOne({"_id": req.params.id}, function(err, poll) {
					poll.choices[req.body.choice]++;
					console.log(poll);
					poll.markModified('choices');
					poll.save();
					res.redirect('/poll/' + poll._id);
				})
			}
		});

	/*app.route('/poll/:id/:choice')
		.post(function (req, res) {
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				Choice.findOneAndUpdate({"_id": req.params.choice}, {$inc : {'count' : 1}});
				res.redirect('/poll');
				})
				//console.log(poll.poll.choices);
			});*/

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/auth/twitter')
		.get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	/*app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);*/

//	app.route('/createpoll')
	//	.post(pollHandler.addPoll);

	app.route('/success')
		.get(function (req, res) {
		//console.dir(req.body);
		res.render('success');
		});
//agasg

};
<|endoftext|>


<commit_before>(function($win, $doc) {
  'use strict';

  var document = $doc;
  var window = $win;

  window.Rplus = {
    ele: {
      html: document.documentElement,
      head: document.head || document.getElementsByTagName('head')[0]
    },
    ready: function (fn) {
      if (document.readyState !== 'loading'){
        fn();
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    },
    ajaxGet: function ($path, $fn) {
      var ajax = new XMLHttpRequest();
      ajax.open('GET', $path, true);
      ajax.send();
      if ('function' === typeof $fn) {
        ajax.onload = function () {
          $fn({data: ajax.responseText});
        };
      }
    },
    getFBInfo: function ($noscriptEle) {
      var _allAttr = (function ($fbString) {
        return {
          arr: $fbString.match(/(?!\s)\w+?=".+?"/g),
          obj: {
            oriString: $fbString.trim(),
            tag: $fbString.match(/^\s+?<(\w+?)\s/)[1]
          }
        };
      })($noscriptEle.firstChild.data);

      for (var i = _allAttr.arr.length; i;) {
        i--;
        _allAttr._tmpArr = _allAttr.arr[i].match(/(\w+?)="(.+?)"/);
        _allAttr.obj[_allAttr._tmpArr[1]] = _allAttr._tmpArr[2];
      }

      return _allAttr.obj;
    },
    injectInline: function ($src, $specilOption) {
      $src.sourceAttr = {
        link: 'href',
        img: 'src'
      }[$src.tag];
      $src.sourceUrl = $src[$src.sourceAttr];
      $src.ext = $src.sourceUrl.split('.').reverse()[0];

      var _cachedItem = $src.sourceUrl.split('/').reverse()[0];
      var _isSvgType = ('svg' === $src.ext);
      var localData = localStorage.getItem(_cachedItem);

      var injectHTML = function (inlineContent) {
        var div = document.createElement('div');
        div.innerHTML = inlineContent;

        if (document.readyState !== 'loading') {
          var _insertBeforeEle = ($specilOption && $specilOption.insertBefore) || Rplus.ele.body.childNodes[0];
          Rplus.ele.body.insertBefore(div, _insertBeforeEle);
        } else {
          Rplus.ele.head.appendChild(div);
        }
      };

      if (Rplus.hasCache && localData) {
        injectHTML(localData);
      } else if ($specilOption && $specilOption.insertTag) {
        injectHTML($src.oriString);
      } else {
        Rplus.ajaxGet($src.sourceUrl, function (response) {
          var inlineContent = response.data;

          if (!_isSvgType) {
            inlineContent = '<style>' + inlineContent + '</sctyle>';
          }

          localStorage.setItem(_cachedItem, inlineContent);

          if ($specilOption && $specilOption.cacheOnly) {
            return;
          }

          injectHTML(inlineContent);
        });
      }
    }
  };

  var Rplus = window.Rplus || {};

  // init Rplus.ele.body
  Rplus.ready(function () {
    Rplus.ele.body = document.body || document.getElementsByTagName('body')[0];
  });

  // check cache version
  ;(function ($ele, $lsItem) {
    var _latestVersion = $ele.getAttribute('data-' + $lsItem);
    var _cacheVersion = localStorage.getItem($lsItem);
    var _hasCache = (_cacheVersion === _latestVersion);

    if (!_hasCache || '#clear' === location.hash) {
      // forcely clear all localStorage data
      localStorage.clear();
      localStorage.setItem($lsItem, _latestVersion);
    }

    Rplus.hasCache = _hasCache;
  })(document.getElementById('js-version'), 'version');

  // init modernizr class for <html>, from cache or inject script callback
  ;(function ($eles, $lsItem) {
    var htmlClassName = localStorage.getItem($lsItem);

    if (Rplus.hasCache && htmlClassName) {
      // init html class
      $eles.html.className = htmlClassName;
    } else {
      var _injectJsEle = document.createElement('script');

      // save html className into localStorage after script loaded
      _injectJsEle.src = '//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js';
      _injectJsEle.addEventListener('load', function () {
        localStorage.setItem($lsItem, $eles.html.className);
      });

      $eles.head.appendChild(_injectJsEle);
    }
  })(Rplus.ele, 'modernizrAllClass');

  // init main style
  Rplus.injectInline(Rplus.getFBInfo(document.getElementById('js-main-style')), {insertTag: true});

})(window, document);
<commit_msg>補上 fallback 的 parent id，部份需要 insert 至 parent 前<commit_after>(function($win, $doc) {
  'use strict';

  var document = $doc;
  var window = $win;

  window.Rplus = {
    ele: {
      html: document.documentElement,
      head: document.head || document.getElementsByTagName('head')[0]
    },
    ready: function (fn) {
      if (document.readyState !== 'loading'){
        fn();
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    },
    ajaxGet: function ($path, $fn) {
      var ajax = new XMLHttpRequest();
      ajax.open('GET', $path, true);
      ajax.send();
      if ('function' === typeof $fn) {
        ajax.onload = function () {
          $fn({data: ajax.responseText});
        };
      }
    },
    getFBInfo: function ($noscriptEle) {
      var _allAttr = (function ($fbString) {
        return {
          arr: $fbString.match(/(?!\s)\w+?=".+?"/g),
          obj: {
            parentId: $noscriptEle.id,
            oriString: $fbString.trim(),
            tag: $fbString.match(/^\s+?<(\w+?)\s/)[1]
          }
        };
      })($noscriptEle.firstChild.data);

      for (var i = _allAttr.arr.length; i;) {
        i--;
        _allAttr._tmpArr = _allAttr.arr[i].match(/(\w+?)="(.+?)"/);
        _allAttr.obj[_allAttr._tmpArr[1]] = _allAttr._tmpArr[2];
      }

      return _allAttr.obj;
    },
    injectInline: function ($src, $specilOption) {
      $src.sourceAttr = {
        link: 'href',
        img: 'src'
      }[$src.tag];
      $src.sourceUrl = $src[$src.sourceAttr];
      $src.ext = $src.sourceUrl.split('.').reverse()[0];

      var _cachedItem = $src.sourceUrl.split('/').reverse()[0];
      var _isSvgType = ('svg' === $src.ext);
      var localData = localStorage.getItem(_cachedItem);

      var injectHTML = function (inlineContent) {
        var div = document.createElement('div');
        div.innerHTML = inlineContent;

        if (document.readyState !== 'loading') {
          var _insertBeforeEle = ($specilOption && $specilOption.insertBefore) || Rplus.ele.body.childNodes[0];
          Rplus.ele.body.insertBefore(div, _insertBeforeEle);
        } else {
          Rplus.ele.head.appendChild(div);
        }
      };

      if (Rplus.hasCache && localData) {
        injectHTML(localData);
      } else if ($specilOption && $specilOption.insertTag) {
        injectHTML($src.oriString);
      } else {
        Rplus.ajaxGet($src.sourceUrl, function (response) {
          var inlineContent = response.data;

          if (!_isSvgType) {
            inlineContent = '<style>' + inlineContent + '</sctyle>';
          }

          localStorage.setItem(_cachedItem, inlineContent);

          if ($specilOption && $specilOption.cacheOnly) {
            return;
          }

          injectHTML(inlineContent);
        });
      }
    }
  };

  var Rplus = window.Rplus || {};

  // init Rplus.ele.body
  Rplus.ready(function () {
    Rplus.ele.body = document.body || document.getElementsByTagName('body')[0];
  });

  // check cache version
  ;(function ($ele, $lsItem) {
    var _latestVersion = $ele.getAttribute('data-' + $lsItem);
    var _cacheVersion = localStorage.getItem($lsItem);
    var _hasCache = (_cacheVersion === _latestVersion);

    if (!_hasCache || '#clear' === location.hash) {
      // forcely clear all localStorage data
      localStorage.clear();
      localStorage.setItem($lsItem, _latestVersion);
    }

    Rplus.hasCache = _hasCache;
  })(document.getElementById('js-version'), 'version');

  // init modernizr class for <html>, from cache or inject script callback
  ;(function ($eles, $lsItem) {
    var htmlClassName = localStorage.getItem($lsItem);

    if (Rplus.hasCache && htmlClassName) {
      // init html class
      $eles.html.className = htmlClassName;
    } else {
      var _injectJsEle = document.createElement('script');

      // save html className into localStorage after script loaded
      _injectJsEle.src = '//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js';
      _injectJsEle.addEventListener('load', function () {
        localStorage.setItem($lsItem, $eles.html.className);
      });

      $eles.head.appendChild(_injectJsEle);
    }
  })(Rplus.ele, 'modernizrAllClass');

  // init main style
  Rplus.injectInline(Rplus.getFBInfo(document.getElementById('js-main-style')), {insertTag: true});

})(window, document);
<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var ctrlPath = path + '/app/controllers';
const UserController = require(ctrlPath + '/userController.server.js');
const SearchController = require(ctrlPath + '/searchController.server.js');
const VenueController = require(ctrlPath + '/venueController.server.js');

var $DEBUG = 0;

var _log = function(msg) {
    console.log("\t" + msg);
};

/** Function for debug logging request.*/
var reqDebug = function(req) {
	_log("Headers: " + JSON.stringify(req.headers));
	_log("Body: "    + JSON.stringify(req.body));
	_log("Params: "  + JSON.stringify(req.params));
	_log("Url:"      + JSON.stringify(req.url));
	_log("Text:"     + JSON.stringify(req.text));
	_log("Content:"  + JSON.stringify(req.content));
	_log("Query:"    + JSON.stringify(req.query));
};

module.exports = function (app, passport) {

    /** Renders a pug template.*/
    var renderPug = function(req, res, pugFile) {
        var isAuth = req.isAuthenticated();
        res.render(path + "/pug/" + pugFile, {isAuth: isAuth});
    };

    /** loggedIn func from clementine.js. */
	var isLoggedIn = function(req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

    // CONTROLLERS
    var userController = new UserController(path);
    var searchController = new SearchController();
    var venueController = new VenueController();

    //----------------------------------------------------------------------
    // ROUTES
    //----------------------------------------------------------------------

	app.route('/')
		.get((req, res) => {
            renderPug(req, res, "index.pug");
            //res.sendFile(path + "/pug/index.pug");
		});

	app.route('/about')
		.get((req, res) => {
            renderPug(req, res, "about.pug");
		});

	app.route('/signup')
		.get((req, res) => {
            renderPug(req, res, "signup.pug");
		});

	app.route('/login')
		.get((req, res) => {
            renderPug(req, res, "login.pug");
		});

	app.route('/loginFailed')
		.get((req, res) => {
            res.render(path + "/pug/login.pug",
                {isAuth: false, loginFailed: true});
        });

    // If a user logs out, return to main page
	app.route('/logout')
		.get((req, res) => {
			req.logout();
			res.redirect('/');
		});

	app.route('/profile')
		.get(isLoggedIn, (req, res) => {
            renderPug(req, res, "profile.pug");
		});

    // Handle registration of user
    app.route('/forms/signup')
        .post((req, res) => {
            if ($DEBUG) {
                console.log("Got a signup form GET request..");
                reqDebug(req);
            }
            userController.addLocalUser(req, res);
        });

    // Called by client to check their authentication status
	app.route('/amiauth')
		.get((req, res) => {
            var data = {isAuth: false};
            if (req.isAuthenticated()) {
                data.isAuth = true;
                data.username = req.user.username;
            }
            res.json(data);
		});

    //----------------------------------
    // Routes for manipulating user data
    //----------------------------------

    /** Marks user as going or not going for an event. */
    app.route('/going')
        .post(isLoggedIn, (req, res) => {
            var obj = {
                username: req.body.username,
                appID: req.body.appID
            };
            console.log("User: " + req.user.username + ' obj: ' + obj.username);
            console.log("appID: " + obj.appID);
            reqDebug(req);

            if (req.user.username === obj.username) {
                venueController.addGoingUser(obj, (err) => {
                    if (err) res.sendStatus(500);
                    else res.sendStatus(200);
                });
            }
            else {
                res.sendStatus(401); // Mismatch between usernames
            }
        });

    //---------------------
    // Routes for searching
    //---------------------
    app.route('/search/:q')
        .get((req, res) => {
            console.log("SearchController search was called. Body: " +
                JSON.stringify(req.body)
            );
            console.log("req.params: " + JSON.stringify(req.params));
            var q = req.params.q;
            searchController.search(q, (err, data) => {
                res.json(data);
            });
        });

    //--------------------------------------
    // User registration and authentication
    //--------------------------------------

	app.route('/api/:id')
		.get((req, res) => {
            userController.getUser(req, res);
		});

    // Logs user in via form (after successful authentication
	app.route('/auth/userlogin')
        .post(passport.authenticate('local',
            { failureRedirect: '/loginFailed' }),
		(req, res) => {
			res.redirect('/');
		});

};
<commit_msg>Returns 500 if there's an error with search.<commit_after>'use strict';

var path = process.cwd();
var ctrlPath = path + '/app/controllers';
const UserController = require(ctrlPath + '/userController.server.js');
const SearchController = require(ctrlPath + '/searchController.server.js');
const VenueController = require(ctrlPath + '/venueController.server.js');

var $DEBUG = 0;

var _log = function(msg) {
    console.log("\t" + msg);
};

/** Function for debug logging request.*/
var reqDebug = function(req) {
	_log("Headers: " + JSON.stringify(req.headers));
	_log("Body: "    + JSON.stringify(req.body));
	_log("Params: "  + JSON.stringify(req.params));
	_log("Url:"      + JSON.stringify(req.url));
	_log("Text:"     + JSON.stringify(req.text));
	_log("Content:"  + JSON.stringify(req.content));
	_log("Query:"    + JSON.stringify(req.query));
};

module.exports = function (app, passport) {

    /** Renders a pug template.*/
    var renderPug = function(req, res, pugFile) {
        var isAuth = req.isAuthenticated();
        res.render(path + "/pug/" + pugFile, {isAuth: isAuth});
    };

    /** loggedIn func from clementine.js. */
	var isLoggedIn = function(req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

    // CONTROLLERS
    var userController = new UserController(path);
    var searchController = new SearchController();
    var venueController = new VenueController();

    //----------------------------------------------------------------------
    // ROUTES
    //----------------------------------------------------------------------

	app.route('/')
		.get((req, res) => {
            renderPug(req, res, "index.pug");
            //res.sendFile(path + "/pug/index.pug");
		});

	app.route('/about')
		.get((req, res) => {
            renderPug(req, res, "about.pug");
		});

	app.route('/signup')
		.get((req, res) => {
            renderPug(req, res, "signup.pug");
		});

	app.route('/login')
		.get((req, res) => {
            renderPug(req, res, "login.pug");
		});

	app.route('/loginFailed')
		.get((req, res) => {
            res.render(path + "/pug/login.pug",
                {isAuth: false, loginFailed: true});
        });

    // If a user logs out, return to main page
	app.route('/logout')
		.get((req, res) => {
			req.logout();
			res.redirect('/');
		});

	app.route('/profile')
		.get(isLoggedIn, (req, res) => {
            renderPug(req, res, "profile.pug");
		});

    // Handle registration of user
    app.route('/forms/signup')
        .post((req, res) => {
            if ($DEBUG) {
                console.log("Got a signup form GET request..");
                reqDebug(req);
            }
            userController.addLocalUser(req, res);
        });

    // Called by client to check their authentication status
	app.route('/amiauth')
		.get((req, res) => {
            var data = {isAuth: false};
            if (req.isAuthenticated()) {
                data.isAuth = true;
                data.username = req.user.username;
            }
            res.json(data);
		});

    //----------------------------------
    // Routes for manipulating user data
    //----------------------------------

    /** Marks user as going or not going for an event. */
    app.route('/going')
        .post(isLoggedIn, (req, res) => {
            var obj = {
                username: req.body.username,
                appID: req.body.appID
            };
            console.log("User: " + req.user.username + ' obj: ' + obj.username);
            console.log("appID: " + obj.appID);
            reqDebug(req);

            if (req.user.username === obj.username) {
                venueController.addGoing(obj, (err) => {
                    if (err) res.sendStatus(500);
                    else res.sendStatus(200);
                });
            }
            else {
                res.sendStatus(401); // Mismatch between usernames
            }
        });

    //---------------------
    // Routes for searching
    //---------------------
    app.route('/search/:q')
        .get((req, res) => {
            console.log("SearchController search was called. Body: " +
                JSON.stringify(req.body)
            );
            console.log("get /search/:q req.params: " + JSON.stringify(req.params));
            var q = req.params.q;
            searchController.search(q, (err, data) => {
                if (err) {
                    res.sendStatus(500);
                }
                else if (data) {
                    res.json(data);
                }
                else {
                    res.sendStatus(500);
                }
            });
        });

    //--------------------------------------
    // User registration and authentication
    //--------------------------------------

	app.route('/api/:id')
		.get((req, res) => {
            userController.getUser(req, res);
		});

    // Logs user in via form (after successful authentication
	app.route('/auth/userlogin')
        .post(passport.authenticate('local',
            { failureRedirect: '/loginFailed' }),
		(req, res) => {
			res.redirect('/');
		});

};
<|endoftext|>


<commit_before>#!/usr/bin/env node
;(function() {
  'use strict';

  /** Load Node.js modules */
  var fs = require('fs'),
      path = require('path');

  /** Add `path.sep` for older versions of Node.js */
  path.sep || (path.sep = process.platform == 'win32' ? '\\' : '/');

  /*--------------------------------------------------------------------------*/

  /**
   * Makes the given `path` directory, without throwing errors for existing
   * directories and making parent directories as needed.
   *
   * @param {String} dirname The path of the directory.
   * @param {Number|String} mode The permission mode.
   */
  function mkdirpSync(dirname, mode) {
    var sep = path.sep,
        type = typeof mode;

    // ensure relative paths are prefixed with `./`
    if (!RegExp('^\\.?' + sep).test(dirname)) {
      dirname = '.' + sep + dirname;
    }
    if (!(type == 'number' || type == 'string')) {
      mode = '0777';
    }
    dirname.split(sep).reduce(function(currPath, segment, index) {
      // skip leading separator of absolute paths
      if (index === 0 && currPath === '') {
        return sep;
      }
      segment = currPath + (currPath === sep ? segment : sep + segment);
      try {
        segment = fs.realpathSync(segment);
      } catch(e) {
        fs.mkdirSync(segment, mode);
      }
      return segment;
    });
  }

  /*--------------------------------------------------------------------------*/

  // expose
  module.exports = mkdirpSync;
}());
<commit_msg>Simplify build/mkdirp-sync.js.<commit_after>#!/usr/bin/env node
;(function() {
  'use strict';

  /** Load Node.js modules */
  var fs = require('fs'),
      path = require('path');

  /** Add `path.sep` for older versions of Node.js */
  path.sep || (path.sep = process.platform == 'win32' ? '\\' : '/');

  /*--------------------------------------------------------------------------*/

  /**
   * Makes the given `dirname` directory, without throwing errors for existing
   * directories and making parent directories as needed.
   *
   * @param {String} dirname The path of the directory.
   * @param {Number|String} [mode='0777'] The permission mode.
   */
  function mkdirpSync(dirname, mode) {
    var sep = path.sep;

    // ensure relative paths are prefixed with `./`
    if (!RegExp('^\\.?' + sep).test(dirname)) {
      dirname = '.' + sep + dirname;
    }
    dirname.split(sep).reduce(function(currPath, segment) {
      currPath += sep + segment;
      try {
        currPath = fs.realpathSync(currPath);
      } catch(e) {
        fs.mkdirSync(currPath, mode);
      }
      return currPath;
    });
  }

  /*--------------------------------------------------------------------------*/

  // expose
  module.exports = mkdirpSync;
}());
<|endoftext|>


<commit_before>(function() {
  /* var blacklist = ['type', 'id'];
  var treeString = this.stringify(blacklist).split('"').join('');
  this.dom.tree.firstChild.textContent = `${this.domID}: ${treeString}`;

  var longestLine = treeString.split('\n').reduce(function(a, b) {
    return a.length > b.length ? a : b;
  });
  // HACK: change 84 to a non-hardcoded value
  this.dom.tree.style.width =
    `${Math.min(longestLine.length + 4, 84)}ch`; */

  /* for (let child of this.children) {
    simple.children[child.domID] = child;
  } */

  draft.Group.mixin({
    tree() {
      if (this._tree === undefined) {
        var domPrefix = `${this.domID}:tree`;
        if (this.doc !== undefined) {
          domPrefix = `${this.doc.domID}:${domPrefix}`;
        }
        var domID = function(element) {
          return `${domPrefix}:${element.domID}`;
        };

        var find = function(element) {
          return document.getElementByID(domID(element));
        };

        var render = function(element) {
          var node = document.createElement('li');
          node.id = domID(element);
          node.className = 'draft-tree-element';

          var id = document.createElement('strong');
          id.textContent = `${element.domID}`;
          node.appendChild(id);

          var propNode = document.createElement('div');
          node.appendChild(propNode);

          var propButton = document.createElement('input');
          // TODO: ensure unique id
          propButton.id = `${node.id}:properties`;
          propButton.setAttribute('type', 'checkbox');
          propButton.setAttribute('checked', null);
          propNode.appendChild(propButton);

          var propLabel = document.createElement('label');
          propLabel.textContent = 'properties:';
          propLabel.setAttribute('for', propButton.id);
          propNode.appendChild(propLabel);

          var propList = document.createElement('ol');
          propNode.appendChild(propList);

          // TODO: remove props, use document.getElementByID instead
          var props = {};
          for (let prop in element.prop()) {
            let item = document.createElement('li');
            item.textContent = `${prop}: ${element.prop(prop)}`;
            props[prop] = item;
            propList.appendChild(item);
          }

          element.on('change', function(prop, val) {
            if (val === null) {
              propList.removeChild(props[prop]);
            } else {
              if (!props.hasOwnProperty(prop)) {
                let item = document.createElement('li');
                props[prop] = item;
                propList.appendChild(item);
              }

              props[prop].textContent = `${prop}: ${val}`;
            }
          });

          // TODO: do a faster check than instanceof
          // Extra code to handle elements that have children
          if (element instanceof draft.Group) {
            let childNode = document.createElement('div');
            node.appendChild(childNode);

            let button = document.createElement('input');
            // TODO: ensure unique id
            button.id = `${node.id}:children`;
            button.setAttribute('type', 'checkbox');
            button.setAttribute('checked', null);
            childNode.appendChild(button);

            let label = document.createElement('label');
            label.textContent = 'children:';
            label.setAttribute('for', button.id);
            childNode.appendChild(label);

            let list = document.createElement('ol');
            childNode.appendChild(list);

            for (let child of element.children) {
              list.appendChild(render(child));
            }

            element.on('add', function(child) {
              list.appendChild(render(child));
            });

            element.on('remove', function(child) {
              list.removeChild(find(child));
            });
          }

          return node;
        };

        var tree = this._tree = document.createElement('div');
        tree.className = 'draft-tree';

        var list = document.createElement('ul');
        list.appendChild(render(this));
        list.firstChild.className = '';
        tree.appendChild(list);
      }

      return this._tree;
    }
  });

  /* var css = document.createElement('link');
  css.setAttribute('rel', 'stylesheet');
  css.setAttribute('type', 'text/css');
  css.setAttribute('href', 'bower_components/draft-treeview/main.css');

  document.getElementsByTagName('head')[0].appendChild(css); */
})();
<commit_msg>Delete old comments<commit_after>(function() {
  /* var blacklist = ['type', 'id'];
  var treeString = this.stringify(blacklist).split('"').join('');
  this.dom.tree.firstChild.textContent = `${this.domID}: ${treeString}`;

  var longestLine = treeString.split('\n').reduce(function(a, b) {
    return a.length > b.length ? a : b;
  });
  // HACK: change 84 to a non-hardcoded value
  this.dom.tree.style.width =
    `${Math.min(longestLine.length + 4, 84)}ch`; */

  draft.Group.mixin({
    tree() {
      if (this._tree === undefined) {
        var domPrefix = `${this.domID}:tree`;
        if (this.doc !== undefined) {
          domPrefix = `${this.doc.domID}:${domPrefix}`;
        }
        var domID = function(element) {
          return `${domPrefix}:${element.domID}`;
        };

        var find = function(element) {
          return document.getElementByID(domID(element));
        };

        var render = function(element) {
          var node = document.createElement('li');
          node.id = domID(element);
          node.className = 'draft-tree-element';

          var id = document.createElement('strong');
          id.textContent = `${element.domID}`;
          node.appendChild(id);

          var propNode = document.createElement('div');
          node.appendChild(propNode);

          var propButton = document.createElement('input');
          // TODO: ensure unique id
          propButton.id = `${node.id}:properties`;
          propButton.setAttribute('type', 'checkbox');
          propButton.setAttribute('checked', null);
          propNode.appendChild(propButton);

          var propLabel = document.createElement('label');
          propLabel.textContent = 'properties:';
          propLabel.setAttribute('for', propButton.id);
          propNode.appendChild(propLabel);

          var propList = document.createElement('ol');
          propNode.appendChild(propList);

          // TODO: remove props, use document.getElementByID instead
          var props = {};
          for (let prop in element.prop()) {
            let item = document.createElement('li');
            item.textContent = `${prop}: ${element.prop(prop)}`;
            props[prop] = item;
            propList.appendChild(item);
          }

          element.on('change', function(prop, val) {
            if (val === null) {
              propList.removeChild(props[prop]);
            } else {
              if (!props.hasOwnProperty(prop)) {
                let item = document.createElement('li');
                props[prop] = item;
                propList.appendChild(item);
              }

              props[prop].textContent = `${prop}: ${val}`;
            }
          });

          // TODO: do a faster check than instanceof
          // Extra code to handle elements that have children
          if (element instanceof draft.Group) {
            let childNode = document.createElement('div');
            node.appendChild(childNode);

            let button = document.createElement('input');
            // TODO: ensure unique id
            button.id = `${node.id}:children`;
            button.setAttribute('type', 'checkbox');
            button.setAttribute('checked', null);
            childNode.appendChild(button);

            let label = document.createElement('label');
            label.textContent = 'children:';
            label.setAttribute('for', button.id);
            childNode.appendChild(label);

            let list = document.createElement('ol');
            childNode.appendChild(list);

            for (let child of element.children) {
              list.appendChild(render(child));
            }

            element.on('add', function(child) {
              list.appendChild(render(child));
            });

            element.on('remove', function(child) {
              list.removeChild(find(child));
            });
          }

          return node;
        };

        var tree = this._tree = document.createElement('div');
        tree.className = 'draft-tree';

        var list = document.createElement('ul');
        list.appendChild(render(this));
        list.firstChild.className = '';
        tree.appendChild(list);
      }

      return this._tree;
    }
  });
})();
<|endoftext|>