<commit_before>var Game = Game || {};

Game.Player = function(options) {
  'use strict';
  Game.Sprite.call(this, options);
  console.log(options.x);
  this.colour = options.colour || '#AADDCC';
  this.xSpeed = options.xSpeed || 10;
  this.ySpeed = options.ySpeed || 10;
  this.health = 100;
};
Game.Player.prototype = Object.create(Game.Sprite.prototype);
Game.Player.constructor = Game.Sprite;

Game.Player.prototype.getBBox = function() {
  'use strict';
  return {
    x: this.x - this.width,
    y: this.y - this.height,
    width: this.width * 2,
    height: this.height
  };
};

Game.Player.prototype.move = function(x, y, width, height) {
  'use strict';
  this.x += x;
  this.y += y;

  // Prevent character from moving out of bounds
  if (this.x <= this.width) {
    this.x = this.width;
  } else if (this.x + this.width >= width) {
    this.x = width - this.width;
  }

  if (this.y <= height * 0.75) {
    this.y = (height * 0.75);
  } else if (this.y + this.height >= height) {
    this.y = height - this.height;
  }
};

Game.Player.prototype.update = function(inputHandler) {
  'use strict';
  var laserOptions;
  if (this.health === 0) {
    this.dead = true;
  }

  if(inputHandler.keysDown[inputHandler.KEY.UP]) {
    this.move(0, -this.ySpeed, this.canvasWidth, this.canvasHeight);
  } else if (inputHandler.keysDown[inputHandler.KEY.DOWN]) {
    this.move(0, this.ySpeed, this.canvasWidth, this.canvasHeight);
  } else if (inputHandler.keysDown[inputHandler.KEY.LEFT]) {
    this.move(-this.xSpeed, 0, this.canvasWidth, this.canvasHeight);
  } else if (inputHandler.keysDown[inputHandler.KEY.RIGHT]) {
    this.move(this.xSpeed, 0, this.canvasWidth, this.canvasHeight);
  }

  if (inputHandler.keysDown[inputHandler.KEY.SPACE] && this.shotWait === 0) {
    laserOptions = {
      width: 7,
      height: 7,
      x: this.x,
      y: this.y,
      speed: 15,
      colour: '#EEDD88',
      damage: this.damage,
      direction: 'up'
    };
    this.laserShots.push(new Game.LaserShot(laserOptions));
  }

  // Wait 5 frames between every laser shot
  if (this.shotWait === 0) {
    this.shotWait = 10;
  } else {
    this.shotWait -= 1;
  }

  // If the user is not holding the spacebar then automatically reset the
  // shot delay, so that spacebar presses won't be skipped
  if (!inputHandler.keysDown[inputHandler.KEY.SPACE]) {
    this.shotWait = 0;
  }

  // Update laser shot positions
  this.laserShots = this.laserShots.filter(function(ls) {
    ls.update();
    return (ls.y + ls.height > 0) && !ls.hit;
  });
};

Game.Player.prototype.render = function(context) {
  'use strict';
  context.beginPath();
  if (this.hit) {
    context.fillStyle = '#FFFFFF';
  } else {
    context.strokeStyle = this.colour;
  }
  //Draw triangle for player
  context.moveTo(this.x, this.y);
  context.lineTo(this.x - this.width, this.y + this.height);
  context.lineTo(this.x + this.width, this.y + this.height);
  context.lineTo(this.x, this.y);
  if (this.hit) {
    context.fill();
  } else {
    context.stroke();
  }
  context.closePath();

  this.laserShots.forEach(function(ls) {
    ls.render(context);
  });
};
<commit_msg>Allow player movement with WASD keys<commit_after>var Game = Game || {};

Game.Player = function(options) {
  'use strict';
  Game.Sprite.call(this, options);
  console.log(options.x);
  this.colour = options.colour || '#AADDCC';
  this.xSpeed = options.xSpeed || 10;
  this.ySpeed = options.ySpeed || 10;
  this.health = 100;
};
Game.Player.prototype = Object.create(Game.Sprite.prototype);
Game.Player.constructor = Game.Sprite;

Game.Player.prototype.getBBox = function() {
  'use strict';
  return {
    x: this.x - this.width,
    y: this.y - this.height,
    width: this.width * 2,
    height: this.height
  };
};

Game.Player.prototype.move = function(x, y, width, height) {
  'use strict';
  this.x += x;
  this.y += y;

  // Prevent character from moving out of bounds
  if (this.x <= this.width) {
    this.x = this.width;
  } else if (this.x + this.width >= width) {
    this.x = width - this.width;
  }

  if (this.y <= height * 0.75) {
    this.y = (height * 0.75);
  } else if (this.y + this.height >= height) {
    this.y = height - this.height;
  }
};

Game.Player.prototype.update = function(inputHandler) {
  'use strict';
  var laserOptions;
  if (this.health === 0) {
    this.dead = true;
  }

  if(inputHandler.isDown('UP') || inputHandler.isDown('W')) {
    this.move(0, -this.ySpeed, this.canvasWidth, this.canvasHeight);
  } else if (inputHandler.isDown('DOWN') || inputHandler.isDown('S')) {
    this.move(0, this.ySpeed, this.canvasWidth, this.canvasHeight);
  } else if (inputHandler.isDown('LEFT') || inputHandler.isDown('A')) {
    this.move(-this.xSpeed, 0, this.canvasWidth, this.canvasHeight);
  } else if (inputHandler.isDown('RIGHT') || inputHandler.isDown('D')) {
    this.move(this.xSpeed, 0, this.canvasWidth, this.canvasHeight);
  }

  if (inputHandler.keysDown[inputHandler.KEY.SPACE] && this.shotWait === 0) {
    laserOptions = {
      width: 7,
      height: 7,
      x: this.x,
      y: this.y,
      speed: 15,
      colour: '#EEDD88',
      damage: this.damage,
      direction: 'up'
    };
    this.laserShots.push(new Game.LaserShot(laserOptions));
  }

  // Wait 5 frames between every laser shot
  if (this.shotWait === 0) {
    this.shotWait = 10;
  } else {
    this.shotWait -= 1;
  }

  // If the user is not holding the spacebar then automatically reset the
  // shot delay, so that spacebar presses won't be skipped
  if (!inputHandler.keysDown[inputHandler.KEY.SPACE]) {
    this.shotWait = 0;
  }

  // Update laser shot positions
  this.laserShots = this.laserShots.filter(function(ls) {
    ls.update();
    return (ls.y + ls.height > 0) && !ls.hit;
  });
};

Game.Player.prototype.render = function(context) {
  'use strict';
  context.beginPath();
  if (this.hit) {
    context.fillStyle = '#FFFFFF';
  } else {
    context.strokeStyle = this.colour;
  }
  //Draw triangle for player
  context.moveTo(this.x, this.y);
  context.lineTo(this.x - this.width, this.y + this.height);
  context.lineTo(this.x + this.width, this.y + this.height);
  context.lineTo(this.x, this.y);
  if (this.hit) {
    context.fill();
  } else {
    context.stroke();
  }
  context.closePath();

  this.laserShots.forEach(function(ls) {
    ls.render(context);
  });
};
<|endoftext|>


<commit_before>(function() {

  var unicodeData = null;
  var proto = location.protocol;

  function startup() {
    displayMsg("Fetching UnicodeData.txt...")
    var xhr = new XMLHttpRequest();
    xhr.onload = getData;
    xhr.open("GET", "../res/short.txt", true);
    xhr.send();
  }

  function getData() {
    if (this.status != "200") {
      complainMsg("Error fetching the file!")
    }
    else {
      displayMsg("Fetched file successfully. Parsing...");
      parseData(this.responseText);
    }
  }

  function parseData(data) {
    var lines, splits;
    lines = data.match(/[^\r\n]+/g);
    unicodeData = {};
    for (var i = 0; i < lines.length; i++) {
      //console.log(lines[i]);
      splits = lines[i].split(";");
      console.log(splits);
      unicodeData[splits[0]] = splits.slice(1);
    }
    displayMsg("Ready");
    window.ud = unicodeData;
    buttonEnabled(true);
  }

  function processText() {
    var text;
    if (!(text = document.getElementById("txt").value)) {
      alert("Enter some text, stupid");
      return;
    }
    alert("insert text processing here");
  }

  function buttonEnabled(yn) {
    var btn = document.getElementById("btn");
    if (yn) {
      btn.removeAttribute("disabled");
    }
    else {
      btn.setAttribute("disabled", "");
    }
  }

  function displayMsg(msg) {
    document.getElementById("msg-line").className = "msg";
    writeMsg(msg);
  }

  function complainMsg(msg) {
    document.getElementById("msg-line").className = "msg bad";
    writeMsg(msg);
  }

  function writeMsg(msg) {
    document.getElementById("msg-line").innerHTML = msg;
  }

  window.submitText = function() {
    processText();
  }

  addEventListener("DOMContentLoaded", startup);

}).call();
<commit_msg>Update charident.js<commit_after>(function() {

  var unicodeData = null;
  var proto = location.protocol;

  function startup() {
    displayMsg("Fetching UnicodeData.txt...")
    var xhr = new XMLHttpRequest();
    xhr.onload = getData;
    xhr.open("GET", "../res/short.txt", true);
    xhr.send();
  }

  function getData() {
    if (this.status != "200") {
      complainMsg("Error fetching the file!")
    }
    else {
      displayMsg("Fetched file successfully. Parsing...");
      parseData(this.responseText);
    }
  }

  function parseData(data) {
    var lines, splits;
    lines = data.match(/[^\r\n]+/g);
    unicodeData = {};
    console.log(lines);
    for (var i = 0; i < lines.length; i++) {
      console.log(lines[i]);
      splits = lines[i].split(";");
      console.log(splits);
      unicodeData[splits[0]] = splits.slice(1);
    }
    displayMsg("Ready");
    window.ud = unicodeData;
    buttonEnabled(true);
  }

  function processText() {
    var text;
    if (!(text = document.getElementById("txt").value)) {
      alert("Enter some text, stupid");
      return;
    }
    alert("insert text processing here");
  }

  function buttonEnabled(yn) {
    var btn = document.getElementById("btn");
    if (yn) {
      btn.removeAttribute("disabled");
    }
    else {
      btn.setAttribute("disabled", "");
    }
  }

  function displayMsg(msg) {
    document.getElementById("msg-line").className = "msg";
    writeMsg(msg);
  }

  function complainMsg(msg) {
    document.getElementById("msg-line").className = "msg bad";
    writeMsg(msg);
  }

  function writeMsg(msg) {
    document.getElementById("msg-line").innerHTML = msg;
  }

  window.submitText = function() {
    processText();
  }

  addEventListener("DOMContentLoaded", startup);

}).call();
<|endoftext|>


<commit_before>(function(w){

        var events = [
            {
                titulo : "BrazilJS Conf 2015",
                data : "21 e 22 de agosto",
                local : "Shopping Center BarraShoppingSul",
                endereco : "Av. Diário de Notícias, 300, bairro Cristal, Porto Alegre, RS",
                embed_link : "https://www.google.com/maps/embed?pb=!1m12!1m8!1m3!1d14715.652343097261!2d-42.9173542!3d-22.76860655!3m2!1i1024!2i768!4f13.1!2m1!1sAv.+Di%C3%A1rio+de+Not%C3%ADcias%2C+300%2C+bairro+Cristal%2C+Porto+Alegre%2C+RS!5e0!3m2!1spt-BR!2sbr!4v1436140686717",
                localizacao : {
                    latitude: -22.76860655,
                    longitude: -42.9173542
                },
                link : "http://braziljs.com.br/"
            },
            {
                titulo : "Android DevConference 2015",
                data : "29 de agosto",
                local : "Hotel Renaissance",
                endereco : "Av. Alameda Santos, 2233, São Paulo - SP",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3657.2665262031114!2d-46.662335999999996!3d-23.5588693!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94ce59d2c9a0e4c3%3A0x32c2ff75b7acd122!2sAlameda+Santos%2C+2233+-+Jardim+Paulista%2C+S%C3%A3o+Paulo+-+SP%2C+01419-002!5e0!3m2!1spt-BR!2sbr!4v1437063872582",
                localizacao : {
                    latitude: -23.5588693,
                    longitude: -46.6623359
                },
                link : "http://androidconference.imasters.com.br/"
            },
            {
                titulo : "WordCamp Rio de Janeiro 2015",
                data : "29 de agosto",
                local : "Senac Flamengo",
                endereco : "Rua Marquês de Abrantes, 99 – Flamengo – Rio de Janeiro, RJ",
                embed_link : "https://www.google.com/maps/embed?pb=!1m19!1m8!1m3!1d3674.371875920687!2d-43.1773033!3d-22.9365277!3m2!1i1024!2i768!4f13.1!4m8!3e6!4m0!4m5!1s0x997f88f435624f%3A0x83ed42214af802dd!2sR.+Marqu%C3%AAs+de+Abrantes%2C+99+-+Flamengo%2C+Rio+de+Janeiro+-+RJ%2C+22230-061!3m2!1d-22.9365277!2d-43.1773033!5e0!3m2!1spt-BR!2sbr!4v1437756544681",
                localizacao : {
                    latitude: -22.9365277,
                    longitude: -43.1773033
                },
                link : "https://riodejaneiro.wordcamp.org/2015/"
            },
            {
                titulo : "JoomlaDay Brasil 2015",
                data : "4 a 6 de Setembro",
                local : "Universidade Católica de Brasília",
                endereco : "QS 07, Lote 01, EPCT, s/n - Águas Claras, Brasília - DF",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3837.7826667761815!2d-48.02944694442749!3d-15.86801596095458!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x935a2d99eddf2aeb%3A0x1f93c6652deda3dc!2sUCB+-+Universidade+Cat%C3%B3lica+de+Bras%C3%ADlia!5e0!3m2!1spt-BR!2sbr!4v1439132769648",
                localizacao : {
                    latitude: -15.8680159,
                    longitude: -48.0294469
                },
                link : "http://joomladaybrasil.org/2015/"
            },
            {
                titulo : "RubyConf Brasil",
                data : "18 e 19 de Setembro",
                local : "FECOMERCIO SP",
                endereco : "Rua Doutor Plínio Barreto, 285 - Bela Vista - São Paulo",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d7314.430140061132!2d-46.653856000000005!3d-23.560717999999998!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0000000000000000%3A0x21c71fd197983309!2sFedera%C3%A7%C3%A3o+do+Com%C3%A9rcio+do+Estado+de+S%C3%A3o+Paulo!5e0!3m2!1spt-BR!2sus!4v1438352225051",
                localizacao : {
                    latitude: -23.55797,
                    longitude: -46.652316
                },
                link : "http://www.rubyconf.com.br/pt-BR/home"
            },
            {
                titulo : "Conferência Web.br 2015",
                data : "22 e 23 de setembro",
                local : "Centro de Convenções Rebolsas",
                endereco : "Rua Doutor Enéas de Carvalho Aguiar, 23 - Cerqueira Cesar",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3657.304241239964!2d-46.66812059999998!3d-23.5575142!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94ce582b0020752d%3A0x3c6835cc0084f24c!2sAv.+Dr.+En%C3%A9as+de+Carvalho+Aguiar%2C+23+-+Cerqueira+C%C3%A9sar%2C+S%C3%A3o+Paulo+-+SP!5e0!3m2!1sen!2sbr!4v1438211682234",
                localizacao : {
                    latitude: -23.557352,
                    longitude: -46.668105
                },
                link : "http://conferenciaweb.w3c.br/"
            },
            {
                titulo : "Front-End Carioca 2015",
                data : "26 de setembro",
                local : "Clube de Engenharia",
                endereco : "Av. Rio Branco, 124 - Centro, Rio de Janeiro - RJ",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3675.229129110692!2d-43.1780723!3d-22.904918100000003!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x997f5e44176677%3A0x13531119e47c4cc9!2sAv.+Rio+Branco%2C+124+-+Centro%2C+Rio+de+Janeiro+-+RJ%2C+20040-001!5e0!3m2!1spt-BR!2sbr!4v1435802972051",
                localizacao : {
                    latitude: -22.9049181,
                    longitude: -43.1780723
                },
                link : "http://frontendcarioca.com.br/"
            },
            {
                titulo : "Mobile Summit",
                data : "26 de setembro",
                local : "Nós Coworking",
                endereco : "Av. Cristovao Colombo, 545 - Prédio 02 - 3º andar, Porto Alegre - RS",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3454.3954512080186!2d-51.212344!3d-30.025510800000017!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0000000000000000%3A0x523e58ce2e6fac7d!2sN%C3%B3s+Coworking!5e0!3m2!1spt-BR!2sbr!4v1436214361314",
                localizacao : {
                    latitude: -30.0255108,
                    longitude: -51.212344
                },
                link : "http://www.msummit.com.br/"
            },
            {
                titulo : "Front in Vale",
                data : "28 de Setembro",
                local : "Faro Hotel São José dos Campos",
                endereco : "Rua Síria, Jardim Oswaldo Cruz, São José dos Campos - São Paulo",
                embed_link : "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d7334.556781778243!2d-45.88264!3d-23.196523!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94cc4a42f3190209%3A0x91ee04f155df318e!2sFaro+Hotel!5e0!3m2!1spt-BR!2sus!4v1438354820485",
                localizacao : {
                    latitude: -23.198722,
                    longitude: -45.883767
                },
                link : "http://frontinvale.com.br/"
            },
            {
                titulo : "1º Encontro PHPESTE",
                data : "3 e 4 de Outubro",
                local : "Instituto Federal da Paraíba",
                endereco : "Av. Primeiro de Maio, 795 - Jaguaribe, João Pessoa, Paraíba",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3958.9257522572016!2d-34.873064899999996!3d-7.1345847!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x7ace81a70c800dd%3A0x9b9b3adc146a7d82!2sAv.+Primeiro+de+Maio%2C+795+-+Jaguaribe%2C+Jo%C3%A3o+Pessoa+-+PB!5e0!3m2!1spt-BR!2sbr!4v1439134819504",
                localizacao : {
                    latitude: -7.1345847,
                    longitude: -34.8730648
                },
                link : "http://phpeste.net/"
            }
        ];

        w.Events = {
                getAll : function(){
                    return events;
                },

                getByTitulo : function (titulo) {
                    var eventos = this.getAll();
                    for(var index in eventos) {
                        var evento = events[index];
                        if (evento.titulo === titulo) {
                            return evento;
                        }
                    }
                }
        };
})(window);
<commit_msg>Delete old events<commit_after>(function(w){

        var events = [
            {
                titulo : "Android DevConference 2015",
                data : "29 de agosto",
                local : "Hotel Renaissance",
                endereco : "Av. Alameda Santos, 2233, São Paulo - SP",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3657.2665262031114!2d-46.662335999999996!3d-23.5588693!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94ce59d2c9a0e4c3%3A0x32c2ff75b7acd122!2sAlameda+Santos%2C+2233+-+Jardim+Paulista%2C+S%C3%A3o+Paulo+-+SP%2C+01419-002!5e0!3m2!1spt-BR!2sbr!4v1437063872582",
                localizacao : {
                    latitude: -23.5588693,
                    longitude: -46.6623359
                },
                link : "http://androidconference.imasters.com.br/"
            },
            {
                titulo : "WordCamp Rio de Janeiro 2015",
                data : "29 de agosto",
                local : "Senac Flamengo",
                endereco : "Rua Marquês de Abrantes, 99 – Flamengo – Rio de Janeiro, RJ",
                embed_link : "https://www.google.com/maps/embed?pb=!1m19!1m8!1m3!1d3674.371875920687!2d-43.1773033!3d-22.9365277!3m2!1i1024!2i768!4f13.1!4m8!3e6!4m0!4m5!1s0x997f88f435624f%3A0x83ed42214af802dd!2sR.+Marqu%C3%AAs+de+Abrantes%2C+99+-+Flamengo%2C+Rio+de+Janeiro+-+RJ%2C+22230-061!3m2!1d-22.9365277!2d-43.1773033!5e0!3m2!1spt-BR!2sbr!4v1437756544681",
                localizacao : {
                    latitude: -22.9365277,
                    longitude: -43.1773033
                },
                link : "https://riodejaneiro.wordcamp.org/2015/"
            },
            {
                titulo : "JoomlaDay Brasil 2015",
                data : "4 a 6 de Setembro",
                local : "Universidade Católica de Brasília",
                endereco : "QS 07, Lote 01, EPCT, s/n - Águas Claras, Brasília - DF",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3837.7826667761815!2d-48.02944694442749!3d-15.86801596095458!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x935a2d99eddf2aeb%3A0x1f93c6652deda3dc!2sUCB+-+Universidade+Cat%C3%B3lica+de+Bras%C3%ADlia!5e0!3m2!1spt-BR!2sbr!4v1439132769648",
                localizacao : {
                    latitude: -15.8680159,
                    longitude: -48.0294469
                },
                link : "http://joomladaybrasil.org/2015/"
            },
            {
                titulo : "RubyConf Brasil",
                data : "18 e 19 de Setembro",
                local : "FECOMERCIO SP",
                endereco : "Rua Doutor Plínio Barreto, 285 - Bela Vista - São Paulo",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d7314.430140061132!2d-46.653856000000005!3d-23.560717999999998!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0000000000000000%3A0x21c71fd197983309!2sFedera%C3%A7%C3%A3o+do+Com%C3%A9rcio+do+Estado+de+S%C3%A3o+Paulo!5e0!3m2!1spt-BR!2sus!4v1438352225051",
                localizacao : {
                    latitude: -23.55797,
                    longitude: -46.652316
                },
                link : "http://www.rubyconf.com.br/pt-BR/home"
            },
            {
                titulo : "Conferência Web.br 2015",
                data : "22 e 23 de setembro",
                local : "Centro de Convenções Rebolsas",
                endereco : "Rua Doutor Enéas de Carvalho Aguiar, 23 - Cerqueira Cesar",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3657.304241239964!2d-46.66812059999998!3d-23.5575142!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94ce582b0020752d%3A0x3c6835cc0084f24c!2sAv.+Dr.+En%C3%A9as+de+Carvalho+Aguiar%2C+23+-+Cerqueira+C%C3%A9sar%2C+S%C3%A3o+Paulo+-+SP!5e0!3m2!1sen!2sbr!4v1438211682234",
                localizacao : {
                    latitude: -23.557352,
                    longitude: -46.668105
                },
                link : "http://conferenciaweb.w3c.br/"
            },
            {
                titulo : "Front-End Carioca 2015",
                data : "26 de setembro",
                local : "Clube de Engenharia",
                endereco : "Av. Rio Branco, 124 - Centro, Rio de Janeiro - RJ",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3675.229129110692!2d-43.1780723!3d-22.904918100000003!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x997f5e44176677%3A0x13531119e47c4cc9!2sAv.+Rio+Branco%2C+124+-+Centro%2C+Rio+de+Janeiro+-+RJ%2C+20040-001!5e0!3m2!1spt-BR!2sbr!4v1435802972051",
                localizacao : {
                    latitude: -22.9049181,
                    longitude: -43.1780723
                },
                link : "http://frontendcarioca.com.br/"
            },
            {
                titulo : "Mobile Summit",
                data : "26 de setembro",
                local : "Nós Coworking",
                endereco : "Av. Cristovao Colombo, 545 - Prédio 02 - 3º andar, Porto Alegre - RS",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3454.3954512080186!2d-51.212344!3d-30.025510800000017!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0000000000000000%3A0x523e58ce2e6fac7d!2sN%C3%B3s+Coworking!5e0!3m2!1spt-BR!2sbr!4v1436214361314",
                localizacao : {
                    latitude: -30.0255108,
                    longitude: -51.212344
                },
                link : "http://www.msummit.com.br/"
            },
            {
                titulo : "Front in Vale",
                data : "28 de Setembro",
                local : "Faro Hotel São José dos Campos",
                endereco : "Rua Síria, Jardim Oswaldo Cruz, São José dos Campos - São Paulo",
                embed_link : "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d7334.556781778243!2d-45.88264!3d-23.196523!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94cc4a42f3190209%3A0x91ee04f155df318e!2sFaro+Hotel!5e0!3m2!1spt-BR!2sus!4v1438354820485",
                localizacao : {
                    latitude: -23.198722,
                    longitude: -45.883767
                },
                link : "http://frontinvale.com.br/"
            },
            {
                titulo : "1º Encontro PHPESTE",
                data : "3 e 4 de Outubro",
                local : "Instituto Federal da Paraíba",
                endereco : "Av. Primeiro de Maio, 795 - Jaguaribe, João Pessoa, Paraíba",
                embed_link : "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3958.9257522572016!2d-34.873064899999996!3d-7.1345847!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x7ace81a70c800dd%3A0x9b9b3adc146a7d82!2sAv.+Primeiro+de+Maio%2C+795+-+Jaguaribe%2C+Jo%C3%A3o+Pessoa+-+PB!5e0!3m2!1spt-BR!2sbr!4v1439134819504",
                localizacao : {
                    latitude: -7.1345847,
                    longitude: -34.8730648
                },
                link : "http://phpeste.net/"
            }
        ];

        w.Events = {
                getAll : function(){
                    return events;
                },

                getByTitulo : function (titulo) {
                    var eventos = this.getAll();
                    for(var index in eventos) {
                        var evento = events[index];
                        if (evento.titulo === titulo) {
                            return evento;
                        }
                    }
                }
        };
})(window);
<|endoftext|>


<commit_before>(function() {

  var unicodeData = null;
  var proto = location.protocol;

  function startup() {
    displayMsg("Fetching UnicodeData.txt...")
    var xhr = new XMLHttpRequest();
    xhr.onload = getData();
    xhr.open("GET", "../res/UnicodeData.txt", true);
    xhr.send();
  }

  function getData() {
    //console.log(this);
    if (this.status != "200" && this.status != "304") {
      complainMsg("Error fetching the file!")
    }
    else {
      displayMsg("Fetched file successfully.");
    }
  }

  function processText() {
    var text;
    if (!(text = document.getElementById("txt").value)) {
      alert("Enter some text, stupid");
      return;
    }
    alert("text");
  }

  function buttonEnabled(yn) {
    var btn = document.getElementById("btn");
    if (yn) {
      btn.removeAttribute("disabled");
    }
    else {
      btn.setAttribute("disabled", "");
    }
  }

  function displayMsg(msg) {
    document.getElementById("msg-line").className = "msg";
    writeMsg(msg);
  }

  function complainMsg(msg) {
    document.getElementById("msg-line").className = "msg bad";
    writeMsg(msg);
  }

  function writeMsg(msg) {
    document.getElementById("msg-line").innerHTML = msg;
  }

  window.submitText = function() {
    processText();
  }

  addEventListener("DOMContentLoaded", startup);

}).call();
<commit_msg>Update charident.js<commit_after>(function() {

  var unicodeData = null;
  var proto = location.protocol;

  function startup() {
    displayMsg("Fetching UnicodeData.txt...")
    var xhr = new XMLHttpRequest();
    xhr.onload = getData;
    xhr.open("GET", "../res/UnicodeData.txt", true);
    xhr.send();
  }

  function getData() {
    console.log(this.status);
    if (this.status != "200" && this.status != "304") {
      complainMsg("Error fetching the file!")
    }
    else {
      displayMsg("Fetched file successfully.");
    }
  }

  function processText() {
    var text;
    if (!(text = document.getElementById("txt").value)) {
      alert("Enter some text, stupid");
      return;
    }
    alert("text");
  }

  function buttonEnabled(yn) {
    var btn = document.getElementById("btn");
    if (yn) {
      btn.removeAttribute("disabled");
    }
    else {
      btn.setAttribute("disabled", "");
    }
  }

  function displayMsg(msg) {
    document.getElementById("msg-line").className = "msg";
    writeMsg(msg);
  }

  function complainMsg(msg) {
    document.getElementById("msg-line").className = "msg bad";
    writeMsg(msg);
  }

  function writeMsg(msg) {
    document.getElementById("msg-line").innerHTML = msg;
  }

  window.submitText = function() {
    processText();
  }

  addEventListener("DOMContentLoaded", startup);

}).call();
<|endoftext|>


<commit_before>var lang = require("./lang")

var state = {
  namespace: "",
  coreRequired: false,
  scopeNames: true,
  scopes: [[]]
}

// TODO: Stream
function assemble (translation) {
  var lines = []

  if (!translation) return lines

  translation.forEach(function (t) {
    if (t instanceof lang.Function) {
      lines = lines.concat(genFunction(t))
    } else if (t instanceof lang.Variable) {
      lines = lines.concat(genVariable(t))
    } else if (t instanceof lang.Invoke) {
      lines = lines.concat(genInvoke(t))
    } else if (t instanceof lang.Keyword) {
      lines = lines.concat(genKeyword(t))
    } else if (t instanceof lang.Symbol) {
      lines = lines.concat(genSymbol(t))
    } else if (t instanceof lang.String) {
      lines = lines.concat(genString(t))
    } else if (t instanceof lang.Number) {
      lines = lines.concat(genNumber(t))
    } else if (t instanceof lang.Boolean) {
      lines = lines.concat(genBoolean(t))
    } else if (t instanceof lang.Namespace) {
      lines = lines.concat(genNamespace(t))
    } else if (t instanceof lang.Assign) {
      lines = lines.concat(genAssign(t))
    } else if (t instanceof lang.Comparison) {
      lines = lines.concat(genComparison(t))
    } else {
      throw new Error("Compile error " + JSON.stringify(t))
    }
  })

  return lines
}

function genFunction (t) {
  if (!state.namespace) throw new Error("No namespace declared")

  state.scopeNames = false
  var functionName = assemble(t.name)[0]
  state.scopeNames = true

  // Add the function to the current scope
  addDefinition(functionName)

  var code = assemble(t.name)[0] + " = function " + functionName + " ("

  // Create a new scope where the function parameters will be declared
  createScope()

  state.scopeNames = false
  code += t.args.val.map(function (arg) {
    var name = assemble([arg])[0]
    addDefinition(name)
    return name
  }).join(", ")
  state.scopeNames = true

  code += ") {"

  var assembledBody = assemble(t.body)

  if (assembledBody.length > 1) {
    code += assembledBody.slice(0, assembledBody.length - 1).join(";\n")
    code += ";\nreturn " + assembledBody[assembledBody.length - 1]
  } else if (t.body.length) {
    code += "return " + assembledBody[0]
  }

  code += "}"

  destroyScope()

  return [code]
}

function genVariable (t) {
  state.scopeNames = false
  var v = assemble(t.name)[0]
  state.scopeNames = true

  addDefinition(v)

  // Top scope gets appended to namespace
  if (state.scopes.length > 1) {
    v = "var " + v
  } else {
    v = state.namespace + "." + v
  }

  return [v + " = " + assemble(t.val)[0]]
}

function genInvoke (t) {
  var lines = []
  var code = ""
  var functionName = assemble(t.name)[0]

  if (!defined(functionName) && !state.coreRequired) {
    state.coreRequired = true
    lines.push("goog.require('cljs.core')")
  }

  if (t.name[0].name.indexOf("js/") > -1) {
    code += functionName + "("
  } else {
    code += functionName + ".call(null"

    if (t.args.length) {
      code += ", "
    }
  }

  if (t.args.length) {
    code += t.args.map(function (arg) {
      return assemble([arg])[0]
    }).join(", ")
  }

  code += ")"

  lines.push(code)

  return lines
}

function genKeyword (t) {
  return [makeJsSafe(t.name)]
}

function genSymbol (t) {
  return [scopedName(t.name)]
}

function genString (t) {
  return ['"' + t.val.replace(/"/g, '\\"') + '"']
}

function genNumber (t) {
  return [t.val.toString()]
}

function genBoolean (t) {
  return [t.val.toString()]
}

function genNamespace (t) {
  state.scopeNames = false
  state.namespace = assemble(t.name)[0]
  state.scopeNames = true
  state.scopes = [[]]
  return ["goog.provide('" + state.namespace + "')"]
}

function genAssign (t) {
  return [assemble(t.name)[0] + " = " + assemble(t.val)[0]]
}

function genComparison (t) {
  console.log(t)
  return ["(" + assemble(t.left) + " " + t.type[0].name + " " + assemble(t.right) + ")"]
}

// Utility

function makeJsSafe (val) {
  return val
    .replace(/-/g, "_")
    .replace(/\*/g, "_STAR_")
    .replace(/!/g, "_BANG_")
    .replace(/=/g, "_EQ_")
}

// Search through current scope and parent scopes to see if name exists
function defined (name) {
  for (var i = 0; i < state.scopes.length; i++) {
    if (state.scopes[i].indexOf(name) > -1) {
      return true
    }
  }
  return false
}

function scopedName (name) {
  name = makeJsSafe(name)

  if (!state.scopeNames) return name

  for (var i = 0; i < state.scopes.length; i++) {
    if (state.scopes[i].indexOf(name) > -1) {
      if (i == state.scopes.length -1) {
        return state.namespace + "." + name
      } else {
        return name
      }
    }
  }

  // Namespaced name
  if (name.indexOf("/") > -1) {
    if (name.indexOf("js/") > -1) {
      return name.replace("js/", "")
    }
    return name.replace("/", ".")
  }

  // TODO: Check defined in core?
  return "cljs.core." + name
}

function addDefinition (name) {
  state.scopes[0].push(name)
  return name
}

function createScope () {
  state.scopes.unshift([])
}

function destroyScope () {
  state.scopes = state.scopes.slice(1)
}

module.exports = function (translation) {
  //console.log(JSON.stringify(translation, null, 2))
  return assemble(translation).join(";\n") + ";"
}<commit_msg>Assemble namespaced variables correctly<commit_after>var lang = require("./lang")

var state = {
  namespace: "",
  coreRequired: false,
  scopeNames: true,
  scopes: [[]]
}

// TODO: Stream
function assemble (translation) {
  var lines = []

  if (!translation) return lines

  translation.forEach(function (t) {
    if (t instanceof lang.Function) {
      lines = lines.concat(genFunction(t))
    } else if (t instanceof lang.Variable) {
      lines = lines.concat(genVariable(t))
    } else if (t instanceof lang.Invoke) {
      lines = lines.concat(genInvoke(t))
    } else if (t instanceof lang.Keyword) {
      lines = lines.concat(genKeyword(t))
    } else if (t instanceof lang.Symbol) {
      lines = lines.concat(genSymbol(t))
    } else if (t instanceof lang.String) {
      lines = lines.concat(genString(t))
    } else if (t instanceof lang.Number) {
      lines = lines.concat(genNumber(t))
    } else if (t instanceof lang.Boolean) {
      lines = lines.concat(genBoolean(t))
    } else if (t instanceof lang.Namespace) {
      lines = lines.concat(genNamespace(t))
    } else if (t instanceof lang.Assign) {
      lines = lines.concat(genAssign(t))
    } else if (t instanceof lang.Comparison) {
      lines = lines.concat(genComparison(t))
    } else {
      throw new Error("Compile error " + JSON.stringify(t))
    }
  })

  return lines
}

function genFunction (t) {
  if (!state.namespace) throw new Error("No namespace declared")

  state.scopeNames = false
  var functionName = assemble(t.name)[0]
  state.scopeNames = true

  // Add the function to the current scope
  addDefinition(functionName)

  var code = assemble(t.name)[0] + " = function " + functionName + " ("

  // Create a new scope where the function parameters will be declared
  createScope()

  state.scopeNames = false
  code += t.args.val.map(function (arg) {
    var name = assemble([arg])[0]
    addDefinition(name)
    return name
  }).join(", ")
  state.scopeNames = true

  code += ") {"

  var assembledBody = assemble(t.body)

  if (assembledBody.length > 1) {
    code += assembledBody.slice(0, assembledBody.length - 1).join(";\n")
    code += ";\nreturn " + assembledBody[assembledBody.length - 1]
  } else if (t.body.length) {
    code += "return " + assembledBody[0]
  }

  code += "}"

  destroyScope()

  return [code]
}

function genVariable (t) {
  state.scopeNames = false
  var v = assemble(t.name)[0]
  state.scopeNames = true

  addDefinition(v)

  // Top scope gets appended to namespace
  if (state.scopes.length > 1) {
    v = "var " + v
  } else {
    v = state.namespace + "." + v
  }

  return [v + " = " + assemble(t.val)[0]]
}

function genInvoke (t) {
  var lines = []
  var code = ""
  var functionName = assemble(t.name)[0]

  if (!defined(functionName) && !state.coreRequired) {
    state.coreRequired = true
    lines.push("goog.require('cljs.core')")
  }

  if (t.name[0].name.indexOf(".") > -1) {
    code += functionName + "("
  } else {
    code += functionName + ".call(null"

    if (t.args.length) {
      code += ", "
    }
  }

  if (t.args.length) {
    code += t.args.map(function (arg) {
      return assemble([arg])[0]
    }).join(", ")
  }

  code += ")"

  lines.push(code)

  return lines
}

function genKeyword (t) {
  return [makeJsSafe(t.name)]
}

function genSymbol (t) {
  return [scopedName(t.name)]
}

function genString (t) {
  return ['"' + t.val.replace(/"/g, '\\"') + '"']
}

function genNumber (t) {
  return [t.val.toString()]
}

function genBoolean (t) {
  return [t.val.toString()]
}

function genNamespace (t) {
  state.scopeNames = false
  state.namespace = assemble(t.name)[0]
  state.scopeNames = true
  state.scopes = [[]]
  return ["goog.provide('" + state.namespace + "')"]
}

function genAssign (t) {
  return [assemble(t.name)[0] + " = " + assemble(t.val)[0]]
}

function genComparison (t) {
  return ["(" + assemble(t.left) + " " + t.type[0].name + " " + assemble(t.right) + ")"]
}

// Utility

function makeJsSafe (val) {
  return val
    .replace(/-/g, "_")
    .replace(/\*/g, "_STAR_")
    .replace(/!/g, "_BANG_")
    .replace(/=/g, "_EQ_")
}

// Search through current scope and parent scopes to see if name exists
function defined (name) {
  for (var i = 0; i < state.scopes.length; i++) {
    if (state.scopes[i].indexOf(name) > -1) {
      return true
    }
  }
  return false
}

function scopedName (name) {
  name = makeJsSafe(name)

  if (!state.scopeNames) return name

  // Namespaced name
  if (name.indexOf("/") > -1) {
    if (name.indexOf("js/") > -1) {
      return name.replace("js/", "")
    }
    return name.replace("/", ".")
  }

  var localName = null

  if (name.indexOf(".") > -1) {
    localName = name.slice(0, name.indexOf("."))
  } else {
    localName = name
  }

  for (var i = 0; i < state.scopes.length; i++) {
    if (state.scopes[i].indexOf(localName) > -1) {
      if (i == state.scopes.length - 1) {
        return state.namespace + "." + name
      } else {
        return name
      }
    }
  }

  // TODO: Check defined in core?
  return "cljs.core." + name
}

function addDefinition (name) {
  state.scopes[0].push(name)
  return name
}

function createScope () {
  state.scopes.unshift([])
}

function destroyScope () {
  state.scopes = state.scopes.slice(1)
}

module.exports = function (translation) {
  //console.log(JSON.stringify(translation, null, 2))
  return assemble(translation).join(";\n") + ";"
}<|endoftext|>


<commit_before>var htmlBody=document.querySelector('body');
ipcRenderer.send('x-setting-panel-ready');
ipcRenderer.on('x-resize',(event,data)=>{
	console.log(data.size);
	htmlBody.style.height=data.size[1]+'px';
	document.querySelector('#pictureSquare').style.height=data.size[1]-123+'px';
});
ipcRenderer.on('x-setting-panel-list',(event,data)=>{
	console.log(data);
	let navs=data.nav.split('\\').slice(1);
	let a="";
	for(let n of navs){
		a+=""+n+"";
	}
	navbar.innerHTML=a;
	let html="";
	data.files.forEach(function(o,i){
		if(o.type!=='folder'){
			html+="
"
					+""
						+""
						+""
							+""
						+""
					+""
					+"
"
						+""
					+"
"
					+""
						+o.name
					+""
				+"
";
		}else{
			html+="
"
					+""
						+""
						+""
							+""
						+""
					+""
					+"
"
						+"
"
							+"

"
							+"

"
							+"

"
						+"
"
					+"
"
					+""
						+o.name
					+""
				+"
";
		}
	});
	pictureSquare.innerHTML=html;
});

// 判断图片宽高比例来缩放图片
var scale=9/7;//width/height
function scaleImg(self){
	// console.log(self.width);
	// console.log(self.height);
	if(self.width/self.height>scale){
		self.style.width='100%';
		self.style.height='auto';
	}else{
		self.style.height='70px';
		self.style.width='auto';
	}
}
// 双击打开文件夹
function openFolder(path){
	// console.log(path)
	ipcRenderer.send('x-setting-panel-open-folder',{path:path});
}
// 右键菜单
let targetElement;//保存待操作的图片路径
function showMenu(event,link){
	let articles=document.querySelectorAll('#pictureSquare article');
	for(let e in articles){
		articles[e].classList && articles[e].classList.remove('active');
	}
 	console.log(event);
 	if(event.button==2){
 		targetElement=link;
 		let path=event.path;
 		for(let e in path){
 			if(path[e].nodeName.toLowerCase()=='article'){
 				path[e].classList.add('active');
 				break;
 			}
 		}
 		rightMenu.style.left=event.pageX+10+'px';
 		rightMenu.style.top=event.pageY+10+'px';
 		rightMenu.style.display='block';
 		// rightMenu.addAttribute('index','-1');
 		pictureSquare.onmousewheel=function(){
 			return false;
 		};
 	}else{
 		targetElement=null;
 		// rightMenu.removeAttribute('index');
 		pictureSquare.onmousewheel=function(){
 			return true;
 		};
 		rightMenu.style.display='none';
 	}
}
// 右键菜单
const openFileFn=()=>{

};
const uploadFn=()=>{

};
const openFilePositionFn=()=>{
	if(targetElement){
		alert(targetElement)
	}
};
<commit_msg>增加后台管理界面菜单弹出的临界位置判断逻辑<commit_after>var htmlBody=document.querySelector('body');
ipcRenderer.send('x-setting-panel-ready');
ipcRenderer.on('x-resize',(event,data)=>{
	console.log(data.size);
	htmlBody.style.height=data.size[1]+'px';
	document.querySelector('#pictureSquare').style.height=data.size[1]-123+'px';
});
ipcRenderer.on('x-setting-panel-list',(event,data)=>{
	console.log(data);
	let navs=data.nav.split('\\').slice(1);
	let a="";
	for(let n of navs){
		a+=""+n+"";
	}
	navbar.innerHTML=a;
	let html="";
	data.files.forEach(function(o,i){
		if(o.type!=='folder'){
			html+="
"
					+""
						+""
						+""
							+""
						+""
					+""
					+"
"
						+""
					+"
"
					+""
						+o.name
					+""
				+"
";
		}else{
			html+="
"
					+""
						+""
						+""
							+""
						+""
					+""
					+"
"
						+"
"
							+"

"
							+"

"
							+"

"
						+"
"
					+"
"
					+""
						+o.name
					+""
				+"
";
		}
	});
	pictureSquare.innerHTML=html;
});

// 判断图片宽高比例来缩放图片
var scale=9/7;//width/height
function scaleImg(self){
	// console.log(self.width);
	// console.log(self.height);
	if(self.width/self.height>scale){
		self.style.width='100%';
		self.style.height='auto';
	}else{
		self.style.height='70px';
		self.style.width='auto';
	}
}
// 双击打开文件夹
function openFolder(path){
	// console.log(path)
	ipcRenderer.send('x-setting-panel-open-folder',{path:path});
}
// 右键菜单
let targetElement;//保存待操作的图片路径
function showMenu(event,link){
	let articles=document.querySelectorAll('#pictureSquare article');
	for(let e in articles){
		articles[e].classList && articles[e].classList.remove('active');
	}
 	console.log(event);
 	if(event.button==2){
 		targetElement=link;
 		let path=event.path;
 		for(let e in path){
 			if(path[e].nodeName.toLowerCase()=='article'){
 				path[e].classList.add('active');
 				break;
 			}
 		}
 		// 菜单位置靠左边
 		if(window.document.body.clientWidth-event.pageX<=110){
 			rightMenu.style.left=event.pageX-108-10+'px';
 		}else{
 			rightMenu.style.left=event.pageX+10+'px';
 		}
 		// 菜单位上边置靠
 		if(window.document.body.clientHeight-event.pageY<=170){
 			rightMenu.style.top=event.pageY-162-10+'px';
 		}else{
 			rightMenu.style.top=event.pageY+10+'px';
 		}
 		rightMenu.style.display='block';
 		// rightMenu.addAttribute('index','-1');
 		pictureSquare.onmousewheel=function(){
 			return false;
 		};
 	}else{
 		targetElement=null;
 		// rightMenu.removeAttribute('index');
 		pictureSquare.onmousewheel=function(){
 			return true;
 		};
 		rightMenu.style.display='none';
 	}
}
// 右键菜单
const openFileFn=()=>{

};
const uploadFn=()=>{

};
const openFilePositionFn=()=>{
	if(targetElement){
		alert(targetElement)
	}
};
<|endoftext|>


<commit_before>var DEBUG = 0;

// General
var EXTENSION_NAME = 'Online Notifier';
var EXTENSION_NICK = 'Notifier';
var EXTENSION_WEBSITE = 'https://online.ntnu.no';
var CREATOR_NAME = 'Online'; // max 8 letters because of styling
var CREATOR_EMAIL = 'dotkom@online.ntnu.no';

// AJAX setup
var AJAX_SETUP = {
	timeout: 9000,
	cache: false,
}

// Loops & intervals
var BACKGROUND_LOOP = 30000; // 30s
var BACKGROUND_LOOP_OFFLINE = 3000; // 3s, respond quickly when we get back online
var PAGE_LOOP = 10000; // 10s

// Update stuff at every X intervals
var UPDATE_OFFICE_INTERVAL = 1; // recommended: 1
var UPDATE_SERVANT_INTERVAL = 20; // recommended: 20
var UPDATE_MEETINGS_INTERVAL = 20; // recommended: 20
var UPDATE_COFFEE_INTERVAL = 1; // recommended: 1
var UPDATE_HOURS_INTERVAL = 60; // recommended: 60
var UPDATE_CANTINAS_INTERVAL = 60; // recommended: 60
var UPDATE_BUS_INTERVAL = 1; // recommended: 1
var UPDATE_NEWS_INTERVAL = 20; // recommended: 30

// OS detection
var OPERATING_SYSTEM = "Unknown";
if (navigator.appVersion.indexOf("Win")!==-1) OPERATING_SYSTEM="Windows";
else if (navigator.appVersion.indexOf("Linux")!==-1) OPERATING_SYSTEM="Linux";
else if (navigator.appVersion.indexOf("X11")!==-1) OPERATING_SYSTEM="UNIX";
else if (navigator.appVersion.indexOf("Mac")!==-1) {
	OPERATING_SYSTEM = "Old Mac";
	if (navigator.appVersion.indexOf("10_7")!==-1||navigator.appVersion.indexOf("10_8")!==-1) {
		OPERATING_SYSTEM = "Mac";
	}
}
else {
	console.log("ERROR: Potentially unsupported operating system");
}

// Browser detection
var BROWSER = "Unknown";
if (typeof chrome != "undefined")
	BROWSER = "Chrome";
else if (typeof opera != "undefined")
	BROWSER = "Opera";
else {
	console.log("ERROR: Potentially unsupported browser");
}

// Production detection
if (BROWSER == "Chrome") {
	if (chrome.i18n.getMessage('@@extension_id') === "hfgffimlnajpbenfpaofmmffcdmgkllf") {
		DEBUG = 0;
	}
}
else if (BROWSER == "Opera") {
	// TODO: Implement this
}
<commit_msg>constants: adding an undefined-check<commit_after>var DEBUG = 1;

// General
var EXTENSION_NAME = 'Online Notifier';
var EXTENSION_NICK = 'Notifier';
var EXTENSION_WEBSITE = 'https://online.ntnu.no';
var CREATOR_NAME = 'Online'; // max 8 letters because of styling
var CREATOR_EMAIL = 'dotkom@online.ntnu.no';

// AJAX setup
var AJAX_SETUP = {
	timeout: 9000,
	cache: false,
}

// Loops & intervals
var BACKGROUND_LOOP = 30000; // 30s
var BACKGROUND_LOOP_OFFLINE = 3000; // 3s, respond quickly when we get back online
var PAGE_LOOP = 10000; // 10s

// Update stuff at every X intervals
var UPDATE_OFFICE_INTERVAL = 1; // recommended: 1
var UPDATE_SERVANT_INTERVAL = 20; // recommended: 20
var UPDATE_MEETINGS_INTERVAL = 20; // recommended: 20
var UPDATE_COFFEE_INTERVAL = 1; // recommended: 1
var UPDATE_HOURS_INTERVAL = 60; // recommended: 60
var UPDATE_CANTINAS_INTERVAL = 60; // recommended: 60
var UPDATE_BUS_INTERVAL = 1; // recommended: 1
var UPDATE_NEWS_INTERVAL = 20; // recommended: 30

// OS detection
var OPERATING_SYSTEM = "Unknown";
if (navigator.appVersion.indexOf("Win")!==-1) OPERATING_SYSTEM="Windows";
else if (navigator.appVersion.indexOf("Linux")!==-1) OPERATING_SYSTEM="Linux";
else if (navigator.appVersion.indexOf("X11")!==-1) OPERATING_SYSTEM="UNIX";
else if (navigator.appVersion.indexOf("Mac")!==-1) {
	OPERATING_SYSTEM = "Old Mac";
	if (navigator.appVersion.indexOf("10_7")!==-1||navigator.appVersion.indexOf("10_8")!==-1) {
		OPERATING_SYSTEM = "Mac";
	}
}
else {
	console.log("ERROR: Potentially unsupported operating system");
}

// Browser detection
var BROWSER = "Unknown";
if (typeof chrome != "undefined")
	BROWSER = "Chrome";
else if (typeof opera != "undefined")
	BROWSER = "Opera";
else {
	console.log("ERROR: Potentially unsupported browser");
}

// Production detection
if (BROWSER == "Chrome") {
	if (typeof chrome.i18n != "undefined") {
		if (chrome.i18n.getMessage('@@extension_id') === "hfgffimlnajpbenfpaofmmffcdmgkllf") {
			DEBUG = 0;
		}
	}
}
else if (BROWSER == "Opera") {
	// TODO: Implement this
}
<|endoftext|>


<commit_before>/* eslint-env browser */
(function() {
  // Detect env.
  var isNode = typeof module !== 'undefined' && module.exports;
  /**
    A tiny assertion lib for both nodejs and the browser.
    @module asserter
    @author Luis Leiva
  */
  var asserter = {
    tests: [],
    currentTest: null,
    negated: false,
    test: function(message) {
      this.currentTest = message;
      this.negated = false;
      return this;
    },
    _set: function(value, reference, operator, result) {
      this.tests.push({
        value: value,
        reference: reference,
        operator: operator,
        negated: this.negated,
        result: result,
        message: this.currentTest,
      });
      return this;
    },
    _condition: function(expr) {
      return !this.negated ? expr : !expr;
    },
    not: function() {
      this.negated = true;
      return this;
    },
    // BEGIN General-purpose matchers.
    equals: function(value, reference) {
      return this._set(value, reference, '==', this._condition(value == reference));
    },
    strictEquals: function(value, reference) {
      return this._set(value, reference, '===', this._condition(value === reference));
    },
    // BEGIN Numberical matchers.
    isGreaterThan: function(value, reference) {
      return this._set(value, reference, '>', this._condition(value > reference));
    },
    isGreaterThanOrEquals: function(value, reference) {
      return this._set(value, reference, '>=', this._condition(value >= reference));
    },
    isLessThan: function(value, reference) {
      return this._set(value, reference, '<', this._condition(value < reference));
    },
    isLessThanOrEquals: function(value, reference) {
      return this._set(value, reference, '<=', this._condition(value <= reference));
    },
    // BEGIN RegExp matchers.
    matches: function(value, reference) {
      return this._set(value, reference, 'matches', this._condition(value.test(reference)));
    },
    // BEGIN String matchers.
    contains: function(value, reference) {
      return this._set(value, reference, 'contains', this._condition(value.indexOf(reference) > -1));
    },
    // BEGIN Other matchers.
    throws: function(fn) {
      try {
        fn();
        this._set('success', 'error', 'is', this._condition(false));
      } catch(err) {
        this._set('success', 'success', 'is', this._condition(true));
      }
    },
    display: console.log,
    // Main.
    run: function() {
      var successes = 0;
      var errors = 0;
      this.tests.forEach(function(test) {
        var label = test.result ? greenBg('PASS') : redBg('FAIL');
        if (!test.result) {
          var reason = test.negated
            ? sprintf('was NOT expecting %s %s %s', test.reference, test.operator, test.value)
            : sprintf('was expecting %s %s %s', test.reference, test.operator, test.value);
          test.message += ' ' + yellow(reason);
          errors++;
        } else {
          successes++;
        }
        asserter.display(label, test.message);
      });
      asserter.display(sprintf('\n%s/%s tests passed (%s errors).', successes, successes + errors, errors));
    },
  };

  // How is that this function is not part of the std lib?
  function sprintf() {
    var args = [].slice.call(arguments);
    var str = args.shift();
    args.forEach(function(arg) {
      str = str.replace('%s', arg);
    });
    return str;
  }

  // Color helpers stuff.
  function colorize(color, msg) {
    if (!isNode) return sprintf('[%s]', msg);
    return color + msg + '\x1b[0m';
  }
  function redBg(msg) {
    return colorize('\x1b[41m', msg);
  }
  function greenBg(msg) {
    return colorize('\x1b[42m', msg);
  }
  function yellow(msg) {
    return colorize('\x1b[33m', msg);
  }

  // Expose library.
  if (isNode) {
    module.exports = asserter;
  } else {
    window.asserter = asserter;
  }

})();
<commit_msg>Added strict mode<commit_after>/* eslint-env browser */
(function() {
  'use strict';
  // Detect env.
  var isNode = typeof module !== 'undefined' && module.exports;
  /**
    A tiny assertion lib for both nodejs and the browser.
    @module asserter
    @author Luis Leiva
  */
  var asserter = {
    tests: [],
    currentTest: null,
    negated: false,
    test: function(message) {
      this.currentTest = message;
      this.negated = false;
      return this;
    },
    _set: function(value, reference, operator, result) {
      this.tests.push({
        value: value,
        reference: reference,
        operator: operator,
        negated: this.negated,
        result: result,
        message: this.currentTest,
      });
      return this;
    },
    _condition: function(expr) {
      return !this.negated ? expr : !expr;
    },
    not: function() {
      this.negated = true;
      return this;
    },
    // BEGIN General-purpose matchers.
    equals: function(value, reference) {
      return this._set(value, reference, '==', this._condition(value == reference));
    },
    strictEquals: function(value, reference) {
      return this._set(value, reference, '===', this._condition(value === reference));
    },
    // BEGIN Numberical matchers.
    isGreaterThan: function(value, reference) {
      return this._set(value, reference, '>', this._condition(value > reference));
    },
    isGreaterThanOrEquals: function(value, reference) {
      return this._set(value, reference, '>=', this._condition(value >= reference));
    },
    isLessThan: function(value, reference) {
      return this._set(value, reference, '<', this._condition(value < reference));
    },
    isLessThanOrEquals: function(value, reference) {
      return this._set(value, reference, '<=', this._condition(value <= reference));
    },
    // BEGIN RegExp matchers.
    matches: function(value, reference) {
      return this._set(value, reference, 'matches', this._condition(value.test(reference)));
    },
    // BEGIN String matchers.
    contains: function(value, reference) {
      return this._set(value, reference, 'contains', this._condition(value.indexOf(reference) > -1));
    },
    // BEGIN Other matchers.
    throws: function(fn) {
      try {
        fn();
        this._set('success', 'error', 'is', this._condition(false));
      } catch(err) {
        this._set('success', 'success', 'is', this._condition(true));
      }
    },
    display: console.log,
    // Main.
    run: function() {
      var successes = 0;
      var errors = 0;
      this.tests.forEach(function(test) {
        var label = test.result ? greenBg('PASS') : redBg('FAIL');
        if (!test.result) {
          var reason = test.negated
            ? sprintf('was NOT expecting %s %s %s', test.reference, test.operator, test.value)
            : sprintf('was expecting %s %s %s', test.reference, test.operator, test.value);
          test.message += ' ' + yellow(reason);
          errors++;
        } else {
          successes++;
        }
        asserter.display(label, test.message);
      });
      asserter.display(sprintf('\n%s/%s tests passed (%s errors).', successes, successes + errors, errors));
    },
  };

  // How is that this function is not part of the std lib?
  function sprintf() {
    var args = [].slice.call(arguments);
    var str = args.shift();
    args.forEach(function(arg) {
      str = str.replace('%s', arg);
    });
    return str;
  }

  // Color helpers stuff.
  function colorize(color, msg) {
    if (!isNode) return sprintf('[%s]', msg);
    return color + msg + '\x1b[0m';
  }
  function redBg(msg) {
    return colorize('\x1b[41m', msg);
  }
  function greenBg(msg) {
    return colorize('\x1b[42m', msg);
  }
  function yellow(msg) {
    return colorize('\x1b[33m', msg);
  }

  // Expose library.
  if (isNode) {
    module.exports = asserter;
  } else {
    window.asserter = asserter;
  }

})();
<|endoftext|>


<commit_before>var DEBUG = 0;

// AJAX setup
var AJAX_SETUP = {
	timeout: 9000,
	cache: false, // this little sentence killed a lot of little bugs that was actually one big bug
}

// Logging setup
console.lolg = function() {
	// Console logging that only happens in debug mode
	// The name "lolg" is a tribute to Lorents Odin Lervik Gravås
	if (DEBUG) {
		console.log.apply(console, arguments);
	}
};

// Loops & intervals
var BACKGROUND_LOOP = 30000; // 30s
var BACKGROUND_LOOP_OFFLINE = 3000; // 3s, respond quickly when we get back online
var PAGE_LOOP = 10000; // 10s

// Update stuff at every X intervals
var UPDATE_OFFICE_INTERVAL = 1; // recommended: 1
var UPDATE_SERVANT_INTERVAL = 20; // recommended: 20
var UPDATE_MEETINGS_INTERVAL = 20; // recommended: 20
var UPDATE_COFFEE_INTERVAL = 1; // recommended: 1
var UPDATE_HOURS_INTERVAL = 60; // recommended: 60
var UPDATE_CANTINAS_INTERVAL = 60; // recommended: 60
var UPDATE_BUS_INTERVAL = 2; // recommended: 1
var UPDATE_NEWS_INTERVAL = 20; // recommended: 20

// Meme detection
var urlExists = function(url) {
	try {
	    var http = new XMLHttpRequest();
	    http.open('HEAD', url, false);
	    http.send();
	    return http.status!=404;
	}
	catch (e) {
		return false;
	}
	finally {
		// do nothing
	}
}
var MEME_AMOUNT = 0;
var __counter__ = 1;
while (urlExists('meme/'+__counter__+'.jpg')) {
	MEME_AMOUNT++;
	__counter__++;
}

// OS detection
var OPERATING_SYSTEM = "Unknown";
if (navigator.appVersion.indexOf("Win")!==-1) OPERATING_SYSTEM="Windows";
else if (navigator.appVersion.indexOf("Linux")!==-1) OPERATING_SYSTEM="Linux";
else if (navigator.appVersion.indexOf("X11")!==-1) OPERATING_SYSTEM="UNIX";
else if (navigator.appVersion.indexOf("Mac")!==-1) {
	OPERATING_SYSTEM = "Old Mac";
	if (navigator.appVersion.indexOf("10_7")!==-1||navigator.appVersion.indexOf("10_8")!==-1) {
		OPERATING_SYSTEM = "Mac";
	}
}
else {
	console.log('WARNING: Potentially unsupported operating system');
}

// Browser detection
var BROWSER = "Unknown";
if (navigator.userAgent.indexOf('Chrome') !== -1 && navigator.userAgent.indexOf('OPR') == -1)
	BROWSER = "Chrome";
else if (navigator.userAgent.indexOf('OPR') !== -1)
	BROWSER = "Opera";
else
	console.log('WARNING: Potentially unsupported browser');

// Production detection
if (BROWSER == 'Chrome')
	if (chrome.runtime.id === 'hfgffimlnajpbenfpaofmmffcdmgkllf')
		DEBUG = 0;
else if (BROWSER == 'Opera')
	if (chrome.runtime.id === 'npnpbddfcaibgnegafofkmffmbmflelj')
		DEBUG = 0;
<commit_msg>constants: enabled debug<commit_after>var DEBUG = 1;

// AJAX setup
var AJAX_SETUP = {
	timeout: 9000,
	cache: false, // this little sentence killed a lot of little bugs that was actually one big bug
}

// Logging setup
console.lolg = function() {
	// Console logging that only happens in debug mode
	// The name "lolg" is a tribute to Lorents Odin Lervik Gravås
	if (DEBUG) {
		console.log.apply(console, arguments);
	}
};

// Loops & intervals
var BACKGROUND_LOOP = 30000; // 30s
var BACKGROUND_LOOP_OFFLINE = 3000; // 3s, respond quickly when we get back online
var PAGE_LOOP = 10000; // 10s

// Update stuff at every X intervals
var UPDATE_OFFICE_INTERVAL = 1; // recommended: 1
var UPDATE_SERVANT_INTERVAL = 20; // recommended: 20
var UPDATE_MEETINGS_INTERVAL = 20; // recommended: 20
var UPDATE_COFFEE_INTERVAL = 1; // recommended: 1
var UPDATE_HOURS_INTERVAL = 60; // recommended: 60
var UPDATE_CANTINAS_INTERVAL = 60; // recommended: 60
var UPDATE_BUS_INTERVAL = 2; // recommended: 1
var UPDATE_NEWS_INTERVAL = 20; // recommended: 20

// Meme detection
var urlExists = function(url) {
	try {
	    var http = new XMLHttpRequest();
	    http.open('HEAD', url, false);
	    http.send();
	    return http.status!=404;
	}
	catch (e) {
		return false;
	}
	finally {
		// do nothing
	}
}
var MEME_AMOUNT = 0;
var __counter__ = 1;
while (urlExists('meme/'+__counter__+'.jpg')) {
	MEME_AMOUNT++;
	__counter__++;
}

// OS detection
var OPERATING_SYSTEM = "Unknown";
if (navigator.appVersion.indexOf("Win")!==-1) OPERATING_SYSTEM="Windows";
else if (navigator.appVersion.indexOf("Linux")!==-1) OPERATING_SYSTEM="Linux";
else if (navigator.appVersion.indexOf("X11")!==-1) OPERATING_SYSTEM="UNIX";
else if (navigator.appVersion.indexOf("Mac")!==-1) {
	OPERATING_SYSTEM = "Old Mac";
	if (navigator.appVersion.indexOf("10_7")!==-1||navigator.appVersion.indexOf("10_8")!==-1) {
		OPERATING_SYSTEM = "Mac";
	}
}
else {
	console.log('WARNING: Potentially unsupported operating system');
}

// Browser detection
var BROWSER = "Unknown";
if (navigator.userAgent.indexOf('Chrome') !== -1 && navigator.userAgent.indexOf('OPR') == -1)
	BROWSER = "Chrome";
else if (navigator.userAgent.indexOf('OPR') !== -1)
	BROWSER = "Opera";
else
	console.log('WARNING: Potentially unsupported browser');

// Production detection
if (BROWSER == 'Chrome')
	if (chrome.runtime.id === 'hfgffimlnajpbenfpaofmmffcdmgkllf')
		DEBUG = 0;
else if (BROWSER == 'Opera')
	if (chrome.runtime.id === 'npnpbddfcaibgnegafofkmffmbmflelj')
		DEBUG = 0;
<|endoftext|>


<commit_before>function contactos(){

	this.getContacts = function(){
		try{
	    var options = new ContactFindOptions();
	    options.filter = "";
	    options.multiple = true;
	    filter = ["displayName", "name"];
	    navigator.contacts.find(filter, function(){
		    for (var i = 0; i < contacts.length; i++) {
		        alert("Formatted: "  + contacts[i].name.formatted       + "\n" +
		            "Family Name: "  + contacts[i].name.familyName      + "\n" +
		            "Given Name: "   + contacts[i].name.givenName       + "\n" +
		            "Middle Name: "  + contacts[i].name.middleName      + "\n" +
		            "Number: "       + contacts[i].phoneNumbers[0].value + "\n" +
		            "Prefix: "       + contacts[i].name.honorificSuffix);
		    }
	    }, function(){alert('onError!');}, options);
		} catch(e){
			alert(e);
		}
	}
}
<commit_msg>alerta<commit_after>function contactos(){

	this.getContacts = function(){
		alert('ere');
		try{
	    var options = new ContactFindOptions();
	    options.filter = "";
	    options.multiple = true;
	    filter = ["displayName", "name"];
	    navigator.contacts.find(filter, function(){
		    for (var i = 0; i < contacts.length; i++) {
		        alert("Formatted: "  + contacts[i].name.formatted       + "\n" +
		            "Family Name: "  + contacts[i].name.familyName      + "\n" +
		            "Given Name: "   + contacts[i].name.givenName       + "\n" +
		            "Middle Name: "  + contacts[i].name.middleName      + "\n" +
		            "Number: "       + contacts[i].phoneNumbers[0].value + "\n" +
		            "Prefix: "       + contacts[i].name.honorificSuffix);
		    }
	    }, function(){alert('onError!');}, options);
		} catch(e){
			alert(e);
		}
	}
}
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { State, Store } from '@sambego/storybook-state';
import {
  text,
  select,
  boolean,
  number
} from '@storybook/addon-knobs';
import Number from './number.component';
import notes from './notes.md';
import OptionsHelper from '../../../utils/helpers/options-helper';
import { StoryHeader, StoryCode } from '../../../../.storybook/style/storybook-info.styles';

const store = new Store(
  {
    value: ''
  }
);

const setValue = (ev) => {
  action('onChange')(ev);
  store.set({ value: ev.target.value });
};
const percentageRange = {
  range: true,
  min: 0,
  max: 100,
  step: 1
};

storiesOf('Experimental/Number Input', module)
  .add('default', () => {
    const disabled = boolean('disabled', false);
    const readOnly = boolean('readOnly', false);
    const fieldHelp = text('fieldHelp', '');
    const label = text('label', '');
    const labelHelp = label ? text('labelHelp') : undefined;
    const labelInline = label ? boolean('labelInline', false) : undefined;
    const labelWidth = labelInline ? number('labelWidth', 30, percentageRange) : undefined;
    const inputWidth = labelInline ? number('inputWidth', 70, percentageRange) : undefined;
    const labelAlign = labelInline ? select(
      'labelAlign',
      OptionsHelper.alignBinary,
      OptionsHelper.alignBinary[0]
    ) : undefined;
    const onChangeDeferred = boolean('onChangeDeferred', false);
    const deferTimeout = onChangeDeferred ? number('deferTimeout') : undefined;

    return (
      <State store={ store }>
        {state => [
          <Number
            value={ state.value }
            disabled={ disabled }
            readOnly={ readOnly }
            inputWidth={ inputWidth }
            fieldHelp={ fieldHelp }
            label={ label }
            labelHelp={ labelHelp }
            labelInline={ labelInline }
            labelWidth={ labelWidth }
            labelAlign={ labelAlign }
            onChange={ setValue }
            onKeyDown={ action('onKeyDown') }
            onChangeDeferred={ onChangeDeferred ? action('onChangeDeferred') : undefined }
            deferTimeout={ deferTimeout }
          />
        ]}
      </State>
    );
  }, {
    info: {
      text: (

A number widget.

It only allows entering of a whole number with an optional minus sign.

          <StoryHeader>Implementation</StoryHeader>

In your file

          <StoryCode padded>
            {'import Number from "carbon-react/lib/components/number";'}
          </StoryCode>

To render a Number:

          <StoryCode padded>
            {'<Number name="myNumber" />'}
          </StoryCode>

      )
    },
    notes: { markdown: notes }
  });
<commit_msg>small storybook fix<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { State, Store } from '@sambego/storybook-state';
import {
  text,
  select,
  boolean,
  number
} from '@storybook/addon-knobs';
import Number from './number.component';
import notes from './notes.md';
import OptionsHelper from '../../../utils/helpers/options-helper';
import { StoryHeader, StoryCode } from '../../../../.storybook/style/storybook-info.styles';

const store = new Store(
  {
    value: ''
  }
);

const setValue = (ev) => {
  action('onChange')(ev);
  store.set({ value: ev.target.value });
};
const percentageRange = {
  range: true,
  min: 0,
  max: 100,
  step: 1
};

storiesOf('Experimental/Number Input', module)
  .add('default', () => {
    const disabled = boolean('disabled', false);
    const readOnly = boolean('readOnly', false);
    const fieldHelp = text('fieldHelp', '');
    const label = text('label', '');
    const labelHelp = label ? text('labelHelp') : undefined;
    const labelInline = label ? boolean('labelInline', false) : undefined;
    const labelWidth = labelInline ? number('labelWidth', 30, percentageRange) : undefined;
    const inputWidth = labelInline ? number('inputWidth', 70, percentageRange) : undefined;
    const labelAlign = labelInline ? select(
      'labelAlign',
      OptionsHelper.alignBinary,
      OptionsHelper.alignBinary[0]
    ) : undefined;
    const onChangeDeferred = boolean('onChangeDeferred', false);
    const deferTimeout = onChangeDeferred ? number('deferTimeout') : undefined;

    return (
      <State store={ store }>
        {state => (
          <Number
            value={ state.value }
            disabled={ disabled }
            readOnly={ readOnly }
            inputWidth={ inputWidth }
            fieldHelp={ fieldHelp }
            label={ label }
            labelHelp={ labelHelp }
            labelInline={ labelInline }
            labelWidth={ labelWidth }
            labelAlign={ labelAlign }
            onChange={ setValue }
            onKeyDown={ action('onKeyDown') }
            onChangeDeferred={ onChangeDeferred ? action('onChangeDeferred') : undefined }
            deferTimeout={ deferTimeout }
          />
        )}
      </State>
    );
  }, {
    info: {
      text: (

A number widget.

It only allows entering of a whole number with an optional minus sign.

          <StoryHeader>Implementation</StoryHeader>

In your file

          <StoryCode padded>
            {'import Number from "carbon-react/lib/components/number";'}
          </StoryCode>

To render a Number:

          <StoryCode padded>
            {'<Number name="myNumber" />'}
          </StoryCode>

      )
    },
    notes: { markdown: notes }
  });
<|endoftext|>


<commit_before>/**
 * Copyright reelyActive 2016
 * We believe in an open Internet of Things
 */

angular.module('reelyactive.cormorant', [])

  .factory('cormorant', function cormorantFactory($http) {

    var stories = {};

    function extractFromHtml(html) {
      var tagIndex = html.search(/(<script\s*?type\s*?=\s*?"application\/ld\+json">)/);
      if(tagIndex < 0) {
        return null;
      }
      var startIndex = html.indexOf('>', tagIndex) + 1;
      var stopIndex = html.indexOf('</script>', startIndex);
      var jsonString = html.substring(startIndex, stopIndex);

      try {
        json = JSON.parse(jsonString);
      }
      catch(e) {
        console.log(e);
        console.log(jsonString);
        return null;
      }
      return json;
    }

    function getStoryTypes(story) {
      var types = [];

      if(story && story.hasOwnProperty('@graph') &&
         story['@graph'] instanceof Array) {
        for(var cType = 0; cType < story['@graph'].length; cType++) {
          types.push(story['@graph'][cType]['@type']);
        }
      }

      return types;
    }

    function combine(story1, story2) {
      var types1 = getStoryTypes(story1);
      var types2 = getStoryTypes(story2);

      if(types1.length > 0) {
        for(var cType = 0; cType < types2.length; cType++) {
          if(types1.indexOf(types2[cType]) < 0) {
            story1['@graph'].push(story2['@graph'][cType]);
          }
        }
      }

      return story1;
    }

    var get = function(url, callback) {
      if(!url || (typeof url !== 'string')) {
        return callback(null, null);
      }
      if(stories.hasOwnProperty(url)) {
        return callback(stories[url], url);
      }
      $http.defaults.headers.common.Accept = 'application/json, text/plain';
      $http.get(url)
        .success(function(data, status, headers, config) {
          switch(typeof data) {
            case 'string':
              data = extractFromHtml(data);
            case 'object':
              stories[url] = data;
              callback(data, url);
          }
        })
        .error(function(data, status, headers, config) {
          console.log('cormorant: GET ' + url + ' returned status ' + status);
          stories[url] = null;
          callback(null, url);
        });
    };

    var getCombined = function(url1, url2, callback) {
      get(url1, function(story1) {
        if(!story1) {
          return callback(null, url1);
        }
        get(url2, function(story2) {
          if(!story2) {
            return callback(story1, url1);
          }
          var combinedStory = combine(story1, story2);
          stories[url1] = combinedStory;
          callback(combinedStory, url1);
        });
      });
    };

    return {
      getStory: get,
      getCombinedStory: getCombined,
      getStories: function() { return stories; }
    }
  });
<commit_msg>No longer store/overwrite combined story<commit_after>/**
 * Copyright reelyActive 2016
 * We believe in an open Internet of Things
 */

angular.module('reelyactive.cormorant', [])

  .factory('cormorant', function cormorantFactory($http) {

    var stories = {};

    function extractFromHtml(html) {
      var tagIndex = html.search(/(<script\s*?type\s*?=\s*?"application\/ld\+json">)/);
      if(tagIndex < 0) {
        return null;
      }
      var startIndex = html.indexOf('>', tagIndex) + 1;
      var stopIndex = html.indexOf('</script>', startIndex);
      var jsonString = html.substring(startIndex, stopIndex);

      try {
        json = JSON.parse(jsonString);
      }
      catch(e) {
        console.log(e);
        console.log(jsonString);
        return null;
      }
      return json;
    }

    function getStoryTypes(story) {
      var types = [];

      if(story && story.hasOwnProperty('@graph') &&
         story['@graph'] instanceof Array) {
        for(var cType = 0; cType < story['@graph'].length; cType++) {
          types.push(story['@graph'][cType]['@type']);
        }
      }

      return types;
    }

    function combine(story1, story2) {
      var types1 = getStoryTypes(story1);
      var types2 = getStoryTypes(story2);

      if(types1.length > 0) {
        for(var cType = 0; cType < types2.length; cType++) {
          if(types1.indexOf(types2[cType]) < 0) {
            story1['@graph'].push(story2['@graph'][cType]);
          }
        }
      }

      return story1;
    }

    var get = function(url, callback) {
      if(!url || (typeof url !== 'string')) {
        return callback(null, null);
      }
      if(stories.hasOwnProperty(url)) {
        return callback(stories[url], url);
      }
      $http.defaults.headers.common.Accept = 'application/json, text/plain';
      $http.get(url)
        .success(function(data, status, headers, config) {
          switch(typeof data) {
            case 'string':
              data = extractFromHtml(data);
            case 'object':
              stories[url] = data;
              callback(data, url);
          }
        })
        .error(function(data, status, headers, config) {
          console.log('cormorant: GET ' + url + ' returned status ' + status);
          stories[url] = null;
          callback(null, url);
        });
    };

    var getCombined = function(url1, url2, callback) {
      get(url1, function(story1) {
        if(!story1) {
          return callback(null, url1);
        }
        get(url2, function(story2) {
          if(!story2) {
            return callback(story1, url1);
          }
          var combinedStory = combine(story1, story2);
          callback(combinedStory, url1);
        });
      });
    };

    return {
      getStory: get,
      getCombinedStory: getCombined,
      getStories: function() { return stories; }
    }
  });
<|endoftext|>


<commit_before>"use strict";

var currentDate = new Date().getTime();
var countdown = document.getElementById('countdown');

function postEventInProgress(event) {
    countdown.innerHTML = "We are currently competing in " + event.atag + "!";
    countdown.parentElement.style.background="#5aad62";
}

function addCountdown(futureDate) {
    var seconds_left = (futureDate - new Date().getTime()) / 1000;
    var days, hours, minutes, seconds;

    // do some time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    countdown.innerHTML = '' + days +  ' Days ' + hours + ' Hours ' + minutes + ' Minutes ' + seconds + ' Seconds';
}

class event {
    constructor(name, start, end, link) {
        this.name  = name;
        this.start = start;
        this.end   = end;
        this.link  = link;
        this.atag  = '' + name + ''
    }

    post() {
        addCountdown(this.start);
    }
}

/* Main */
var events = [];
var eventPosted = false;

events.push(new event(
                'Hatboro-Horsham',
                new Date('Mar, 3, 2017, 8:00:00 GMT-400').getTime(),
                new Date('Mar, 5, 2017, 8:00:00 GMT-400').getTime(),
                'https://www.thebluealliance.com/event/2017pahat/'
                ));

events.push(new event(
                'Bridgewater-Raritan',
                new Date('Mar, 17, 2017, 8:00:00 GMT-400').getTime(),
                new Date('Mar, 19, 2017, 8:00:00 GMT-400').getTime(),
                'https://www.thebluealliance.com/event/2017njbri'
                ));

//Sort the events array based on start date
events.sort(function(a,b) {return a.start - b.start; });

for(var currentEvent in events) {

    //If the currentEvent in the array hasn't occured yet,
    if(events[currentEvent].start > currentDate) {
        document.getElementById("nextevent").innerHTML = 'Next Event: ' + events[currentEvent].atag + '';
        setInterval(function() { events[currentEvent].post(); }, 1000);
        eventPosted = true;
        break;
    } //If this statement is true, the start of the event has passed

    //If the event is in progress, post it as such
    else if(events[currentEvent].end > currentDate) {
        postEventInProgress(events[currentEvent]);
        eventPosted = true;
        break;
    }
}

if(!eventPosted) {
    document.getElementById("nextevent").innerHTML = 'We have no upcoming events!';
}
<commit_msg>Added new events to the countdown timer<commit_after>"use strict";

var currentDate = new Date().getTime();
var countdown = document.getElementById('countdown');

function postEventInProgress(event) {
    countdown.innerHTML = "We are currently competing in " + event.atag + "!";
    countdown.parentElement.style.background = "#5aad62";
}

function addCountdown(futureDate) {
    var seconds_left = (futureDate - new Date().getTime()) / 1000;
    var days, hours, minutes, seconds;

    // do some time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    countdown.innerHTML = '' + days + ' Days ' + hours + ' Hours ' + minutes + ' Minutes ' + seconds + ' Seconds';
}

class event {
    constructor(name, start, end, link) {
        this.name = name;
        this.start = start;
        this.end = end;
        this.link = link;
        this.atag = '' + name + ''
    }

    post() {
        addCountdown(this.start);
    }
}

/* Main */
var events = [];
var eventPosted = false;

events.push(new event(
    'MAR District Championship',
    new Date('Apr, 5, 2017, 8:00:00 GMT-400').getTime(),
    new Date('Apr, 8, 2017, 18:00:00 GMT-400').getTime(),
    'https://www.thebluealliance.com/event/2017mrcmp'
));

events.push(new event(
    'FIRST Championship (St. Louis)',
    new Date('Apr, 26, 2017, 8:00:00 GMT-400').getTime(),
    new Date('Apr, 29, 2017, 18:00:00 GMT-400').getTime(),
    'https://www.thebluealliance.com/event/2017cmpmo'
));

//Sort the events array based on start date
events.sort(function(a, b) {
    return a.start - b.start;
});

for (var currentEvent in events) {

    //If the currentEvent in the array hasn't occured yet,
    if (events[currentEvent].start > currentDate) {
        document.getElementById("nextevent").innerHTML = 'Next Event: ' + events[currentEvent].atag + '';
        setInterval(function() {
            events[currentEvent].post();
        }, 1000);
        eventPosted = true;
        break;
    } //If this statement is true, the start of the event has passed

    //If the event is in progress, post it as such
    else if (events[currentEvent].end > currentDate) {
        postEventInProgress(events[currentEvent]);
        eventPosted = true;
        break;
    }
}

if (!eventPosted) {
    document.getElementById("nextevent").innerHTML = 'We have no upcoming events!';
}
<|endoftext|>


<commit_before>define(['Format', '../chunk/iso-9660'], function(Format, chunkTypes) {

  'use strict';

  return {
    split: function split(segment, entries) {
      var root = (segment.format.parameters['root-segment'] || '').match(/^\s*(\d+)\s*,\s*(\d+)\s*$/);
      if (!root) {
        return Promise.reject('root-segment parameter must be specified as a pair of decimal numbers');
      }
      var root = segment.getSegment('chunk/');
      if (isNaN(segment.format.parameters['struct-segment'] === '
      function doVolumeDescriptor(n) {
        var descriptorOffset = 2048 * (0x10 + n);
        var descriptorSegment = segment.getSegment('chunk/iso-9660; which=volume-descriptor', descriptorOffset, 2048);
        return descriptorSegment.getStruct().then(function(descriptor) {
          if (!descriptor.hasValidSignature) {
            return Promise.reject('ISO 9660 volume descriptor signature not found');
          }
          entries.add(descriptorSegment);
          switch (descriptor.descriptorType) {
            case 'terminator':
              // i.e. don't call doVolumeDescriptor for the next n
              return;
            case 'volume':
              var formatName = 'recursive/iso-9660';
              var formatParameters = {
                volume: descriptor.isPrimaryVolume ? 'primary' : 'supplementary',
                offset: descriptorOffset + descriptor.body.offsetof_rootDirectory,
                length: descriptor.body.sizeof_rootDirectory,
              };
              if (descriptor.body.blockByteLength !== 2048) {
                formatParameters['block-size'] = descriptor.body.blockByteLength;
              }
              var volumeSegment = segment.getSegment(
                Format(formatName, formatParameters),
                0,
                descriptor.body.blockByteLength * descriptor.body.blockCount);
              entries.add(volumeSegment);
              return doVolumeDescriptor(n + 1);
            default:
              return doVolumeDescriptor(n + 1);
          }
        });
      }
      return doVolumeDescriptor(0);
    },
  };

});
<commit_msg>Update volume.js<commit_after>define(['Format'], function(Format) {

  'use strict';

  const PARTITION_FMT = Format('iso-9660/chunk', {which:'volume-descriptor'});

  return {
    split: function split(segment, entries) {
      var root = (segment.format.parameters['root-segment'] || '').match(/^\s*(\d+)\s*,\s*(\d+)\s*$/);
      if (!root) {
        return Promise.reject('root-segment parameter must be specified as a pair of decimal numbers');
      }
      var partitionOffset = +root[1], partitionLength = +root[2];
      var partitionSegment = segment.getSegment(PARTITION_FMT, partitionOffset, partitionLength);
      entries.add(partitionSegment);
      return partitionSegment.getStruct().then(function(partition) {
        var rootFolder = segment.getSegment(Format('iso-9660/folder', {
          'root-segment':
            (partitionOffset + partition.body.offsetof_rootDirectory)
            + ',' + partition.body.sizeof_rootDirectory,
        }));
        entries.add(rootFolder);
      });
    },
  };

});
<|endoftext|>


<commit_before>var people;
var darknessOpen;

$(document).ready( function(){
  // create tooltips
  $('#Rooms').children().children().tipsy({gravity: 'e', opacity: 1.0});

  // initialize people directory
  people = new People();

  // initially hide all rooms
  $('#Rooms').children().children().fadeOut(0);

  // modal: search
  $('.magnifying-glass').click(function() {
    openDarkness();
    $('.search').animate(
      {top: getTopOf('search') },
      150,
      "swing",
      function() {
        $('.search-box').focus();
        $('.search-box').autocomplete('search');
      });
  });

  // modal: map preferences
  $('.gear').click( function() {
    openDarkness();
    $('.map-preferences').animate( {top: getTopOf('map-preferences') } );
  });

  // to close modals
  $('.darkness').click(closeDarkness);

  // initial animation
  $('.search-box').focus();
  $('.search').animate({top: getTopOf('search') }, 1000);
  $('.darkness').fadeIn(700);
  $('.search-btn').one('click', search);
  darknessOpen = true;

  // autocomplete functions
  $( '.search-box' ).autocomplete({
    minLength: 0,
    source: function(request, response) {
      if (request.term == '') {
        response([]);
        return;
      }
      var results = matchAutocomplete(request.term);
      response(results);
    },
    focus: function( event, ui ) {
      return false;
    },
    select: function( event, ui ) {
      $( '.search-box' ).val( ui.item.label );
      $('.search-btn').click();
      return true;
    },
    messages: {
      noResults: '',
      results: function() {}
    }
  })
  .autocomplete({appendTo: '.autocomplete-list'})
  .autocomplete( 'instance' )._renderItem = function( ul, item ) {
    return $( '
' )
      .append( '' + item.label + '
' + item.desc + '' )
      .appendTo( ul );
  };
});

function contains(s1, s2) {
  return s1.toLowerCase().indexOf(s2.toLowerCase()) === 0;
};

function matchSearch(s) {
  var results = match(s); // search for everything explicitly
  return results;
};

function matchAutocomplete(s) {
  var categoryResults = [];
  // search years, lounges, sections
  var yearList = people.getYearList();
  for (var i = 0; i < yearList.length; i++) {
    if (contains(yearList[i], s)) {
      categoryResults.push({
        value: yearList[i],
        label: yearList[i],
        desc: 'Year'
      });
    }
  }
  var loungeList = people.getLoungeList();
  for (var i = 0; i < loungeList.length; i++) {
    if (contains(loungeList[i], s)) {
      categoryResults.push({
        value: loungeList[i],
        label: loungeList[i],
        desc: 'Lounge'
      });
    }
  }
  var sectionList = people.getSectionList();
  for (var i = 0; i < sectionList.length; i++) {
    if (contains(sectionList[i], s)) {
      categoryResults.push({
        value: sectionList[i],
        label: sectionList[i],
        desc: 'Section'
      });
    }
  }
  var typeList = people.getTypeList();
  for (var i = 0; i < typeList.length; i++) {
    if (contains(typeList[i], s)) {
      categoryResults.push({
        value: typeList[i],
        label: typeList[i],
        desc: 'Type'
      });
    }
  }
  var matched = match(s, ['lname', 'fname', 'title', 'kerb', 'room', 'fullname', 'email']);
  var results = [];
  for (var i = 0; i < matched.length; i++) {
    var m = matched[i];
    results.push({
      value: people.getKerb(m),
      label: people.getFName(m) + ' ' + people.getLName(m),
      desc: people.getKerb(m) + ' (' + people.getRoom(m) + ')'
    });
  }
  return categoryResults.concat(results);
};

function match(s, things) {
  things = things || ['lname', 'fname', 'title', 'kerb', 'room', 'year', 'fullname', 'lounge', 'section', 'type', 'email'];
  var results = [];
  for (var i = 0; i < people.numPeople(); i++) {
    for (var j = 0; j < things.length; j++) {
      var str = people.get(i, things[j]);
      if (str !== "" && contains(str, s)) {
        results.push(i);
        break;
      }
    }
  }
  return results;
};

function onSearchBoxClick() {
  if (darknessOpen) {
    $('.search-box').autocomplete('search');
  }
};

function openDarkness() {
  $('.modal').show();
  $('.search-btn').one('click', search);
  $('.darkness').fadeIn(300);
  darknessOpen = true;
  $('.search-box').autocomplete('enable');
};

function closeDarkness() {
  $('.search-box').autocomplete('close');
  $('.darkness').fadeOut(300);
  $('.search').animate({top: '-60px'}, 150);
  $('.map-preferences').animate({top: '-300px'}, 150);
  darknessOpen = false;
  $('.search-box').autocomplete('disable');
};

function getTopOf(modal) {
  centerOfMap = $('.nav-region').height() + $('.map-region').height() / 2;
  if (modal == 'search') {
    searchHeight = $('.search-box').outerHeight();
    topPx = centerOfMap - (searchHeight/2);
  }
  else if (modal == 'map-preferences') {
    mapPreferencesHeight = $('.map-preferences').outerHeight();
    topPx = centerOfMap - (mapPreferencesHeight/2);
  }
  return topPx;
};

function userHasTyped(input) {
  // show everything
  if (input === '') {
    $('#Facilities, #Dining, #Firestairs, #Elevators, #Lounges').fadeIn(300);
    $('.btn-facilities, .btn-dining, .btn-firestairs, .btn-elevators, .btn-lounges').addClass('active');
  }
};

function handleKeyDown(key) {
  if (key.keyCode == 13) {
    $('.search-btn').click();
  } else if (key.keyCode == 27) {
    closeDarkness();
  }
};

function search(event, input) {
  if (!darknessOpen) {
    return;
  }
  input = input || $('.search-box').val();
  var results = matchSearch(input);

  // clear previous results and search box
  ClearDownload();
  $('.results-table tbody').empty();
  $(".results-explanation").html("No results.");
  $('#Rooms').children().children().attr('title', '');
  $('#Rooms').children().children().fadeOut(300);
  $('#Facilities, #Dining, #Firestairs, #Laundry, #Kitchens, #Lounges').fadeOut(300);
  $('.btn-facilities, .btn-dining, .btn-firestairs, .btn-laundry, .btn-kitchens, .btn-lounges').removeClass('active');
  closeDarkness();

  if (input != '') { // return none instead of all
    var numberOfResults = results.length;
    for (var i = 0; i < numberOfResults; i++) {
      display(results[i]);
    }
    $(".results-explanation").html(numberOfResults + " for \"" + input + "\"");
    PrepareDownload(input);
  }
};

function display(result) {
  var role = '';
  if (people.getYear(result) != '') {
    role = ' \'' + people.getYear(result).slice(-2);
  }
  else {
    // TODO: replace with Role field in people
    var room = people.getRoom(result);
    if (room == '365' || room == '772') {
      role = ' (Housemaster)';
    }
    else if (room == '580') {
      role = ' (RLAD)';
    }
    // hack for apts currently for res. scholars
    else if (room == '436' ||
             room == '480' ||
             room == '528' ||
             room == '1080') {
      role = ' (Residential Scholar)';
    }
    else {
      role = ' (GRT)';
    }
  }
  var room = people.getRoom(result);
  var fname = people.getFName(result);
  var lname = people.getLName(result);
  var kerb = people.getKerb(result);
  $('.results-table tbody').append(
    '
 '+fname+'	 '+lname+'	 '+kerb+'	 '+room+'
 '
  );
  $('#r' + room).fadeIn(300);

    // set onclicks for all rooms
  $('#r' + room).attr('onclick', 'search(undefined, \"' + room + '\");');
  $('#r' + room).attr('style', 'cursor: pointer;');

  // set titles for tooltips
  var currAttr = $('#r' + room).attr('title');
  if (!currAttr) {
    $('#r' + room).attr('title', 'Room ' + room + ', ' + fname + ' ' + lname);
  } else {
    $('#r' + room).attr('title', currAttr + ', ' + fname + ' ' + lname);
  }
};

function PrepareDownload(searchTerm) {
    // container
    $('.results-download').show();

    var tbody = $('.results-table tbody');
    var csv = '';

    tbody.find('tr').each(function() {
      $(this).find('td').each(function() {
        csv += $(this).text() + ', ';
      });
      csv += '\n';
    });

    $('.download-link').attr('href', 'data:application/vnd.ms-excel,' + encodeURIComponent(csv));
    $('.download-link').attr('download', 'Simmons Directory results for ' + searchTerm + '.csv');
};

function ClearDownload() {
    $('.download-link').attr('href', '');
    $('.download-link').attr('download', '');
    $('.results-download').hide();
};<commit_msg>made arrow keys + enter work<commit_after>var people;
var darknessOpen;

$(document).ready( function(){
  // create tooltips
  $('#Rooms').children().children().tipsy({gravity: 'e', opacity: 1.0});

  // initialize people directory
  people = new People();

  // initially hide all rooms
  $('#Rooms').children().children().fadeOut(0);

  // modal: search
  $('.magnifying-glass').click(function() {
    openDarkness();
    $('.search').animate(
      {top: getTopOf('search') },
      150,
      "swing",
      function() {
        $('.search-box').focus();
        $('.search-box').autocomplete('search');
      });
  });

  // modal: map preferences
  $('.gear').click( function() {
    openDarkness();
    $('.map-preferences').animate( {top: getTopOf('map-preferences') } );
  });

  // to close modals
  $('.darkness').click(closeDarkness);

  // initial animation
  $('.search-box').focus();
  $('.search').animate({top: getTopOf('search') }, 1000);
  $('.darkness').fadeIn(700);
  $('.search-btn').one('click', search);
  darknessOpen = true;

  // autocomplete functions
  $( '.search-box' ).autocomplete({
    minLength: 0,
    source: function(request, response) {
      if (request.term == '') {
        response([]);
        return;
      }
      var results = matchAutocomplete(request.term);
      response(results);
    },
    select: function( event, ui ) {
      $( '.search-box' ).val( ui.item.label );
      $('.search-btn').click();
      return true;
    },
    messages: {
      noResults: '',
      results: function() {}
    },
    change: function(event, ui) {
      if (ui.item) {
        console.log(ui.item.value);
      } else {
        console.log('nothing');
      }
    }
  })
  .autocomplete({appendTo: '.autocomplete-list'})
  .autocomplete( 'instance' )._renderItem = function( ul, item ) {
    return $( '
' )
      .append( '' + item.label + '
' + item.desc + '' )
      .appendTo( ul );
  };
});

function contains(s1, s2) {
  return s1.toLowerCase().indexOf(s2.toLowerCase()) === 0;
};

function matchSearch(s) {
  var results = match(s); // search for everything explicitly
  return results;
};

function matchAutocomplete(s) {
  var categoryResults = [];
  // search years, lounges, sections
  var yearList = people.getYearList();
  for (var i = 0; i < yearList.length; i++) {
    if (contains(yearList[i], s)) {
      categoryResults.push({
        value: yearList[i],
        label: yearList[i],
        desc: 'Year'
      });
    }
  }
  var loungeList = people.getLoungeList();
  for (var i = 0; i < loungeList.length; i++) {
    if (contains(loungeList[i], s)) {
      categoryResults.push({
        value: loungeList[i],
        label: loungeList[i],
        desc: 'Lounge'
      });
    }
  }
  var sectionList = people.getSectionList();
  for (var i = 0; i < sectionList.length; i++) {
    if (contains(sectionList[i], s)) {
      categoryResults.push({
        value: sectionList[i],
        label: sectionList[i],
        desc: 'Section'
      });
    }
  }
  var typeList = people.getTypeList();
  for (var i = 0; i < typeList.length; i++) {
    if (contains(typeList[i], s)) {
      categoryResults.push({
        value: typeList[i],
        label: typeList[i],
        desc: 'Type'
      });
    }
  }
  var matched = match(s, ['lname', 'fname', 'title', 'kerb', 'room', 'fullname', 'email']);
  var results = [];
  for (var i = 0; i < matched.length; i++) {
    var m = matched[i];
    results.push({
      value: people.getKerb(m),
      label: people.getFName(m) + ' ' + people.getLName(m),
      desc: people.getKerb(m) + ' (' + people.getRoom(m) + ')'
    });
  }
  return categoryResults.concat(results);
};

function match(s, things) {
  things = things || ['lname', 'fname', 'title', 'kerb', 'room', 'year', 'fullname', 'lounge', 'section', 'type', 'email'];
  var results = [];
  for (var i = 0; i < people.numPeople(); i++) {
    for (var j = 0; j < things.length; j++) {
      var str = people.get(i, things[j]);
      if (str !== "" && contains(str, s)) {
        results.push(i);
        break;
      }
    }
  }
  return results;
};

function onSearchBoxClick() {
  if (darknessOpen) {
    $('.search-box').autocomplete('search');
  }
};

function openDarkness() {
  $('.modal').show();
  $('.search-btn').one('click', search);
  $('.darkness').fadeIn(300);
  darknessOpen = true;
  $('.search-box').autocomplete('enable');
};

function closeDarkness() {
  $('.search-box').autocomplete('close');
  $('.darkness').fadeOut(300);
  $('.search').animate({top: '-60px'}, 150);
  $('.map-preferences').animate({top: '-300px'}, 150);
  darknessOpen = false;
  $('.search-box').autocomplete('disable');
};

function getTopOf(modal) {
  centerOfMap = $('.nav-region').height() + $('.map-region').height() / 2;
  if (modal == 'search') {
    searchHeight = $('.search-box').outerHeight();
    topPx = centerOfMap - (searchHeight/2);
  }
  else if (modal == 'map-preferences') {
    mapPreferencesHeight = $('.map-preferences').outerHeight();
    topPx = centerOfMap - (mapPreferencesHeight/2);
  }
  return topPx;
};

function userHasTyped(input) {
  // show everything
  if (input === '') {
    $('#Facilities, #Dining, #Firestairs, #Elevators, #Lounges').fadeIn(300);
    $('.btn-facilities, .btn-dining, .btn-firestairs, .btn-elevators, .btn-lounges').addClass('active');
  }
};

function handleKeyDown(key) {
  if (key.keyCode == 13) {
    $('.search-btn').click();
  } else if (key.keyCode == 27) {
    closeDarkness();
  }
};

function search(event, input) {
  if (!darknessOpen) {
    return;
  }
  input = input || $('.search-box').val();
  var results = matchSearch(input);

  // clear previous results and search box
  ClearDownload();
  $('.results-table tbody').empty();
  $(".results-explanation").html("No results.");
  $('#Rooms').children().children().attr('title', '');
  $('#Rooms').children().children().fadeOut(300);
  $('#Facilities, #Dining, #Firestairs, #Laundry, #Kitchens, #Lounges').fadeOut(300);
  $('.btn-facilities, .btn-dining, .btn-firestairs, .btn-laundry, .btn-kitchens, .btn-lounges').removeClass('active');
  closeDarkness();

  if (input != '') { // return none instead of all
    var numberOfResults = results.length;
    for (var i = 0; i < numberOfResults; i++) {
      display(results[i]);
    }
    $(".results-explanation").html(numberOfResults + " for \"" + input + "\"");
    PrepareDownload(input);
  }
};

function display(result) {
  var role = '';
  if (people.getYear(result) != '') {
    role = ' \'' + people.getYear(result).slice(-2);
  }
  else {
    // TODO: replace with Role field in people
    var room = people.getRoom(result);
    if (room == '365' || room == '772') {
      role = ' (Housemaster)';
    }
    else if (room == '580') {
      role = ' (RLAD)';
    }
    // hack for apts currently for res. scholars
    else if (room == '436' ||
             room == '480' ||
             room == '528' ||
             room == '1080') {
      role = ' (Residential Scholar)';
    }
    else {
      role = ' (GRT)';
    }
  }
  var room = people.getRoom(result);
  var fname = people.getFName(result);
  var lname = people.getLName(result);
  var kerb = people.getKerb(result);
  $('.results-table tbody').append(
    '
 '+fname+'	 '+lname+'	 '+kerb+'	 '+room+'
 '
  );
  $('#r' + room).fadeIn(300);

    // set onclicks for all rooms
  $('#r' + room).attr('onclick', 'search(undefined, \"' + room + '\");');
  $('#r' + room).attr('style', 'cursor: pointer;');

  // set titles for tooltips
  var currAttr = $('#r' + room).attr('title');
  if (!currAttr) {
    $('#r' + room).attr('title', 'Room ' + room + ', ' + fname + ' ' + lname);
  } else {
    $('#r' + room).attr('title', currAttr + ', ' + fname + ' ' + lname);
  }
};

function PrepareDownload(searchTerm) {
    // container
    $('.results-download').show();

    var tbody = $('.results-table tbody');
    var csv = '';

    tbody.find('tr').each(function() {
      $(this).find('td').each(function() {
        csv += $(this).text() + ', ';
      });
      csv += '\n';
    });

    $('.download-link').attr('href', 'data:application/vnd.ms-excel,' + encodeURIComponent(csv));
    $('.download-link').attr('download', 'Simmons Directory results for ' + searchTerm + '.csv');
};

function ClearDownload() {
    $('.download-link').attr('href', '');
    $('.download-link').attr('download', '');
    $('.results-download').hide();
};<|endoftext|>