<commit_before>// script.aculo.us unittest.js v1.7.1_beta3, Fri May 25 17:19:41 +0200 2007

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
//           (c) 2005-2007 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
  var options = Object.extend({
    pointerX: 0,
    pointerY: 0,
    buttons:  0,
    ctrlKey:  false,
    altKey:   false,
    shiftKey: false,
    metaKey:  false
  }, arguments[2] || {});
  var oEvent = document.createEvent("MouseEvents");
  oEvent.initMouseEvent(eventName, true, true, document.defaultView,
    options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
    options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));

  if(this.mark) Element.remove(this.mark);
  this.mark = document.createElement('div');
  this.mark.appendChild(document.createTextNode(" "));
  document.body.appendChild(this.mark);
  this.mark.style.position = 'absolute';
  this.mark.style.top = options.pointerY + "px";
  this.mark.style.left = options.pointerX + "px";
  this.mark.style.width = "5px";
  this.mark.style.height = "5px;";
  this.mark.style.borderTop = "1px solid red;"
  this.mark.style.borderLeft = "1px solid red;"

  if(this.step)
    alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));

  $(element).dispatchEvent(oEvent);
};

// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
  var options = Object.extend({
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    keyCode: 0,
    charCode: 0
  }, arguments[2] || {});

  var oEvent = document.createEvent("KeyEvents");
  oEvent.initKeyEvent(eventName, true, true, window,
    options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
    options.keyCode, options.charCode );
  $(element).dispatchEvent(oEvent);
};

Event.simulateKeys = function(element, command) {
  for(var i=0; i<command.length; i++) {
    Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
  }
};

var Test = {}
Test.Unit = {};

// security exception workaround
Test.Unit.inspect = Object.inspect;

Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
  initialize: function(log) {
    this.log = $(log);
    if (this.log) {
      this._createLogTable();
    }
  },
  start: function(testName) {
    if (!this.log) return;
    this.testName = testName;
    this.lastLogLine = document.createElement('tr');
    this.statusCell = document.createElement('td');
    this.nameCell = document.createElement('td');
    this.nameCell.className = "nameCell";
    this.nameCell.appendChild(document.createTextNode(testName));
    this.messageCell = document.createElement('td');
    this.lastLogLine.appendChild(this.statusCell);
    this.lastLogLine.appendChild(this.nameCell);
    this.lastLogLine.appendChild(this.messageCell);
    this.loglines.appendChild(this.lastLogLine);
  },
  finish: function(status, summary) {
    if (!this.log) return;
    this.lastLogLine.className = status;
    this.statusCell.innerHTML = status;
    this.messageCell.innerHTML = this._toHTML(summary);
    this.addLinksToResults();
  },
  message: function(message) {
    if (!this.log) return;
    this.messageCell.innerHTML = this._toHTML(message);
  },
  summary: function(summary) {
    if (!this.log) return;
    this.logsummary.innerHTML = this._toHTML(summary);
  },
  _createLogTable: function() {
    this.log.innerHTML =
    '

' +
    '
' +
    '

Status	Test	Message

' +
    '

' +
    '
';
    this.logsummary = $('logsummary')
    this.loglines = $('loglines');
  },
  _toHTML: function(txt) {
    return txt.escapeHTML().replace(/\n/g,"
");
  },
  addLinksToResults: function(){
    $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
      td.title = "Run only this test"
      Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
    });
    $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
      td.title = "Run all tests"
      Event.observe(td, 'click', function(){ window.location.search = "";});
    });
  }
}

Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
  initialize: function(testcases) {
    this.options = Object.extend({
      testLog: 'testlog'
    }, arguments[1] || {});
    this.options.resultsURL = this.parseResultsURLQueryParameter();
    this.options.tests      = this.parseTestsQueryParameter();
    if (this.options.testLog) {
      this.options.testLog = $(this.options.testLog) || null;
    }
    if(this.options.tests) {
      this.tests = [];
      for(var i = 0; i < this.options.tests.length; i++) {
        if(/^test/.test(this.options.tests[i])) {
          this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
        }
      }
    } else {
      if (this.options.test) {
        this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
      } else {
        this.tests = [];
        for(var testcase in testcases) {
          if(/^test/.test(testcase)) {
            this.tests.push(
               new Test.Unit.Testcase(
                 this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
                 testcases[testcase], testcases["setup"], testcases["teardown"]
               ));
          }
        }
      }
    }
    this.currentTest = 0;
    this.logger = new Test.Unit.Logger(this.options.testLog);
    setTimeout(this.runTests.bind(this), 1000);
  },
  parseResultsURLQueryParameter: function() {
    return window.location.search.parseQuery()["resultsURL"];
  },
  parseTestsQueryParameter: function(){
    if (window.location.search.parseQuery()["tests"]){
        return window.location.search.parseQuery()["tests"].split(',');
    };
  },
  // Returns:
  //  "ERROR" if there was an error,
  //  "FAILURE" if there was a failure, or
  //  "SUCCESS" if there was neither
  getResult: function() {
    var hasFailure = false;
    for(var i=0;i<this.tests.length;i++) {
      if (this.tests[i].errors > 0) {
        return "ERROR";
      }
      if (this.tests[i].failures > 0) {
        hasFailure = true;
      }
    }
    if (hasFailure) {
      return "FAILURE";
    } else {
      return "SUCCESS";
    }
  },
  postResults: function() {
    if (this.options.resultsURL) {
      new Ajax.Request(this.options.resultsURL,
        { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
    }
  },
  runTests: function() {
    var test = this.tests[this.currentTest];
    if (!test) {
      // finished!
      this.postResults();
      this.logger.summary(this.summary());
      return;
    }
    if(!test.isWaiting) {
      this.logger.start(test.name);
    }
    test.run();
    if(test.isWaiting) {
      this.logger.message("Waiting for " + test.timeToWait + "ms");
      setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
    } else {
      this.logger.finish(test.status(), test.summary());
      this.currentTest++;
      // tail recursive, hopefully the browser will skip the stackframe
      this.runTests();
    }
  },
  summary: function() {
    var assertions = 0;
    var failures = 0;
    var errors = 0;
    var messages = [];
    for(var i=0;i<this.tests.length;i++) {
      assertions +=   this.tests[i].assertions;
      failures   +=   this.tests[i].failures;
      errors     +=   this.tests[i].errors;
    }
    return (
      (this.options.context ? this.options.context + ': ': '') +
      this.tests.length + " tests, " +
      assertions + " assertions, " +
      failures   + " failures, " +
      errors     + " errors");
  }
}

Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
  initialize: function() {
    this.assertions = 0;
    this.failures   = 0;
    this.errors     = 0;
    this.messages   = [];
  },
  summary: function() {
    return (
      this.assertions + " assertions, " +
      this.failures   + " failures, " +
      this.errors     + " errors" + "\n" +
      this.messages.join("\n"));
  },
  pass: function() {
    this.assertions++;
  },
  fail: function(message) {
    this.failures++;
    this.messages.push("Failure: " + message);
  },
  info: function(message) {
    this.messages.push("Info: " + message);
  },
  error: function(error) {
    this.errors++;
    this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
  },
  status: function() {
    if (this.failures > 0) return 'failed';
    if (this.errors > 0) return 'error';
    return 'passed';
  },
  assert: function(expression) {
    var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
    try { expression ? this.pass() :
      this.fail(message); }
    catch(e) { this.error(e); }
  },
  assertEqual: function(expected, actual) {
    var message = arguments[2] || "assertEqual";
    try { (expected == actual) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertInspect: function(expected, actual) {
    var message = arguments[2] || "assertInspect";
    try { (expected == actual.inspect()) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertEnumEqual: function(expected, actual) {
    var message = arguments[2] || "assertEnumEqual";
    try { $A(expected).length == $A(actual).length &&
      expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
        this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
          ', actual ' + Test.Unit.inspect(actual)); }
    catch(e) { this.error(e); }
  },
  assertNotEqual: function(expected, actual) {
    var message = arguments[2] || "assertNotEqual";
    try { (expected != actual) ? this.pass() :
      this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertIdentical: function(expected, actual) {
    var message = arguments[2] || "assertIdentical";
    try { (expected === actual) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertNotIdentical: function(expected, actual) {
    var message = arguments[2] || "assertNotIdentical";
    try { !(expected === actual) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertNull: function(obj) {
    var message = arguments[1] || 'assertNull'
    try { (obj==null) ? this.pass() :
      this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
    catch(e) { this.error(e); }
  },
  assertMatch: function(expected, actual) {
    var message = arguments[2] || 'assertMatch';
    var regex = new RegExp(expected);
    try { (regex.exec(actual)) ? this.pass() :
      this.fail(message + ' : regex: "' +  Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertHidden: function(element) {
    var message = arguments[1] || 'assertHidden';
    this.assertEqual("none", element.style.display, message);
  },
  assertNotNull: function(object) {
    var message = arguments[1] || 'assertNotNull';
    this.assert(object != null, message);
  },
  assertType: function(expected, actual) {
    var message = arguments[2] || 'assertType';
    try {
      (actual.constructor == expected) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + (actual.constructor) + '"'); }
    catch(e) { this.error(e); }
  },
  assertNotOfType: function(expected, actual) {
    var message = arguments[2] || 'assertNotOfType';
    try {
      (actual.constructor != expected) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + (actual.constructor) + '"'); }
    catch(e) { this.error(e); }
  },
  assertInstanceOf: function(expected, actual) {
    var message = arguments[2] || 'assertInstanceOf';
    try {
      (actual instanceof expected) ? this.pass() :
      this.fail(message + ": object was not an instance of the expected type"); }
    catch(e) { this.error(e); }
  },
  assertNotInstanceOf: function(expected, actual) {
    var message = arguments[2] || 'assertNotInstanceOf';
    try {
      !(actual instanceof expected) ? this.pass() :
      this.fail(message + ": object was an instance of the not expected type"); }
    catch(e) { this.error(e); }
  },
  assertRespondsTo: function(method, obj) {
    var message = arguments[2] || 'assertRespondsTo';
    try {
      (obj[method] && typeof obj[method] == 'function') ? this.pass() :
      this.fail(message + ": object doesn't respond to [" + method + "]"); }
    catch(e) { this.error(e); }
  },
  assertReturnsTrue: function(method, obj) {
    var message = arguments[2] || 'assertReturnsTrue';
    try {
      var m = obj[method];
      if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
      m() ? this.pass() :
      this.fail(message + ": method returned false"); }
    catch(e) { this.error(e); }
  },
  assertReturnsFalse: function(method, obj) {
    var message = arguments[2] || 'assertReturnsFalse';
    try {
      var m = obj[method];
      if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
      !m() ? this.pass() :
      this.fail(message + ": method returned true"); }
    catch(e) { this.error(e); }
  },
  assertRaise: function(exceptionName, method) {
    var message = arguments[2] || 'assertRaise';
    try {
      method();
      this.fail(message + ": exception expected but none was raised"); }
    catch(e) {
      ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
    }
  },
  assertElementsMatch: function() {
    var expressions = $A(arguments), elements = $A(expressions.shift());
    if (elements.length != expressions.length) {
      this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
      return false;
    }
    elements.zip(expressions).all(function(pair, index) {
      var element = $(pair.first()), expression = pair.last();
      if (element.match(expression)) return true;
      this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
    }.bind(this)) && this.pass();
  },
  assertElementMatches: function(element, expression) {
    this.assertElementsMatch([element], expression);
  },
  benchmark: function(operation, iterations) {
    var startAt = new Date();
    (iterations || 1).times(operation);
    var timeTaken = ((new Date())-startAt);
    this.info((arguments[2] || 'Operation') + ' finished ' +
       iterations + ' iterations in ' + (timeTaken/1000)+'s' );
    return timeTaken;
  },
  _isVisible: function(element) {
    element = $(element);
    if(!element.parentNode) return true;
    this.assertNotNull(element);
    if(element.style && Element.getStyle(element, 'display') == 'none')
      return false;

    return this._isVisible(element.parentNode);
  },
  assertNotVisible: function(element) {
    this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
  },
  assertVisible: function(element) {
    this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
  },
  benchmark: function(operation, iterations) {
    var startAt = new Date();
    (iterations || 1).times(operation);
    var timeTaken = ((new Date())-startAt);
    this.info((arguments[2] || 'Operation') + ' finished ' +
       iterations + ' iterations in ' + (timeTaken/1000)+'s' );
    return timeTaken;
  }
}

Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
  initialize: function(name, test, setup, teardown) {
    Test.Unit.Assertions.prototype.initialize.bind(this)();
    this.name           = name;

    if(typeof test == 'string') {
      test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
      test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
      this.test = function() {
        eval('with(this){'+test+'}');
      }
    } else {
      this.test = test || function() {};
    }

    this.setup          = setup || function() {};
    this.teardown       = teardown || function() {};
    this.isWaiting      = false;
    this.timeToWait     = 1000;
  },
  wait: function(time, nextPart) {
    this.isWaiting = true;
    this.test = nextPart;
    this.timeToWait = time;
  },
  run: function() {
    try {
      try {
        if (!this.isWaiting) this.setup.bind(this)();
        this.isWaiting = false;
        this.test.bind(this)();
      } finally {
        if(!this.isWaiting) {
          this.teardown.bind(this)();
        }
      }
    }
    catch(e) { this.error(e); }
  }
});

// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/

Test.setupBDDExtensionMethods = function(){
  var METHODMAP = {
    shouldEqual:     'assertEqual',
    shouldNotEqual:  'assertNotEqual',
    shouldEqualEnum: 'assertEnumEqual',
    shouldBeA:       'assertType',
    shouldNotBeA:    'assertNotOfType',
    shouldBeAn:      'assertType',
    shouldNotBeAn:   'assertNotOfType',
    shouldBeNull:    'assertNull',
    shouldNotBeNull: 'assertNotNull',

    shouldBe:        'assertReturnsTrue',
    shouldNotBe:     'assertReturnsFalse',
    shouldRespondTo: 'assertRespondsTo'
  };
  Test.BDDMethods = {};
  for(m in METHODMAP) {
    Test.BDDMethods[m] = eval(
      'function(){'+
      'var args = $A(arguments);'+
      'var scope = args.shift();'+
      'scope.'+METHODMAP[m]+'.apply(scope,(args || []).concat([this])); }');
  }
  [Array.prototype, String.prototype, Number.prototype].each(
    function(p){ Object.extend(p, Test.BDDMethods) }
  );
}

Test.context = function(name, spec, log){
  Test.setupBDDExtensionMethods();

  var compiledSpec = {};
  var titles = {};
  for(specName in spec) {
    switch(specName){
      case "setup":
      case "teardown":
        compiledSpec[specName] = spec[specName];
        break;
      default:
        var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
        var body = spec[specName].toString().split('\n').slice(1);
        if(/^\{/.test(body[0])) body = body.slice(1);
        body.pop();
        body = body.map(function(statement){
          return statement.strip()
        });
        compiledSpec[testName] = body.join('\n');
        titles[testName] = specName;
    }
  }
  new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
};<commit_msg>Removed unittests for scriptaculous<commit_after><|endoftext|>


<commit_before>Meteor.publish('algoParticular',function(algoID){
	return AlgoPedia.find({AiD:algoID});
});

Meteor.publish('allLangs',function(){
	return Languages.find();
});

Meteor.publish('codeByAlgo',function(algoID){
	return LSIs.find({pAiD:algoID});
});

Meteor.publish('codeByAlgoAndLang',function(algoID,langSlug){
	var lang = Languages.findOne({Slug:langSlug});
	return LSIs.find({pAiD:algoID,Language:lang.Name});
});

Meteor.publish('codeByLang',function(langSlug){
	var lang = Languages.findOne({Slug:langSlug});
	return LSIs.find({Language:lang.Name});
});

Meteor.publish('getUserAlgos',function(username){
	var user = Meteor.users.findOne({username:username});
	return AlgoPedia.find({Contributor:user._id});
});

Meteor.publish('getAlgosByReg',function(query){
	var queryMod = new RegExp(query);
	return AlgoPedia.find({AiD: { $regex: queryMod}});
});

Meteor.publish('getAlgosByKeyWord',function(query){
	return AlgoPedia.find({KeyWords: { $elemMatch: {Name:query}}});
});
<commit_msg>front page keyword match needs fixing<commit_after>Meteor.publish('algoParticular',function(algoID){
	return AlgoPedia.find({AiD:algoID});
});

Meteor.publish('allLangs',function(){
	return Languages.find();
});

Meteor.publish('codeByAlgo',function(algoID){
	return LSIs.find({pAiD:algoID});
});

Meteor.publish('codeByAlgoAndLang',function(algoID,langSlug){
	var lang = Languages.findOne({Slug:langSlug});
	return LSIs.find({pAiD:algoID,Language:lang.Name});
});

Meteor.publish('codeByLang',function(langSlug){
	var lang = Languages.findOne({Slug:langSlug});
	return LSIs.find({Language:lang.Name});
});

Meteor.publish('getUserAlgos',function(username){
	var user = Meteor.users.findOne({username:username});
	return AlgoPedia.find({Contributor:user._id});
});

Meteor.publish('getAlgosByReg',function(query){
	var queryMod = new RegExp(query);
	return AlgoPedia.find({AiD: { $regex: queryMod}});
});

Meteor.publish('getAlgosByKeyWord',function(query){
	var queryMod = new RegExp(query);
	return AlgoPedia.find({AiD: { $regex: queryMod}});
});
<|endoftext|>


<commit_before>const {joinRoom, addNote} = require('./io-helpers');
const {findRoom} = require('../database/db-helpers');

module.exports = (listen) => {
  const io = require('socket.io').listen(listen);
  const rooms = io.sockets.adapter.rooms;

  io.on('connection', (socket) => {
    //console.log('a user connected');

    socket.on('create room', (pathUrl, userId) => {
      // verify if pathUrl and userId are valid
      if (pathUrl.length === 5 && userId) {
        // verify if room at pathUrl exists in database
        findRoom(pathUrl, (found) => {
          if (found) {
            joinRoom(socket, pathUrl, userId, () => socket.emit('create room success'));
          } else {
            socket.emit('create room error', `Room '${pathUrl}' not found`);
          }
        });
      } else {
        socket.emit('create room error', `Room '${pathUrl}' is invalid`);
      }
    });

    socket.on('join room', (pathUrl, userId) => {
      // verify if pathUrl and userId are valid and if room at pathUrl exists
      if (pathUrl.length === 5 && userId && rooms[pathUrl]) {
        joinRoom(socket, pathUrl, userId, () => socket.emit('join room success'));
        return;
      }
      socket.emit('join room error', `Room '${pathUrl}' was not found`);
    });

    socket.on('lecture start', (pathUrl) => {
      if (socket.pathUrl) {
        io.in(socket.pathUrl).emit('lecture started');
      } else {
        socket.emit('lecture start error', 'You do not belong to a room');
      }
    });

    socket.on('lecture end', (pathUrl) => {
      if (socket.pathUrl) {
        io.in(socket.pathUrl).emit('lecture ended');
      } else {
        socket.emit('lecture end error', 'You do not belong to a room');
      }
    });

    socket.on('new note', (note) => {
      if (note) {
        addNote(socket, note, (result) => socket.emit('add note success', result));
        return;
      }
      socket.emit('add note error', 'Note does not exist you asshat');
    });

    //socket.on('disconnect', () => console.log('a user disconnected'));
  });
  return io;
};
<commit_msg>moved socket error message to else statement<commit_after>const {joinRoom, addNote} = require('./io-helpers');
const {findRoom} = require('../database/db-helpers');

module.exports = (listen) => {
  const io = require('socket.io').listen(listen);
  const rooms = io.sockets.adapter.rooms;

  io.on('connection', (socket) => {
    //console.log('a user connected');

    socket.on('create room', (pathUrl, userId) => {
      // verify if pathUrl and userId are valid
      if (pathUrl.length === 5 && userId) {
        // verify if room at pathUrl exists in database
        findRoom(pathUrl, (found) => {
          if (found) {
            joinRoom(socket, pathUrl, userId, () => socket.emit('create room success'));
          } else {
            socket.emit('create room error', `Room '${pathUrl}' not found`);
          }
        });
      } else {
        socket.emit('create room error', `Room '${pathUrl}' is invalid`);
      }
    });

    socket.on('join room', (pathUrl, userId) => {
      // verify if pathUrl and userId are valid and if room at pathUrl exists
      if (pathUrl.length === 5 && userId && rooms[pathUrl]) {
        joinRoom(socket, pathUrl, userId, () => socket.emit('join room success'));
        return;
      } else {
        socket.emit('join room error', `Room '${pathUrl}' was not found`);
      }
    });

    socket.on('lecture start', (pathUrl) => {
      if (socket.pathUrl) {
        io.in(socket.pathUrl).emit('lecture started');
      } else {
        socket.emit('lecture start error', 'You do not belong to a room');
      }
    });

    socket.on('lecture end', (pathUrl) => {
      if (socket.pathUrl) {
        io.in(socket.pathUrl).emit('lecture ended');
      } else {
        socket.emit('lecture end error', 'You do not belong to a room');
      }
    });

    socket.on('new note', (note) => {
      if (note) {
        addNote(socket, note, (result) => socket.emit('add note success', result));
        return;
      }
      socket.emit('add note error', 'Note does not exist you asshat');
    });

    //socket.on('disconnect', () => console.log('a user disconnected'));
  });
  return io;
};
<|endoftext|>


<commit_before>const redis = require('./redis');
const config = require('../config');
const { randomBid } = require('../simulation/vehicles');
const { getVehicle } = require('../store/vehicles');
const { getNeed } = require('./needs');

const saveBid = async ({ vehicle_id, price, time_to_pickup, time_to_dropoff }, needId, userId) => {
  // get new unique id for bid
  const bidId = await redis.incrAsync('next_bid_id');

  // Save bid id in need_bids
  redis.rpushAsync(`need_bids:${needId}`, bidId);

  // Add bid to bids
  redis.hmsetAsync(`bids:${bidId}`,
    'id', bidId,
    'vehicle_id', vehicle_id,
    'user_id', userId,
    'price', price,
    'time_to_pickup', time_to_pickup,
    'time_to_dropoff', time_to_dropoff,
    'need_id', needId,
  );

  // Set TTL for bid
  redis.expire(`bids:${bidId}`, config('bids_ttl'));
  return bidId;
};

const getBid = async bidId => {
  // Set TTL for bid
  redis.expire(`bids:${bidId}`, config('bids_ttl'));
  return await redis.hgetallAsync(`bids:${bidId}`);
};

const getBidsForNeed = async needId => {
  // get request details
  const need = await getNeed(needId);
  if (!need) return [];

  const userId = need.user_id;

  // get bids for need
  const bidIds = await redis.lrangeAsync(`need_bids:${needId}`, 0, -1);
  const bids = await Promise.all(
    bidIds.map(bidId => {
      redis.expire(`bids:${bidId}`, config('bids_ttl'));
      return redis.hgetallAsync(`bids:${bidId}`);
    }),
  );

  // If not enough bids, make some up
  if (bidIds.length < 10) {
    const { pickup_longitude, pickup_latitude, dropoff_latitude, dropoff_longitude } = need;
    const pickup = { lat: pickup_latitude, long: pickup_longitude };
    const dropoff = { lat: dropoff_latitude, long: dropoff_longitude };
    const vehicleIds = await redis.georadiusAsync(
      'vehicle_positions',
      pickup_longitude,
      pickup_latitude,
      2000,
      'm',
    );
    if (vehicleIds.length > bidIds.length) {
      // Just a hacky way to get more bids from different vehicles.
      // Not guaranteed to not have duplicate bids from same vehicle
      const vehicleId = vehicleIds[bidIds.length];
      const vehicle = await getVehicle(vehicleId);
      const origin = { lat: vehicle.lat, long: vehicle.long };
      let newBid = randomBid(origin, pickup, dropoff);
      newBid.vehicle_id = vehicleId;
      const newBidId = await saveBid(newBid, needId, userId);
      newBid.id = newBidId;
      bids.push(newBid);
    }
  }

  return bids;
};

const deleteBidsForNeed = async needId => {
  const bidIds = await redis.lrangeAsync(`need_bids:${needId}`, 0, -1);
  await Promise.all(
    bidIds.map(bidId => redis.del(`bids:${bidId}`))
  );
  return await redis.del(`need_bids:${needId}`);
};

module.exports = {
  getBidsForNeed,
  getBid,
  deleteBidsForNeed,
};
<commit_msg>issue #156 - Added the function setBidTTL(bidId) to replace repeated lines<commit_after>const redis = require('./redis');
const config = require('../config');
const { randomBid } = require('../simulation/vehicles');
const { getVehicle } = require('../store/vehicles');
const { getNeed } = require('./needs');

const saveBid = async ({ vehicle_id, price, time_to_pickup, time_to_dropoff }, needId, userId) => {
  // get new unique id for bid
  const bidId = await redis.incrAsync('next_bid_id');

  // Save bid id in need_bids
  redis.rpushAsync(`need_bids:${needId}`, bidId);

  // Add bid to bids
  redis.hmsetAsync(`bids:${bidId}`,
    'id', bidId,
    'vehicle_id', vehicle_id,
    'user_id', userId,
    'price', price,
    'time_to_pickup', time_to_pickup,
    'time_to_dropoff', time_to_dropoff,
    'need_id', needId,
  );

  // Set TTL for bid
  setBidTTL(bidId);
  return bidId;
};

const getBid = async bidId => {
  // Set TTL for bid
  setBidTTL(bidId);
  return await redis.hgetallAsync(`bids:${bidId}`);
};

const getBidsForNeed = async needId => {
  // get request details
  const need = await getNeed(needId);
  if (!need) return [];

  const userId = need.user_id;

  // get bids for need
  const bidIds = await redis.lrangeAsync(`need_bids:${needId}`, 0, -1);
  const bids = await Promise.all(
    bidIds.map(bidId => {
      setBidTTL(bidId);
      return redis.hgetallAsync(`bids:${bidId}`);
    }),
  );

  // If not enough bids, make some up
  if (bidIds.length < 10) {
    const { pickup_longitude, pickup_latitude, dropoff_latitude, dropoff_longitude } = need;
    const pickup = { lat: pickup_latitude, long: pickup_longitude };
    const dropoff = { lat: dropoff_latitude, long: dropoff_longitude };
    const vehicleIds = await redis.georadiusAsync(
      'vehicle_positions',
      pickup_longitude,
      pickup_latitude,
      2000,
      'm',
    );
    if (vehicleIds.length > bidIds.length) {
      // Just a hacky way to get more bids from different vehicles.
      // Not guaranteed to not have duplicate bids from same vehicle
      const vehicleId = vehicleIds[bidIds.length];
      const vehicle = await getVehicle(vehicleId);
      const origin = { lat: vehicle.lat, long: vehicle.long };
      let newBid = randomBid(origin, pickup, dropoff);
      newBid.vehicle_id = vehicleId;
      const newBidId = await saveBid(newBid, needId, userId);
      newBid.id = newBidId;
      bids.push(newBid);
    }
  }

  return bids;
};

const deleteBidsForNeed = async needId => {
  const bidIds = await redis.lrangeAsync(`need_bids:${needId}`, 0, -1);
  await Promise.all(
    bidIds.map(bidId => redis.del(`bids:${bidId}`))
  );
  return await redis.del(`need_bids:${needId}`);
};

module.exports = {
  getBidsForNeed,
  getBid,
  deleteBidsForNeed,
};

const setBidTTL = async bidId => redis.expire(`bids:${bidId}`, config('bids_ttl'));<|endoftext|>


<commit_before>(function(){

    angular.module('bp.directives', [])
        .directive('bpNavEjercicios', function(){
            return {
                //Hay varios tipos de directivas, está será de tipo elemento.
                restrict: 'E',
                templateUrl: 'partials/bp-nav-ejercicios.html'
            };
        })
        .directive('bpNavOperaciones', function(){
            return {
                //Hay varios tipos de directivas, está será de tipo elemento.
                restrict: 'E',
                templateUrl: 'partials/bp-nav-operaciones.html'
            };
        });
})();
<commit_msg>Corregido arror en las directivas<commit_after>(function(){

    angular.module('bp.directives', [])
        .directive('bpNavEjercicios', function(){
            return {
                //Hay varios tipos de directivas, está será de tipo elemento.
                restrict: 'E',
                templateUrl: 'partials/bp-nav-ejercicios.html',
                controller: 'bpController'
            };
        })
        .directive('bpNavOperaciones', function(){
            return {
                //Hay varios tipos de directivas, está será de tipo elemento.
                restrict: 'E',
                templateUrl: 'partials/bp-nav-operaciones.html',
                controller: 'bpController'
            };
        });
})();
<|endoftext|>


<commit_before>import url from 'url'
import jwt from 'jsonwebtoken'
import fetch from 'isomorphic-fetch'
import getBullQueue from 'bull'
import socketCluster from 'socketcluster-client'

import config from 'src/config'
import {graphQLErrorHandler} from 'src/common/util/getGraphQLFetcher'

const JWT_ISSUER = 'learnersguild.org'

// TODO: fix this! we're effectively using module caching to create a singleton. yuck.
let socket = null

export function serverToServerJWT() {
  /* eslint-disable camelcase */
  const now = Math.floor(Date.now() / 1000)
  const claims = {
    iss: JWT_ISSUER,
    iat: now,
    exp: now + (60 * 10),  // 10 minutes from now
    sub: 0,
    name: 'Server-to-Server Authentication',
    preferred_username: '__server_to_server__',
    email: 'noreply@learnersguild.org',
    emails: 'noreply@learnersguild.org',
    roles: 'backoffice',
  }
  return jwt.sign(claims, config.server.jwt.privateKey, {algorithm: config.server.jwt.algorithm})
}

export function graphQLFetcher(baseURL, lgJWT = serverToServerJWT()) {
  return graphQLParams => {
    const options = {
      method: 'post',
      headers: {
        'Authorization': `Bearer ${lgJWT}`,
        'Origin': config.server.baseURL,
        'Content-Type': 'application/json',
        'LearnersGuild-Skip-Update-User-Middleware': 1,
      },
      body: JSON.stringify(graphQLParams),
    }

    return fetch(`${baseURL}/graphql`, options)
      .then(resp => {
        if (!resp.ok) {
          return Promise.reject(`GraphQL request resulted in an ERROR: ${resp.statusText}`)
        }
        return resp.json()
      })
      .then(graphQLErrorHandler)
  }
}

export function getQueue(queueName) {
  const redisConfig = url.parse(config.server.redis.url)
  /* eslint-disable camelcase */
  const redisOpts = redisConfig.auth ? {auth_pass: redisConfig.auth.split(':')[1]} : undefined
  return getBullQueue(queueName, redisConfig.port, redisConfig.hostname, redisOpts)
}

export function getSocket() {
  if (socket) {
    return socket
  }

  socket = socketCluster.connect({hostname: config.server.sockets.host})
  socket.on('connect', () => console.log('... socket connected'))
  socket.on('disconnect', () => console.log('socket disconnected, will try to reconnect socket ...'))
  socket.on('connectAbort', () => null)
  socket.on('error', error => console.warn(error.message))

  return socket
}

export function sum(values) {
  if (!Array.isArray(values)) {
    return null
  }
  return values.reduce((result, n) => result + n, 0)
}

export function avg(values) {
  const sumValues = sum(values)
  if (isNaN(sumValues)) {
    return sumValues
  }
  if (sumValues === 0) {
    return 0
  }
  return (sumValues / values.length)
}

export function toPercent(num) {
  return isNaN(num) ? NaN : (num * 100)
}

export function toArray(val) {
  if (Array.isArray(val)) {
    return val
  }
  if (val instanceof Map) {
    return Array.from(val.values())
  }
  return [val]
}

export function toPairs(arr) {
  if (!Array.isArray(arr)) {
    return null
  }
  if (arr.length < 2) {
    return []
  }
  const pairs = []
  for (let i = 0, len = arr.length - 1; i < len; i++) {
    for (let j = (i + 1); j < arr.length; j++) {
      pairs.push([arr[i], arr[j]])
    }
  }
  return pairs
}

export function roundDecimal(num) {
  return isNaN(num) ? null : (Math.round((num + 0.00001) * 100) / 100)
}

export function pickRandom(arr) {
  if (!Array.isArray(arr)) {
    return null
  }
  return arr[Math.floor(Math.random() * arr.length)]
}

export function shuffle(arr) {
  const shuffled = toArray(arr)

  let j
  let x
  for (let i = shuffled.length; i; i--) {
    j = Math.floor(Math.random() * i)
    x = shuffled[i - 1]
    shuffled[i - 1] = shuffled[j]
    shuffled[j] = x
  }

  return shuffled
}

export function mapById(arr) {
  return arr.reduce((result, el) => {
    result.set(el.id, el)
    return result
  }, new Map())
}

export function safePush(arr, num) {
  const value = parseInt(num, 10)
  if (!isNaN(value)) {
    arr.push(value)
  }
}
<commit_msg>yay for comments<commit_after>import url from 'url'
import jwt from 'jsonwebtoken'
import fetch from 'isomorphic-fetch'
import getBullQueue from 'bull'
import socketCluster from 'socketcluster-client'

import config from 'src/config'
import {graphQLErrorHandler} from 'src/common/util/getGraphQLFetcher'

const JWT_ISSUER = 'learnersguild.org'

// TODO: fix this! we're effectively using module caching to create a singleton. yuck.
let socket = null

export function serverToServerJWT() {
  /* eslint-disable camelcase */
  const now = Math.floor(Date.now() / 1000)
  const claims = {
    iss: JWT_ISSUER,
    iat: now,
    exp: now + (60 * 10),  // 10 minutes from now
    sub: 0,
    name: 'Server-to-Server Authentication',
    preferred_username: '__server_to_server__',
    email: 'noreply@learnersguild.org',
    emails: 'noreply@learnersguild.org',
    roles: 'backoffice',
  }
  return jwt.sign(claims, config.server.jwt.privateKey, {algorithm: config.server.jwt.algorithm})
}

export function graphQLFetcher(baseURL, lgJWT = serverToServerJWT()) {
  return graphQLParams => {
    const options = {
      method: 'post',
      headers: {
        'Authorization': `Bearer ${lgJWT}`,
        'Origin': config.server.baseURL,
        'Content-Type': 'application/json',
        'LearnersGuild-Skip-Update-User-Middleware': 1,
      },
      body: JSON.stringify(graphQLParams),
    }

    return fetch(`${baseURL}/graphql`, options)
      .then(resp => {
        if (!resp.ok) {
          return Promise.reject(`GraphQL request resulted in an ERROR: ${resp.statusText}`)
        }
        return resp.json()
      })
      .then(graphQLErrorHandler)
  }
}

export function getQueue(queueName) {
  const redisConfig = url.parse(config.server.redis.url)
  /* eslint-disable camelcase */
  const redisOpts = redisConfig.auth ? {auth_pass: redisConfig.auth.split(':')[1]} : undefined
  return getBullQueue(queueName, redisConfig.port, redisConfig.hostname, redisOpts)
}

export function getSocket() {
  if (socket) {
    return socket
  }

  socket = socketCluster.connect({hostname: config.server.sockets.host})
  socket.on('connect', () => console.log('... socket connected'))
  socket.on('disconnect', () => console.log('socket disconnected, will try to reconnect socket ...'))
  socket.on('connectAbort', () => null)
  socket.on('error', error => console.warn(error.message))

  return socket
}

export function sum(values) {
  if (!Array.isArray(values)) {
    return null
  }
  return values.reduce((result, n) => result + n, 0)
}

export function avg(values) {
  const sumValues = sum(values)
  if (isNaN(sumValues)) {
    return sumValues
  }
  if (sumValues === 0) {
    return 0
  }
  return (sumValues / values.length)
}

export function toPercent(num) {
  return isNaN(num) ? NaN : (num * 100)
}

export function toArray(val) {
  if (Array.isArray(val)) {
    return val
  }
  if (val instanceof Map) {
    return Array.from(val.values())
  }
  return [val]
}

export function toPairs(arr) {
  if (!Array.isArray(arr)) {
    return null
  }
  if (arr.length < 2) {
    return []
  }
  const pairs = []
  for (let i = 0, len = arr.length - 1; i < len; i++) {
    for (let j = (i + 1); j < arr.length; j++) {
      pairs.push([arr[i], arr[j]])
    }
  }
  return pairs
}

export function roundDecimal(num) {
  // http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript#comment28521418_11832950
  return isNaN(num) ? null : (Math.round((num + 0.00001) * 100) / 100)
}

export function pickRandom(arr) {
  if (!Array.isArray(arr)) {
    return null
  }
  return arr[Math.floor(Math.random() * arr.length)]
}

export function shuffle(arr) {
  const shuffled = toArray(arr)

  let j
  let x
  for (let i = shuffled.length; i; i--) {
    j = Math.floor(Math.random() * i)
    x = shuffled[i - 1]
    shuffled[i - 1] = shuffled[j]
    shuffled[j] = x
  }

  return shuffled
}

export function mapById(arr) {
  return arr.reduce((result, el) => {
    result.set(el.id, el)
    return result
  }, new Map())
}

export function safePush(arr, num) {
  const value = parseInt(num, 10)
  if (!isNaN(value)) {
    arr.push(value)
  }
}
<|endoftext|>


<commit_before>/* eslint-disable react/no-danger*/
import React, { PropTypes } from 'react';
import serialize from 'serialize-javascript';

function Html({ content, state, scriptHash, vendorHash, cssHash, styles }) {
  return (

        <meta charSet="UTF-8" />
        <meta httpEquiv="Content-Language" content="en" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <meta name="web_section_id" content="R11935" />
        <title>Brand Central</title>
        <link href={`${cssHash}`} rel="stylesheet" />


<commit_before>var geocoder;
var map;

function decodeLevels(encodedLevelsString) {
   var decodedLevels = [];

   for (var i = 0; i < encodedLevelsString.length; ++i) {
        var level = encodedLevelsString.charCodeAt(i) - 63;
        decodedLevels.push(level);
   }
   return decodedLevels;
}

function initialize() {
   var map_canvas = document.getElementById('map_canvas');
   geocoder = new google.maps.Geocoder();

   // Create an array of styles.
   var styles = [
      {
         stylers : [
            {
               hue : "#0080ff"
            },
            {
               saturation : 10
            }
         ]
      },
      {
         featureType : "road",
         elementType : "geometry",
         stylers : [
            {
               lightness : 100
            },
            {
               visibility : "simplified"
            }
         ]
      },
      {
         featureType : "road",
         elementType : "labels",
         stylers : [
            {
               lightness : 50
            },
            {
               visibility : "simplified"
            }
         ]
      },
      {
         featureType : "poi.business",
         elementType : "labels",
         stylers : [
            {
               visibility : "off"
            }
         ]
      }
   ];

   var stravaMap = new google.maps.StyledMapType(styles, { name : 'Strava' });
   var types = [ 'map_fg', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID ];
   var map_options = {
      center : new google.maps.LatLng(39.7392, -104.9842),
      zoom : 8,
      mapTypeId : google.maps.MapTypeId.ROADMAP,
      mapTypeControlOptions : {
         style : google.maps.MapTypeControlStyle.DROPDOWN_MENU,
         mapTypeIds : types
      }
   };

   map = new google.maps.Map(map_canvas, map_options);
   map.mapTypes.set('map_fg', stravaMap);
   map.setMapTypeId('map_fg');
}

function loadActivities() {
   $.ajax({
      type:'GET',
      url:'/api/activities',
      success:function(json){
         console.log("Retrieved Strava activities:");
         $.each(json, function(key, activity){
            console.log("Loading activity: " + activity.name);
            var decodedPath = google.maps.geometry.encoding.decodePath(activity.map.summary_polyline);
            var decodedLevels = decodeLevels('BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB');

            var setRegion = new google.maps.Polyline({
                 path: decodedPath,
                 levels: decodedLevels,
                 strokeColor: "#ff8000",
                 strokeOpacity: 1.0,
                 strokeWeight: 1,
                 map: map
            });
            var infowindow = new google.maps.InfoWindow({
               content: 'Name: ' + activity.name + '
' +
                  'Date: ' + formatDate(activity.start_date) + '
' +
                  'Distance: ' + metersToMiles(activity.distance) + ' mi.
' +
                  'Time: ' + secondsToTime(activity.moving_time) + '
' +
                  'Elevation Gain: ' + metersToFeet(activity.total_elevation_gain) + ' ft.',
               maxWidth: 200
            });

            var marker = new google.maps.Marker({
               position: decodedPath[0],
               map: map,
               title: activity.name
            });

            google.maps.event.addListener(marker, 'click', function() {
               infowindow.open(map,marker);
            });
         });
         console.log("Finished loading Strava activities");
      }
   });

}

function metersToFeet(meters) {
   return Math.round((meters*3.2808) * 100) / 100
}

function metersToMiles(meters) {
   return Math.round((meters* 0.00062137) * 100) / 100
}

function formatDate(dateString) {
   var date = new Date(dateString);
   return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
}

function secondsToTime(seconds) {
   var hours = parseInt( seconds / 3600 ) % 24;
   if (hours < 10) { hours = '0' + hours; }
   var minutes = parseInt( seconds / 60 ) % 60;
   if (minutes < 10) { mintes = '0' + minutes; }
   var seconds = seconds % 60;
   if (seconds < 10) { seconds = '0' + seconds; }
   return hours + ':' + minutes + ':' + seconds;
}

$(document).ready(function(){
   initialize();
   loadActivities();
});
<commit_msg>handle manual entries<commit_after>var geocoder;
var map;

function decodeLevels(encodedLevelsString) {
   var decodedLevels = [];

   for (var i = 0; i < encodedLevelsString.length; ++i) {
        var level = encodedLevelsString.charCodeAt(i) - 63;
        decodedLevels.push(level);
   }
   return decodedLevels;
}

function initialize() {
   var map_canvas = document.getElementById('map_canvas');
   geocoder = new google.maps.Geocoder();

   // Create an array of styles.
   var styles = [
      {
         stylers : [
            {
               hue : "#0080ff"
            },
            {
               saturation : 10
            }
         ]
      },
      {
         featureType : "road",
         elementType : "geometry",
         stylers : [
            {
               lightness : 100
            },
            {
               visibility : "simplified"
            }
         ]
      },
      {
         featureType : "road",
         elementType : "labels",
         stylers : [
            {
               lightness : 50
            },
            {
               visibility : "simplified"
            }
         ]
      },
      {
         featureType : "poi.business",
         elementType : "labels",
         stylers : [
            {
               visibility : "off"
            }
         ]
      }
   ];

   var stravaMap = new google.maps.StyledMapType(styles, { name : 'Strava' });
   var types = [ 'map_fg', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID ];
   var map_options = {
      center : new google.maps.LatLng(39.7392, -104.9842),
      zoom : 8,
      mapTypeId : google.maps.MapTypeId.ROADMAP,
      mapTypeControlOptions : {
         style : google.maps.MapTypeControlStyle.DROPDOWN_MENU,
         mapTypeIds : types
      }
   };

   map = new google.maps.Map(map_canvas, map_options);
   map.mapTypes.set('map_fg', stravaMap);
   map.setMapTypeId('map_fg');
}

function loadActivities() {
   $.ajax({
      type:'GET',
      url:'/api/activities',
      success:function(json){
         console.log("Retrieved Strava activities:");
         $.each(json, function(key, activity){
            console.log("Loading activity: " + activity.name);
            if (!activity.map.summary_polyline) {
               activity.map.summary_polyline='';
            }
            var decodedPath = google.maps.geometry.encoding.decodePath(activity.map.summary_polyline);
            var decodedLevels = decodeLevels('BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB');

            var setRegion = new google.maps.Polyline({
                 path: decodedPath,
                 levels: decodedLevels,
                 strokeColor: "#ff8000",
                 strokeOpacity: 1.0,
                 strokeWeight: 1,
                 map: map
            });
            var infowindow = new google.maps.InfoWindow({
               content: 'Name: ' + activity.name + '
' +
                  'Date: ' + formatDate(activity.start_date) + '
' +
                  'Distance: ' + metersToMiles(activity.distance) + ' mi.
' +
                  'Time: ' + secondsToTime(activity.moving_time) + '
' +
                  'Elevation Gain: ' + metersToFeet(activity.total_elevation_gain) + ' ft.',
               maxWidth: 200
            });

            var marker = new google.maps.Marker({
               position: decodedPath[0],
               map: map,
               title: activity.name
            });

            google.maps.event.addListener(marker, 'click', function() {
               infowindow.open(map,marker);
            });
         });
         console.log("Finished loading Strava activities");
      }
   });

}

function metersToFeet(meters) {
   return Math.round((meters*3.2808) * 100) / 100
}

function metersToMiles(meters) {
   return Math.round((meters* 0.00062137) * 100) / 100
}

function formatDate(dateString) {
   var date = new Date(dateString);
   return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
}

function secondsToTime(seconds) {
   var hours = parseInt( seconds / 3600 ) % 24;
   if (hours < 10) { hours = '0' + hours; }
   var minutes = parseInt( seconds / 60 ) % 60;
   if (minutes < 10) { mintes = '0' + minutes; }
   var seconds = seconds % 60;
   if (seconds < 10) { seconds = '0' + seconds; }
   return hours + ':' + minutes + ':' + seconds;
}

$(document).ready(function(){
   initialize();
   loadActivities();
});
<|endoftext|>


<commit_before>var basicScraper = require('../controllers/basicScraperController');
var getExternalUrl = require('../controllers/urlController').getExternalUrl;
var compare = require('../imgCompare').compare;
var CronJob = require('cron').CronJob;
var CronJobManager = require('cron-job-manager');
var nodemailer = require('nodemailer');
var ocr = require('../controllers/ocrController.js');
var secret = require('../../config.js');
var Sequelize = require('sequelize');
var transporter = nodemailer.createTransport({
    service: 'mailgun',
    auth: secret.auth
});

module.exports = {

  getDate: function() {
    var date = new Date();
    var options = {
      year: 'numeric', month: '2-digit',
      day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit'
    };
    return date.toLocaleTimeString("en-us", options);
  },

  getNewCroppedImage: function(UserUrl, website, email, params, oldImg, cb) {
    basicScraper.getScreenshot(website, UserUrl.user_id, function(img1, email) {
      // crops new image so we can compare the the old cropped image
      basicScraper.cropImg(img1, params, true, function(newImg) {
        // checks for difference in pictures
        cb(oldImg, newImg)
      });
    }, email);
  },

  compareOCR: function(UserUrl, website, email, params, oldImg, cb) {
    module.exports.getNewCroppedImage(UserUrl, website, email, params, oldImg, function(oldImg, newImg) {
      console.log('inside ocrCompare, oldImg', oldImg, 'newImg', newImg);

        newImg = __dirname.substr(0, __dirname.length - 12) + 'client/' + newImg;
        oldImg = __dirname.substr(0, __dirname.length - 12) + 'client/' + oldImg;
        ocr.convertImageToText(newImg, function(err, text) {
          if (err) {
            console.log('ocr error' + err);
          } else {
            if (UserUrl.filter === 'greater') {
              // pulls first set of numbers from text
              if (text.match(/\d+\.?\d*/gi)) {
                var compareVal = text.match(/\d+\.?\d*/gi)[0];
              }
              if (compareVal > UserUrl.compareVal) {
                cb(oldImg, newImg);
              }
            } else if (UserUrl.filter == 'less') {
              if (text.match(/\d+\.?\d*/gi)) {
                var compareVal = text.match(/\d+\.?\d*/gi)[0];
              }
              if (compareVal < UserUrl.compareVal) {
                cb(oldImg, newImg);
              }
            } else if (UserUrl.filter == 'contains') {
              // if a user wants to check for multiple words
              var contains = UserUrl.compareVal.split(',') || UserUrl.compareVal;
              // iterate through each word
              for (var i = 0; i < contains.length; i++) {
                // if text contains any of the values
                if (text.toLowerCase().indexOf(contains[i].toLowerCase()) > -1) {
                  cb(oldImg, newImg);
                }
              }
            } else {
              console.log('comparing', UserUrl.cronVal, 'to', text);
              if (UserUrl.ocrText !== text) {
               cb(oldImg, newImg);
              }
            };
          };
        });
    });
  },

  compareScreenShot: function(UserUrl, website, email, params, oldImg, cb) {
    module.exports.getNewCroppedImage(UserUrl, website, email, params, oldImg, function(oldImg, newImg) {
      // checks for difference in pictures
      compare(oldImg, newImg, function (equal, oldImg, newImg){
        if (!equal){
          cb(oldImg, newImg);
        };
      });
    });
  },

  sendEmail: function(website, email, oldImg, newImg, sendOption, UserUrl) {
    console.log('change detected on', website, 'sending email to ', email);
    // parameters for email
    var mailOptions = {
        greater: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '! Looks like the value you are watching went over ' + UserUrl.compareVal, // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        },
        less: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '! Looks like the value you are watching went under ' + UserUrl.compareVal, // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        },
        contains: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '! Looks like the value you are watching contains ' + UserUrl.compareVal, // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        },
        Text: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '!', // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        },
        Image: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '!', // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        }
    };

    // send email function
    transporter.sendMail(mailOptions[sendOption], function(error, info){mailOptions[sendOption]
        if(error){
          console.log(error);
        } else {
          console.log('Message sent: ' + info.response);
        };
    });
  }
}

<commit_msg>[Style] Removed unneeded console.log<commit_after>var basicScraper = require('../controllers/basicScraperController');
var getExternalUrl = require('../controllers/urlController').getExternalUrl;
var compare = require('../imgCompare').compare;
var CronJob = require('cron').CronJob;
var CronJobManager = require('cron-job-manager');
var nodemailer = require('nodemailer');
var ocr = require('../controllers/ocrController.js');
var secret = require('../../config.js');
var Sequelize = require('sequelize');
var transporter = nodemailer.createTransport({
    service: 'mailgun',
    auth: secret.auth
});

module.exports = {

  getDate: function() {
    var date = new Date();
    var options = {
      year: 'numeric', month: '2-digit',
      day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit'
    };
    return date.toLocaleTimeString("en-us", options);
  },

  getNewCroppedImage: function(UserUrl, website, email, params, oldImg, cb) {
    basicScraper.getScreenshot(website, UserUrl.user_id, function(img1, email) {
      // crops new image so we can compare the the old cropped image
      basicScraper.cropImg(img1, params, true, function(newImg) {
        // checks for difference in pictures
        cb(oldImg, newImg)
      });
    }, email);
  },

  compareOCR: function(UserUrl, website, email, params, oldImg, cb) {
    module.exports.getNewCroppedImage(UserUrl, website, email, params, oldImg, function(oldImg, newImg) {
      console.log('inside ocrCompare, oldImg', oldImg, 'newImg', newImg);

        newImg = __dirname.substr(0, __dirname.length - 12) + 'client/' + newImg;
        oldImg = __dirname.substr(0, __dirname.length - 12) + 'client/' + oldImg;
        ocr.convertImageToText(newImg, function(err, text) {
          if (err) {
            console.log('ocr error' + err);
          } else {
            if (UserUrl.filter === 'greater') {
              // pulls first set of numbers from text
              if (text.match(/\d+\.?\d*/gi)) {
                var compareVal = text.match(/\d+\.?\d*/gi)[0];
              }
              if (compareVal > UserUrl.compareVal) {
                cb(oldImg, newImg);
              }
            } else if (UserUrl.filter == 'less') {
              if (text.match(/\d+\.?\d*/gi)) {
                var compareVal = text.match(/\d+\.?\d*/gi)[0];
              }
              if (compareVal < UserUrl.compareVal) {
                cb(oldImg, newImg);
              }
            } else if (UserUrl.filter == 'contains') {
              // if a user wants to check for multiple words
              var contains = UserUrl.compareVal.split(',') || UserUrl.compareVal;
              // iterate through each word
              for (var i = 0; i < contains.length; i++) {
                // if text contains any of the values
                if (text.toLowerCase().indexOf(contains[i].toLowerCase()) > -1) {
                  cb(oldImg, newImg);
                }
              }
            } else {
              if (UserUrl.ocrText !== text) {
               cb(oldImg, newImg);
              }
            };
          };
        });
    });
  },

  compareScreenShot: function(UserUrl, website, email, params, oldImg, cb) {
    module.exports.getNewCroppedImage(UserUrl, website, email, params, oldImg, function(oldImg, newImg) {
      // checks for difference in pictures
      compare(oldImg, newImg, function (equal, oldImg, newImg){
        if (!equal){
          cb(oldImg, newImg);
        };
      });
    });
  },

  sendEmail: function(website, email, oldImg, newImg, sendOption, UserUrl) {
    console.log('change detected on', website, 'sending email to ', email);
    // parameters for email
    var mailOptions = {
        greater: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '! Looks like the value you are watching went over ' + UserUrl.compareVal, // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        },
        less: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '! Looks like the value you are watching went under ' + UserUrl.compareVal, // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        },
        contains: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '! Looks like the value you are watching contains ' + UserUrl.compareVal, // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        },
        Text: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '!', // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        },
        Image: {
          from: "The Blank Arrays <postmaster@sandbox72a87403dd654630bfa3c4b021cda08d.mailgun.org>", // sender address
          to: email, // list of receivers
          subject: 'We found some tubular changes!', // Subject line
          text: 'Hi there! It looks like we found a change on '+ website + '!', // plaintext body
          html: "The Scrapinit team found a change on " + website +"!",
          attachments: [
          {
            path: oldImg
          },
          {
            path: newImg
          }
          ]
        }
    };

    // send email function
    transporter.sendMail(mailOptions[sendOption], function(error, info){mailOptions[sendOption]
        if(error){
          console.log(error);
        } else {
          console.log('Message sent: ' + info.response);
        };
    });
  }
}

<|endoftext|>


<commit_before>const mongoose = require('mongoose');
exports.mongoose = mongoose;
// --------------------------------------------------------------------------------------
var logs_schema = mongoose.Schema({
  timestamp : Date,
  realm : String,
  viscountry : String,
  visinst : String,
  csi : String,
  pn : String,
  result : String
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.logs_schema = logs_schema;
var logs = mongoose.model('logs', logs_schema, 'logs');
exports.logs = logs;
// --------------------------------------------------------------------------------------
var users_mac_schema = mongoose.Schema({
  username : String,
  addrs : Array
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.users_mac_schema = users_mac_schema;
var users_mac = mongoose.model('users_mac', users_mac_schema, 'users_mac');
exports.users_mac = users_mac;
// --------------------------------------------------------------------------------------
var realm_admin_logins_schema = mongoose.Schema({
  admin_login_ids : Array,
  admin_notify_address : String,
  administered_realms : Array
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.realm_admin_logins_schema = realm_admin_logins_schema;
var realm_admin_logins = mongoose.model('realm_admin_logins', realm_admin_logins_schema, 'realm_admin_logins');
exports.realm_admin_logins = realm_admin_logins;
// --------------------------------------------------------------------------------------
var mac_count_schema = mongoose.Schema({
  username  : String,
  count     : Number,
  addrs     : Array,
  timestamp : Date
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.mac_count_schema = mac_count_schema;
var mac_count = mongoose.model('mac_count', mac_count_schema, 'mac_count');
exports.mac_count = mac_count;
// --------------------------------------------------------------------------------------
var roaming_schema = mongoose.Schema({
  inst_name      : String,
  used_count     : Number,
  provided_count : Number,
  timestamp      : Date
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.roaming_schema = roaming_schema;
var roaming = mongoose.model('roaming', roaming_schema, 'roaming');
exports.roaming = roaming;
// --------------------------------------------------------------------------------------
var failed_logins_schema = mongoose.Schema({
  username    : String,
  timestamp   : Date,
  fail_count  : Number,
  ok_count    : Number,
  ratio       : Number
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.failed_logins_schema = failed_logins_schema;
var failed_logins = mongoose.model('failed_logins', failed_logins_schema, 'failed_logins');
exports.failed_logins = failed_logins;
// --------------------------------------------------------------------------------------
var realm_admins_schema = mongoose.Schema({
  realm          : String,
  admin          : String,
  notify_enabled : Boolean
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.realm_admins_schema = realm_admins_schema;
var realm_admins = mongoose.model('realm_admins', realm_admins_schema, 'realm_admins');
exports.realm_admins = realm_admins;
// --------------------------------------------------------------------------------------
var shared_mac_schema = mongoose.Schema({
  timestamp   : Date,
  mac_address : String,
  users       : Array,
  count       : Number
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.shared_mac_schema = shared_mac_schema;
var shared_mac = mongoose.model('shared_mac', shared_mac_schema, 'shared_mac');
exports.shared_mac = shared_mac;
// --------------------------------------------------------------------------------------
var heat_map_schema = mongoose.Schema({
  timestamp     : Date,
  realm         : String,
  institutions  : Array
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.heat_map_schema = heat_map_schema;
var heat_map = mongoose.model('heat_map', heat_map_schema, 'heat_map');
exports.heat_map = heat_map;
// --------------------------------------------------------------------------------------
var realms_schema = mongoose.Schema({
  realm     : String
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.realms_schema = realms_schema;
var realms = mongoose.model('realms', realms_schema, 'realms');
exports.realms = realms;
// --------------------------------------------------------------------------------------
var realm_logins_schema = mongoose.Schema({
  timestamp            : Date,
  realm                : String,
  ok_count             : Number,
  grouped_ok_count     : Number,
  fail_count           : Number,
  grouped_fail_count   : Number
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.realm_logins_schema = realm_logins_schema;
var realm_logins = mongoose.model('realm_logins', realm_logins_schema, 'realm_logins');
exports.realm_logins = realm_logins;
// --------------------------------------------------------------------------------------
var visinst_logins_schema = mongoose.Schema({
  timestamp            : Date,
  realm                : String,
  ok_count             : Number,
  grouped_ok_count     : Number,
  fail_count           : Number,
  grouped_fail_count   : Number
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.visinst_logins_schema = visinst_logins_schema;
var visinst_logins = mongoose.model('visinst_logins', visinst_logins_schema, 'visinst_logins');
exports.visinst_logins = visinst_logins;
// --------------------------------------------------------------------------------------
var unique_users_schema = mongoose.Schema({
  timestamp       : Date,
  realm           : String,
  realm_addrs     : Array,
  visinst_addrs   : Array
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.unique_users_schema = unique_users_schema;
var unique_users = mongoose.model('unique_users', unique_users_schema, 'unique_users');
exports.unique_users = unique_users;
// --------------------------------------------------------------------------------------
var concurrent_users_schema = mongoose.Schema({
  timestamp       : Date,
  timestamp_1     : Date,
  timestamp_2     : Date,
  visinst_1       : String,
  visinst_2       : String,
  username        : String,
  mac_address_1   : String,
  mac_address_2   : String,
  time_needed     : Number,
  dist            : Number,
  revision        : Number,
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.concurrent_users_schema = concurrent_users_schema;
var concurrent_users = mongoose.model('concurrent_users', concurrent_users_schema, 'concurrent_users');
exports.concurrent_users = concurrent_users;
// --------------------------------------------------------------------------------------
var concurrent_rev_schema = mongoose.Schema({
  revisions       : Array,
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.concurrent_rev_schema = concurrent_rev_schema;
var concurrent_rev = mongoose.model('concurrent_rev', concurrent_rev_schema, 'concurrent_rev');
exports.concurrent_rev = concurrent_rev;
// --------------------------------------------------------------------------------------
var privileged_ips_schema = mongoose.Schema({
  ip       : String,
  hostname : String,
  comment  : String,
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.privileged_ips_schema = privileged_ips_schema;
var privileged_ips = mongoose.model('privileged_ips', privileged_ips_schema, 'privileged_ips');
exports.privileged_ips = privileged_ips;
// --------------------------------------------------------------------------------------
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
/*
mongoose.connection.once('open', function (callback) {
  console.log("sucesfully connected do mongodb database on localhost");
});
*/
// --------------------------------------------------------------------------------------
// connect to the databse
// --------------------------------------------------------------------------------------
exports.connect = function()
{
  mongoose.connect('mongodb://localhost/etlog', {
    server : {
      socketOptions : {
        socketTimeoutMS: 0,
        connectTimeoutMS: 5000,
        keepAlive: 300000
      }
    }
  });
}
// --------------------------------------------------------------------------------------
// disconnect from the databse
// --------------------------------------------------------------------------------------
exports.disconnect = function()
{
  mongoose.connection.close();
}
// --------------------------------------------------------------------------------------
<commit_msg>tune database connection params<commit_after>const mongoose = require('mongoose');
exports.mongoose = mongoose;
// --------------------------------------------------------------------------------------
var logs_schema = mongoose.Schema({
  timestamp : Date,
  realm : String,
  viscountry : String,
  visinst : String,
  csi : String,
  pn : String,
  result : String
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.logs_schema = logs_schema;
var logs = mongoose.model('logs', logs_schema, 'logs');
exports.logs = logs;
// --------------------------------------------------------------------------------------
var users_mac_schema = mongoose.Schema({
  username : String,
  addrs : Array
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.users_mac_schema = users_mac_schema;
var users_mac = mongoose.model('users_mac', users_mac_schema, 'users_mac');
exports.users_mac = users_mac;
// --------------------------------------------------------------------------------------
var realm_admin_logins_schema = mongoose.Schema({
  admin_login_ids : Array,
  admin_notify_address : String,
  administered_realms : Array
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.realm_admin_logins_schema = realm_admin_logins_schema;
var realm_admin_logins = mongoose.model('realm_admin_logins', realm_admin_logins_schema, 'realm_admin_logins');
exports.realm_admin_logins = realm_admin_logins;
// --------------------------------------------------------------------------------------
var mac_count_schema = mongoose.Schema({
  username  : String,
  count     : Number,
  addrs     : Array,
  timestamp : Date
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.mac_count_schema = mac_count_schema;
var mac_count = mongoose.model('mac_count', mac_count_schema, 'mac_count');
exports.mac_count = mac_count;
// --------------------------------------------------------------------------------------
var roaming_schema = mongoose.Schema({
  inst_name      : String,
  used_count     : Number,
  provided_count : Number,
  timestamp      : Date
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.roaming_schema = roaming_schema;
var roaming = mongoose.model('roaming', roaming_schema, 'roaming');
exports.roaming = roaming;
// --------------------------------------------------------------------------------------
var failed_logins_schema = mongoose.Schema({
  username    : String,
  timestamp   : Date,
  fail_count  : Number,
  ok_count    : Number,
  ratio       : Number
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.failed_logins_schema = failed_logins_schema;
var failed_logins = mongoose.model('failed_logins', failed_logins_schema, 'failed_logins');
exports.failed_logins = failed_logins;
// --------------------------------------------------------------------------------------
var realm_admins_schema = mongoose.Schema({
  realm          : String,
  admin          : String,
  notify_enabled : Boolean
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.realm_admins_schema = realm_admins_schema;
var realm_admins = mongoose.model('realm_admins', realm_admins_schema, 'realm_admins');
exports.realm_admins = realm_admins;
// --------------------------------------------------------------------------------------
var shared_mac_schema = mongoose.Schema({
  timestamp   : Date,
  mac_address : String,
  users       : Array,
  count       : Number
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.shared_mac_schema = shared_mac_schema;
var shared_mac = mongoose.model('shared_mac', shared_mac_schema, 'shared_mac');
exports.shared_mac = shared_mac;
// --------------------------------------------------------------------------------------
var heat_map_schema = mongoose.Schema({
  timestamp     : Date,
  realm         : String,
  institutions  : Array
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.heat_map_schema = heat_map_schema;
var heat_map = mongoose.model('heat_map', heat_map_schema, 'heat_map');
exports.heat_map = heat_map;
// --------------------------------------------------------------------------------------
var realms_schema = mongoose.Schema({
  realm     : String
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.realms_schema = realms_schema;
var realms = mongoose.model('realms', realms_schema, 'realms');
exports.realms = realms;
// --------------------------------------------------------------------------------------
var realm_logins_schema = mongoose.Schema({
  timestamp            : Date,
  realm                : String,
  ok_count             : Number,
  grouped_ok_count     : Number,
  fail_count           : Number,
  grouped_fail_count   : Number
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.realm_logins_schema = realm_logins_schema;
var realm_logins = mongoose.model('realm_logins', realm_logins_schema, 'realm_logins');
exports.realm_logins = realm_logins;
// --------------------------------------------------------------------------------------
var visinst_logins_schema = mongoose.Schema({
  timestamp            : Date,
  realm                : String,
  ok_count             : Number,
  grouped_ok_count     : Number,
  fail_count           : Number,
  grouped_fail_count   : Number
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.visinst_logins_schema = visinst_logins_schema;
var visinst_logins = mongoose.model('visinst_logins', visinst_logins_schema, 'visinst_logins');
exports.visinst_logins = visinst_logins;
// --------------------------------------------------------------------------------------
var unique_users_schema = mongoose.Schema({
  timestamp       : Date,
  realm           : String,
  realm_addrs     : Array,
  visinst_addrs   : Array
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.unique_users_schema = unique_users_schema;
var unique_users = mongoose.model('unique_users', unique_users_schema, 'unique_users');
exports.unique_users = unique_users;
// --------------------------------------------------------------------------------------
var concurrent_users_schema = mongoose.Schema({
  timestamp       : Date,
  timestamp_1     : Date,
  timestamp_2     : Date,
  visinst_1       : String,
  visinst_2       : String,
  username        : String,
  mac_address_1   : String,
  mac_address_2   : String,
  time_needed     : Number,
  dist            : Number,
  revision        : Number,
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.concurrent_users_schema = concurrent_users_schema;
var concurrent_users = mongoose.model('concurrent_users', concurrent_users_schema, 'concurrent_users');
exports.concurrent_users = concurrent_users;
// --------------------------------------------------------------------------------------
var concurrent_rev_schema = mongoose.Schema({
  revisions       : Array,
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.concurrent_rev_schema = concurrent_rev_schema;
var concurrent_rev = mongoose.model('concurrent_rev', concurrent_rev_schema, 'concurrent_rev');
exports.concurrent_rev = concurrent_rev;
// --------------------------------------------------------------------------------------
var privileged_ips_schema = mongoose.Schema({
  ip       : String,
  hostname : String,
  comment  : String,
},
{ versionKey: false });
// --------------------------------------------------------------------------------------
exports.privileged_ips_schema = privileged_ips_schema;
var privileged_ips = mongoose.model('privileged_ips', privileged_ips_schema, 'privileged_ips');
exports.privileged_ips = privileged_ips;
// --------------------------------------------------------------------------------------
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
/*
mongoose.connection.once('open', function (callback) {
  console.log("sucesfully connected do mongodb database on localhost");
});
*/
// --------------------------------------------------------------------------------------
// connect to the databse
// --------------------------------------------------------------------------------------
exports.connect = function()
{
  mongoose.connect('mongodb://localhost/etlog', {
    db: { native_parser: true },
    server : {
      poolSize: 20,
      socketOptions : {
        socketTimeoutMS: 0,
        connectTimeoutMS: 5000,
        keepAlive: 300000
      }
    }
  });
}
// --------------------------------------------------------------------------------------
// disconnect from the databse
// --------------------------------------------------------------------------------------
exports.disconnect = function()
{
  mongoose.connection.close();
}
// --------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>// This module provides a global object
// with operations for finding Yelp data.
var YELP = (function(window, $, coordinates) {
  'use strict';

  var contextArray = window.location.hostname.split('.');
  var context = (contextArray.length == 1 ? contextArray[0] : contextArray[1]);

  var yelp = {
    fetch: function (callback) {
      // Todo: Fix this here...
      $.ajax({
        url: context + '/api/v1/yelp',
        type: 'GET',
        data: coordinates,
        success: function(data) {
          console.log('Recieved from yelp: ' + JSON.stringify(data));
          callback(data);
        },
        error: function(error) {
          console.log('Error fetching yelp data.');
          callback(error);
        }
      });
    }
  };

  return yelp;
}(window, $, COORDINATES));
<commit_msg>Closes #2<commit_after>// This module provides a global object
// with operations for finding Yelp data.
var YELP = (function(window, $, coordinates, apiVersion) {
  'use strict';

  var yelp = {
    fetch: function (callback) {
      // Todo: Fix this here...
      $.ajax({
        url: '/api/'+ apiVersion +'/yelp',
        type: 'GET',
        data: coordinates,
        success: function(data) {
          console.log('Recieved from yelp: ' + JSON.stringify(data));
          callback(data);
        },
        error: function(error) {
          console.log('Error fetching yelp data.');
          callback(error);
        }
      });
    }
  };

  return yelp;
}(window, $, COORDINATES, 'v1'));
<|endoftext|>


<commit_before>let Collection = require('nedb');
let makeService = require('feathers-nedb');

let services = exports.services = {};

exports.getService = name => {
  if (services[name]) {
    return services[name];
  }

  let collection = new Collection({
    filename: `${__dirname}/collections/${name}.json`,
    autoload: true,
  });

  return services[name] = makeService({
    Model: collection,
  });
};

for (let k of [
  'get',
  'find',
  'create',
  'update',
  'patch',
  'remove',
]) {
  exports[k] = (name, ...args) =>
    exports.getService(name)[k](...args);
}
<commit_msg>Implement service request / response filters [#2]<commit_after>let Collection = require('nedb');
let makeService = require('feathers-nedb');

let services = exports.services = {};

exports.getService = name => {
  if (services[name]) {
    return services[name];
  }

  let collection = new Collection({
    filename: `${__dirname}/collections/${name}.json`,
    autoload: true,
  });

  return services[name] = makeService({
    Model: collection,
  });
};

for (let k of [
  'get',
  'find',
  'create',
  'update',
  'patch',
  'remove',
]) {
  exports[k] = async (name, ...args) => {
    let service = exports.getService(name);

    if (service.requestFilter) {
      args = (await service.requestFilter(...args)) || args;
    }

    let data = await exports.getService(name)[k](...args);

    if (!Array.isArray(data)) {
      data = [data];
    }

    if (service.responseFilter) {
      data = await service.responseFilter(data, ...args);
    }

    return data;
  };
}
<|endoftext|>


<commit_before>/*jslint forin: true*/
/*global FormData, jQuery, MM, setTimeout */
MM.S3MapRepository = function (s3Url, folder, activityLog) {
	'use strict';
	this.description = 'S3_CORS';

	this.recognises = function (mapId) {
		return mapId && mapId[0] === 'a';
	};

	this.loadMap = function (mapId) {
		var deferred = jQuery.Deferred(),
			onMapLoaded = function (result) {
				deferred.resolve(result, mapId, 'application/json');
			},
			mapUrl = s3Url + folder + mapId + '.json',
			loadMapUsingProxy = function () {
				activityLog.log('Map', 'ProxyLoad', mapId);
				jQuery.ajax(
					'/s3proxy/' + mapId,
					{ dataType: 'json', success: onMapLoaded, error: deferred.reject }
				);
			};
		jQuery.ajax(
			mapUrl,
			{ dataType: 'json', success: onMapLoaded, error: loadMapUsingProxy }
		);
		return deferred.promise();
	};

	this.saveMap = function (mapInfo) {
		var deferred = jQuery.Deferred(),
			publishing = true,
			submitS3Form = function (publishingConfig) {
				var formData = new FormData();
				publishing = false;
				['key', 'AWSAccessKeyId', 'policy', 'signature'].forEach(function (parameter) {
					formData.append(parameter, publishingConfig[parameter]);
				});
				formData.append('acl', 'public-read');
				formData.append('Content-Type', 'text/plain');
				formData.append('file', JSON.stringify(mapInfo.idea));
				jQuery.ajax({
					url: s3Url,
					type: 'POST',
					processData: false,
					contentType: false,
					data: formData
				}).done(function () {
					mapInfo.mapId = publishingConfig.s3UploadIdentifier;
					deferred.resolve(mapInfo);
				}).fail(function (evt) {
					publishing = false;
					deferred.reject({
						type: 's3-save-error',
						responseText: evt.responseText
					});
				});
			},
			fetchPublishingConfig = function () {
				activityLog.log('Fetching publishing config');
				jQuery.ajax(
					'/publishingConfig?no_redirect=true',
					{
						dataType: 'json',
						cache: false,
						success: submitS3Form,
						error: function () {
							if (publishing) {
								setTimeout(fetchPublishingConfig, 1000);
							}
						}
					}
				);
			};
		fetchPublishingConfig();
		return deferred.promise();
	};
};
<commit_msg>dont need to retry publishing config, it is done by MM.maprepository now<commit_after>/*jslint forin: true*/
/*global FormData, jQuery, MM, setTimeout */
MM.S3MapRepository = function (s3Url, folder, activityLog) {
	'use strict';
	this.description = 'S3_CORS';

	this.recognises = function (mapId) {
		return mapId && mapId[0] === 'a';
	};

	this.loadMap = function (mapId) {
		var deferred = jQuery.Deferred(),
			onMapLoaded = function (result) {
				deferred.resolve(result, mapId, 'application/json');
			},
			mapUrl = s3Url + folder + mapId + '.json',
			loadMapUsingProxy = function () {
				activityLog.log('Map', 'ProxyLoad', mapId);
				jQuery.ajax(
					'/s3proxy/' + mapId,
					{ dataType: 'json', success: onMapLoaded, error: deferred.reject }
				);
			};
		jQuery.ajax(
			mapUrl,
			{ dataType: 'json', success: onMapLoaded, error: loadMapUsingProxy }
		);
		return deferred.promise();
	};

	this.saveMap = function (mapInfo) {
		var deferred = jQuery.Deferred(),
			submitS3Form = function (publishingConfig) {
				var formData = new FormData();
				['key', 'AWSAccessKeyId', 'policy', 'signature'].forEach(function (parameter) {
					formData.append(parameter, publishingConfig[parameter]);
				});
				formData.append('acl', 'public-read');
				formData.append('Content-Type', 'text/plain');
				formData.append('file', JSON.stringify(mapInfo.idea));
				jQuery.ajax({
					url: s3Url,
					type: 'POST',
					processData: false,
					contentType: false,
					data: formData
				}).done(function () {
					mapInfo.mapId = publishingConfig.s3UploadIdentifier;
					deferred.resolve(mapInfo);
				}).fail(function (evt) {
					deferred.reject({
						type: 's3-save-error',
						responseText: evt.responseText
					});
				});
			};
		activityLog.log('Fetching publishing config');
		jQuery.ajax(
			'/publishingConfig?no_redirect=true',
			{
				dataType: 'json',
				cache: false
			}
		).then(
			submitS3Form,
			deferred.reject.bind(deferred, 'network-error')
		);
		return deferred.promise();
	};
};
<|endoftext|>


<commit_before>require.paths.unshift(__dirname + "/vendor/rest-mongo/src")

var rest_mongo = require("rest-mongo")

var schema = {
  Geek: {
    schema: {
      id: "Geek",
      description: "A geek / person / dev ...",
      type: "object",

      properties: {
        name: {type: "string"},
        pole: {type: "string"},
        width: {type: "float"},
        height: {type: "float"},
        top: {type: "float"},
        left: {type: "float"}
      }
    }
  },

  URL: {
    schema: {
      id: "URL",
      description: "URL, potentially interesting for geeks",
      type: "object",

      properties: {
        url: {type: "string"}, // the URL value
        from: {type: "string"}, // who posted the url (nick, name...)
        channel: {type: "string"} // where it has been posted (irc chan...)
      }
    }
  }

}

exports.RFactory = rest_mongo.getRFactory(schema, {db_name: "Geeks_dev"})

<commit_msg>Add id to Geek schema (we need it on client side!).<commit_after>require.paths.unshift(__dirname + "/vendor/rest-mongo/src")

var rest_mongo = require("rest-mongo")

var schema = {
  Geek: {
    schema: {
      id: "Geek",
      description: "A geek / person / dev ...",
      type: "object",

      properties: {
        id: {type: "string"},
        name: {type: "string"},
        pole: {type: "string"},
        width: {type: "float"},
        height: {type: "float"},
        top: {type: "float"},
        left: {type: "float"}
      }
    }
  },

  URL: {
    schema: {
      id: "URL",
      description: "URL, potentially interesting for geeks",
      type: "object",

      properties: {
        url: {type: "string"}, // the URL value
        from: {type: "string"}, // who posted the url (nick, name...)
        channel: {type: "string"} // where it has been posted (irc chan...)
      }
    }
  }

}

exports.RFactory = rest_mongo.getRFactory(schema, {db_name: "Geeks_dev"})

<|endoftext|>