<commit_before>/////////////////////////////////
//// GORDON'S ADDITIONS /////////
/////////////////////////////////

var PIPETTES = { // global variable for use in setPipetteContainers
  "Center": false, // remembers which pipette is assigned to which axis
  "Left": false
}

function setPipetteNames(inputJSON){ // sets the names of the pipettes in the containers menu

  PIPETTES = { "Center": false, "Left": false }; // reset PIPETTES variable

  for(var pipette in inputJSON.head){ // loop through head items (pipettes)
    var channel = "";

    if(inputJSON.head[pipette].axis == "a") { // A is center
      channel = "Center";
    } else if(inputJSON.head[pipette].axis == "b") { // B is left
      channel = "Left";
    }

//    var channel = inputJSON.head[pipette].axis; // find the channel that this pipette is attached to
    PIPETTES[channel] = pipette;
  }

  for(var channel in PIPETTES){ // go through and set each channel
    var divName = "pipette-" + channel;
    var pip_divs = document.getElementsByClassName(divName);

    if(!PIPETTES[channel]){
      for(var i=0; i<pip_divs.length;i++){
        pip_divs[i].innerHTML = "N/A"; // set name to channel if the variable in PIPETTES is unset
      }
    } else {
      var pipette = PIPETTES[channel];

      for(var i=0; i<pip_divs.length;i++){
        if(pip_divs[i].classList.contains("shortform")){
          pip_divs[i].innerHTML = channel + ": " + pipette; // no real difference between shortform and regular since changing to left/center
        } else {
          pip_divs[i].innerHTML = channel + ": " + pipette; // set the text to the new name
        }
      }
    }
  }
}

function setPipetteContainers(inputJSON, pipettes){ // blanks out containers based on their use with each pipette

  var containerUsage = {};

  for(var location in pipettes){
    if(pipettes[location]){
      containerUsage[pipettes[location]] = {}; // if pipette isn't null, set containerUsage to an empty hash for that pipette
    }
  }

  var headItems = inputJSON.head; // hash of pipettes
  var instructions = inputJSON.instructions; // list of instructions

  // populages containerUsage with the containers each pipette uses
  for(var i=0; i<instructions.length; i++){

    var tool = instructions[i].tool;
    var groups = instructions[i].groups;

    //add trash, tiprack to each pipette
    var trash = ""
    if ("container" in headItems[tool]["trash-container"]){
      trash = headItems[tool]["trash-container"]["container"];
    }else{
      trash = headItems[tool]["trash-container"][0];
    }

    containerUsage[tool][trash] = true; //add trash container

    var tipracks = headItems[tool]["tip-racks"];
    for(var j=0; j<tipracks.length; j++){ //add all tipracks
      if ("container" in tipracks[0]){
        containerUsage[tool][tipracks[j].container] = true;
      }else{
        containerUsage[tool][tipracks[j]] = true;
      }
    }

    //go through to add each liquid container
    for(var j=0; j<groups.length; j++){
      var move = groups[j];

      for(var key in move){

        var action = move[key];

        // go through each instruction type and fish around for the "container" section
        if(key == "transfer"){
          for(var k=0; k<action.length; k++){
            containerUsage[tool][action[k].from.container] = true; // container exists for this pipette
            containerUsage[tool][action[k].to.container] = true;
          }

        } else if(key == "distribute"){
          containerUsage[tool][action.from.container] = true;

          for(var k=0; k<action.to.length; k++){
            containerUsage[tool][action.to[k].container] = true;
          }

        } else if(key == "consolidate"){
          for(var k=0; k<action.from.length; k++){
            containerUsage[tool][action.from[k].container] = true;
          }
          containerUsage[tool][action.to.container] = true;

        } else if(key == "mix"){
          for(var k=0; k<action.length; k++){
            containerUsage[tool][action[k].container] = true;
          }
        }
      }
    }
  }

  var containers = document.getElementById("containerMenu").children[0].children; //get the row elements corresponding to the containers

  // go through containers displayed and cut out the "save" buttons accordingly
  for(var i=0; i<containers.length; i++){

    var rowBlocks = containers[i].children;

    rowBlocks[1].children[0].style.display = 'inline-block'; //make both visible by default
    rowBlocks[2].children[0].style.display = 'inline-block';

    var name = rowBlocks[0].innerHTML;

    if(pipettes["Left"] != false){ // pipette exists
      if(!(name in containerUsage[pipettes["Left"]])) { // containerUsage does not contain this key for this pipette
        rowBlocks[1].children[0].style.display = 'none';
      }
    } else {
      rowBlocks[1].children[0].style.display = 'none';
    }

    if(pipettes["Center"] != false){ // pipette exists
      if(!(name in containerUsage[pipettes["Center"]])) { // containerUsage does not contain this key for this pipette
        rowBlocks[2].children[0].style.display = 'none';
      }
    } else {
      rowBlocks[2].children[0].style.display = 'none';
    }

  }

}

function console_log(string){ // makeshift "console" - console div is currently commented out in index.html
  var console = document.getElementById("console");
  console.innerHTML += string + "
";
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function setupPlateInterface() {
  setupDragBox();
  //loadDefaultContainers();
}

window.addEventListener('load',setupPlateInterface);

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function setupDragBox(){

  function preventD(e) {
    e.preventDefault();
  }

  var dragDiv = document.getElementById('dragDiv');

  window.addEventListener('dragover', function(e){
    dragDiv.classList.add('tron-blue');
    e.preventDefault();
  }, false);
  window.addEventListener('dragenter', function(e){
    dragDiv.classList.add('tron-blue');
    e.preventDefault();
  }, false);
  window.addEventListener('dragleave', function(e){
    dragDiv.classList.remove('tron-blue');
    e.preventDefault();
  }, false);

  window.addEventListener('drop', function(e){
    e.preventDefault();
    dragDiv.classList.remove('tron-blue');
    loadFile(e);
  }, false);

  window.addEventListener('dragover', preventD, false);
  window.addEventListener('dragenter', preventD, false);
  window.addEventListener('dragleave', preventD, false);
  window.addEventListener('drop', preventD, false);
}

////////
////////
////////

var CURRENT_PROTOCOL = undefined;
var _FILENAME = undefined;
var TIPRACKS = undefined // tip rack origin is just first tiprack in list

function loadFile(e) {
  var files = e.dataTransfer.files; // FileList object.

  if(files[0]){
    var _F = files[0];
    TIPRACKS = {'a':[],'b':[]};
    _FILENAME = _F.name;

    document.getElementById('fileName').innerHTML = _FILENAME.split('.')[0];

    var reader = new FileReader();

    reader.onload = function(e){

      var tempProtocol = undefined;

      try{
        var tempProtocol = JSON.parse(reader.result);
      }
      catch(err){
        tempProtocol = undefined;
      }

      if(tempProtocol) {

        setPipetteNames(tempProtocol); // set the names of the pipettes in the container table
        //if we find the info generate html elements
        if(tempProtocol.deck && tempProtocol.head && tempProtocol.instructions && tempProtocol.ingredients) {

          document.getElementById('runButton').disabled = false;
          document.getElementById('runButton').classList.add('tron-red');

          CURRENT_PROTOCOL = tempProtocol;
          for (var k in tempProtocol.head){
            console.log('the k: ',k);
            console.log('the head:')
            console.log(tempProtocol.head)
            ax = tempProtocol.head[k].axis;
            if (tempProtocol.head[k]['tip-racks']){
              console.log("there be tip-racks: "+tempProtocol.head[k]['tip-racks']);
              if (tempProtocol.head[k]['tip-racks'].length > 0){
                for (var n in tempProtocol.head[k]['tip-racks']){
                  console.log('tip-rack['+n+': '+tempProtocol.head[k]['tip-racks'][n])
                  if ("container" in tempProtocol.head[k]['tip-racks'][n]){
                    TIPRACKS[ax].push(tempProtocol.head[k]['tip-racks'][n].container)
                  }else{
                    TIPRACKS[ax].push(tempProtocol.head[k]['tip-racks'][n])
                  }
                }
                console.log("TIPRACKS[",ax,"] = ",TIPRACKS[ax]);
              }
            }

          }
          show_robot_new_info();
          configureHead(tempProtocol.head)

          document.getElementById('runButton').removeEventListener('click',createAndSend);
          document.getElementById('runButton').addEventListener('click',createAndSend);

          if(tempProtocol.info){
            document.getElementById('infoName').innerHTML= "File Name: "+ tempProtocol.info.name;
            document.getElementById('infoDate').innerHTML= "Date Created: "+ tempProtocol.info['create-date'];
            document.getElementById('infoVersion').innerHTML= "Version: "+ tempProtocol.info.version;
            document.getElementById('infoDesc').innerHTML= "Description: " + tempProtocol.info.description;
            document.getElementById('infoRun').innerHTML= "Run Notes: " + tempProtocol.info['run-notes'];

          }else if(!tempProtocol.info){
            document.getElementById('infoDesc').innerHTML="";
          }
        }
      }
      else { // if the files messed up, current_protocol is undefined
        CURRENT_PROTOCOL = undefined;
      }
    }
    reader.readAsText(_F);
  }
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function show_robot_new_info() {

  // first, tell it the new containers we're using in this protocol

  var socketMsg = {
    'type' : 'createDeck',
    'data' : CURRENT_PROTOCOL.deck
  }

  sendMessage(socketMsg);

}

function configureHead(data) {
  var socketMsg = {
    'type' : 'configureHead',
    'data' : data
  }

  sendMessage(socketMsg);
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function createAndSend () {
  if(CURRENT_PROTOCOL) {

    var robotProtocol;
    var throwError = false;

    for(var toolname in CURRENT_PROTOCOL.head) {
      var thisAxis = CURRENT_PROTOCOL.head[toolname].axis;
      var calibratedVolume = robotState.pipettes[thisAxis].volume;
      if(calibratedVolume>0) {
        CURRENT_PROTOCOL.head[toolname].volume = calibratedVolume;
      }
      if(isNaN(CURRENT_PROTOCOL.head[toolname].volume) || CURRENT_PROTOCOL.head[toolname].volume<=0) {
        throwError = true;
      }
    }

    if(throwError) {
      alert('Please calibrate pipette volumes before running');
    }
    else {

      try {
        robotProtocol = createRobotProtocol(CURRENT_PROTOCOL);
      }
      catch (error) {
        console.log(error);
        alert(error);
      }

      if(robotProtocol) {

        var d = new Date();
        var dateString = '';

        dateString += d.getDate();
        dateString += '-';
        dateString += d.getMonth();
        dateString += '-';
        dateString += d.getFullYear();
        dateString += '-';
        dateString += d.getHours();
        dateString += ':';
        dateString += d.getMinutes();
        dateString += ':';
        dateString += d.getSeconds();

        var savefilename = _FILENAME.split('.')[0] + '-' + dateString + '.json';

        var blob = new Blob([JSON.stringify({
          'time' : dateString,
          'protocol' : CURRENT_PROTOCOL,
          'executable' : robotProtocol
        },undefined,2)], {type: "text/json;charset=utf-8"});

        var shouldSave = confirm('File processed. Save it to disk?');

        if(shouldSave) saveAs(blob, savefilename);

        var jobMsg = {
          'type' : 'instructions',
          'data' : robotProtocol
        }

        var shouldRun = confirm('Send file to be run?');

        if(shouldRun) {
          timeSentJob = new Date().getTime();
          sendMessage(jobMsg);
        }
        else {
          var shouldInfinity = confirm('Send file to be run FOR INFINITY?!?!?!?!?!');
          if(shouldInfinity) {
            jobMsg.type = 'infinity';
            sendMessage(jobMsg);
          }
          else {
            timeSentJob = undefined;
          }
        }
      }
    }
  }
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function loadDefaultContainers() {

  function onContainers () {
    try {
      var blob = JSON.parse(this.responseText);
      var newContainers = blob.containers;
      console.log('newContainers...');
      console.log(newContainers);
      if (newContainers) {
        saveContainers(newContainers);
      }
    }
    catch(error) {
      console.log(error);
    }
  }

    var containersFilepath = './data/containers.json';

  getAJAX(containersFilepath,onContainers);
}

////////
////////
////////

var labware_from_db  = {};

function saveContainers(newContainers) {
  for(var n in newContainers) {
    console.log('newContainer n = '+n);
    var cont = newContainers[n];
    var stringedCont = undefined;
    try {
      stringedCont = JSON.stringify(cont);
      console.log('stringedCont');
      console.log(stringedCont)
    }
    catch (error) {
      //
    }
    if(cont.locations && stringedCont) {
      console.log('saving cont '+cont+' to labware_from_db');
      labware_from_db[n] = stringedCont;
    }
  }
}

////////
////////
////////

function getAJAX(filepath,callback) {
  var oReq = new XMLHttpRequest();
  oReq.onload = callback;
  oReq.open("get", filepath, true);
  oReq.send();
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////<commit_msg>dealing with json objects-->arrays<commit_after>/////////////////////////////////
//// GORDON'S ADDITIONS /////////
/////////////////////////////////

var PIPETTES = { // global variable for use in setPipetteContainers
  "Center": false, // remembers which pipette is assigned to which axis
  "Left": false
}

function setPipetteNames(inputJSON){ // sets the names of the pipettes in the containers menu

  PIPETTES = { "Center": false, "Left": false }; // reset PIPETTES variable

  for(var pipette in inputJSON.head){ // loop through head items (pipettes)
    var channel = "";

    if(inputJSON.head[pipette].axis == "a") { // A is center
      channel = "Center";
    } else if(inputJSON.head[pipette].axis == "b") { // B is left
      channel = "Left";
    }

//    var channel = inputJSON.head[pipette].axis; // find the channel that this pipette is attached to
    PIPETTES[channel] = pipette;
  }

  for(var channel in PIPETTES){ // go through and set each channel
    var divName = "pipette-" + channel;
    var pip_divs = document.getElementsByClassName(divName);

    if(!PIPETTES[channel]){
      for(var i=0; i<pip_divs.length;i++){
        pip_divs[i].innerHTML = "N/A"; // set name to channel if the variable in PIPETTES is unset
      }
    } else {
      var pipette = PIPETTES[channel];

      for(var i=0; i<pip_divs.length;i++){
        if(pip_divs[i].classList.contains("shortform")){
          pip_divs[i].innerHTML = channel + ": " + pipette; // no real difference between shortform and regular since changing to left/center
        } else {
          pip_divs[i].innerHTML = channel + ": " + pipette; // set the text to the new name
        }
      }
    }
  }
}

function setPipetteContainers(inputJSON, pipettes){ // blanks out containers based on their use with each pipette

  var containerUsage = {};

  for(var location in pipettes){
    if(pipettes[location]){
      containerUsage[pipettes[location]] = {}; // if pipette isn't null, set containerUsage to an empty hash for that pipette
    }
  }

  var headItems = inputJSON.head; // hash of pipettes
  var instructions = inputJSON.instructions; // list of instructions

  // populages containerUsage with the containers each pipette uses
  for(var i=0; i<instructions.length; i++){

    var tool = instructions[i].tool;
    var groups = instructions[i].groups;

    //add trash, tiprack to each pipette
    var trash = ""
    if (typeof headItems[tool]["trash-container"] === 'string'){
      trash = headItems[tool]["trash-container"][0];
    }else{
      trash = headItems[tool]["trash-container"].container;
    }

    containerUsage[tool][trash] = true; //add trash container

    var tipracks = headItems[tool]["tip-racks"];
    for(var j=0; j<tipracks.length; j++){ //add all tipracks
      if (typeof tipracks[0] == 'string'){
        containerUsage[tool][tipracks[j]] = true;
      }else{
        containerUsage[tool][tipracks[j].container] = true;
      }
    }

    //go through to add each liquid container
    for(var j=0; j<groups.length; j++){
      var move = groups[j];

      for(var key in move){

        var action = move[key];

        // go through each instruction type and fish around for the "container" section
        if(key == "transfer"){
          for(var k=0; k<action.length; k++){
            containerUsage[tool][action[k].from.container] = true; // container exists for this pipette
            containerUsage[tool][action[k].to.container] = true;
          }

        } else if(key == "distribute"){
          containerUsage[tool][action.from.container] = true;

          for(var k=0; k<action.to.length; k++){
            containerUsage[tool][action.to[k].container] = true;
          }

        } else if(key == "consolidate"){
          for(var k=0; k<action.from.length; k++){
            containerUsage[tool][action.from[k].container] = true;
          }
          containerUsage[tool][action.to.container] = true;

        } else if(key == "mix"){
          for(var k=0; k<action.length; k++){
            containerUsage[tool][action[k].container] = true;
          }
        }
      }
    }
  }

  var containers = document.getElementById("containerMenu").children[0].children; //get the row elements corresponding to the containers

  // go through containers displayed and cut out the "save" buttons accordingly
  for(var i=0; i<containers.length; i++){

    var rowBlocks = containers[i].children;

    rowBlocks[1].children[0].style.display = 'inline-block'; //make both visible by default
    rowBlocks[2].children[0].style.display = 'inline-block';

    var name = rowBlocks[0].innerHTML;

    if(pipettes["Left"] != false){ // pipette exists
      if(!(name in containerUsage[pipettes["Left"]])) { // containerUsage does not contain this key for this pipette
        rowBlocks[1].children[0].style.display = 'none';
      }
    } else {
      rowBlocks[1].children[0].style.display = 'none';
    }

    if(pipettes["Center"] != false){ // pipette exists
      if(!(name in containerUsage[pipettes["Center"]])) { // containerUsage does not contain this key for this pipette
        rowBlocks[2].children[0].style.display = 'none';
      }
    } else {
      rowBlocks[2].children[0].style.display = 'none';
    }

  }

}

function console_log(string){ // makeshift "console" - console div is currently commented out in index.html
  var console = document.getElementById("console");
  console.innerHTML += string + "
";
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function setupPlateInterface() {
  setupDragBox();
  //loadDefaultContainers();
}

window.addEventListener('load',setupPlateInterface);

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function setupDragBox(){

  function preventD(e) {
    e.preventDefault();
  }

  var dragDiv = document.getElementById('dragDiv');

  window.addEventListener('dragover', function(e){
    dragDiv.classList.add('tron-blue');
    e.preventDefault();
  }, false);
  window.addEventListener('dragenter', function(e){
    dragDiv.classList.add('tron-blue');
    e.preventDefault();
  }, false);
  window.addEventListener('dragleave', function(e){
    dragDiv.classList.remove('tron-blue');
    e.preventDefault();
  }, false);

  window.addEventListener('drop', function(e){
    e.preventDefault();
    dragDiv.classList.remove('tron-blue');
    loadFile(e);
  }, false);

  window.addEventListener('dragover', preventD, false);
  window.addEventListener('dragenter', preventD, false);
  window.addEventListener('dragleave', preventD, false);
  window.addEventListener('drop', preventD, false);
}

////////
////////
////////

var CURRENT_PROTOCOL = undefined;
var _FILENAME = undefined;
var TIPRACKS = undefined // tip rack origin is just first tiprack in list

function loadFile(e) {
  var files = e.dataTransfer.files; // FileList object.

  if(files[0]){
    var _F = files[0];
    TIPRACKS = {'a':[],'b':[]};
    _FILENAME = _F.name;

    document.getElementById('fileName').innerHTML = _FILENAME.split('.')[0];

    var reader = new FileReader();

    reader.onload = function(e){

      var tempProtocol = undefined;

      try{
        var tempProtocol = JSON.parse(reader.result);
      }
      catch(err){
        tempProtocol = undefined;
      }

      if(tempProtocol) {

        setPipetteNames(tempProtocol); // set the names of the pipettes in the container table
        //if we find the info generate html elements
        if(tempProtocol.deck && tempProtocol.head && tempProtocol.instructions && tempProtocol.ingredients) {

          document.getElementById('runButton').disabled = false;
          document.getElementById('runButton').classList.add('tron-red');

          CURRENT_PROTOCOL = tempProtocol;
          for (var k in tempProtocol.head){
            console.log('the k: ',k);
            console.log('the head:')
            console.log(tempProtocol.head)
            ax = tempProtocol.head[k].axis;
            if (tempProtocol.head[k]['tip-racks']){
              console.log("there be tip-racks: "+tempProtocol.head[k]['tip-racks']);
              if (tempProtocol.head[k]['tip-racks'].length > 0){
                for (var n in tempProtocol.head[k]['tip-racks']){
                  console.log('tip-rack['+n+': '+tempProtocol.head[k]['tip-racks'][n])
                  if ("container" in tempProtocol.head[k]['tip-racks'][n]){
                    TIPRACKS[ax].push(tempProtocol.head[k]['tip-racks'][n].container)
                  }else{
                    TIPRACKS[ax].push(tempProtocol.head[k]['tip-racks'][n])
                  }
                }
                console.log("TIPRACKS[",ax,"] = ",TIPRACKS[ax]);
              }
            }

          }
          show_robot_new_info();
          configureHead(tempProtocol.head)

          document.getElementById('runButton').removeEventListener('click',createAndSend);
          document.getElementById('runButton').addEventListener('click',createAndSend);

          if(tempProtocol.info){
            document.getElementById('infoName').innerHTML= "File Name: "+ tempProtocol.info.name;
            document.getElementById('infoDate').innerHTML= "Date Created: "+ tempProtocol.info['create-date'];
            document.getElementById('infoVersion').innerHTML= "Version: "+ tempProtocol.info.version;
            document.getElementById('infoDesc').innerHTML= "Description: " + tempProtocol.info.description;
            document.getElementById('infoRun').innerHTML= "Run Notes: " + tempProtocol.info['run-notes'];

          }else if(!tempProtocol.info){
            document.getElementById('infoDesc').innerHTML="";
          }
        }
      }
      else { // if the files messed up, current_protocol is undefined
        CURRENT_PROTOCOL = undefined;
      }
    }
    reader.readAsText(_F);
  }
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function show_robot_new_info() {

  // first, tell it the new containers we're using in this protocol

  var socketMsg = {
    'type' : 'createDeck',
    'data' : CURRENT_PROTOCOL.deck
  }

  sendMessage(socketMsg);

}

function configureHead(data) {
  var socketMsg = {
    'type' : 'configureHead',
    'data' : data
  }

  sendMessage(socketMsg);
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function createAndSend () {
  if(CURRENT_PROTOCOL) {

    var robotProtocol;
    var throwError = false;

    for(var toolname in CURRENT_PROTOCOL.head) {
      var thisAxis = CURRENT_PROTOCOL.head[toolname].axis;
      var calibratedVolume = robotState.pipettes[thisAxis].volume;
      if(calibratedVolume>0) {
        CURRENT_PROTOCOL.head[toolname].volume = calibratedVolume;
      }
      if(isNaN(CURRENT_PROTOCOL.head[toolname].volume) || CURRENT_PROTOCOL.head[toolname].volume<=0) {
        throwError = true;
      }
    }

    if(throwError) {
      alert('Please calibrate pipette volumes before running');
    }
    else {

      try {
        robotProtocol = createRobotProtocol(CURRENT_PROTOCOL);
      }
      catch (error) {
        console.log(error);
        alert(error);
      }

      if(robotProtocol) {

        var d = new Date();
        var dateString = '';

        dateString += d.getDate();
        dateString += '-';
        dateString += d.getMonth();
        dateString += '-';
        dateString += d.getFullYear();
        dateString += '-';
        dateString += d.getHours();
        dateString += ':';
        dateString += d.getMinutes();
        dateString += ':';
        dateString += d.getSeconds();

        var savefilename = _FILENAME.split('.')[0] + '-' + dateString + '.json';

        var blob = new Blob([JSON.stringify({
          'time' : dateString,
          'protocol' : CURRENT_PROTOCOL,
          'executable' : robotProtocol
        },undefined,2)], {type: "text/json;charset=utf-8"});

        var shouldSave = confirm('File processed. Save it to disk?');

        if(shouldSave) saveAs(blob, savefilename);

        var jobMsg = {
          'type' : 'instructions',
          'data' : robotProtocol
        }

        var shouldRun = confirm('Send file to be run?');

        if(shouldRun) {
          timeSentJob = new Date().getTime();
          sendMessage(jobMsg);
        }
        else {
          var shouldInfinity = confirm('Send file to be run FOR INFINITY?!?!?!?!?!');
          if(shouldInfinity) {
            jobMsg.type = 'infinity';
            sendMessage(jobMsg);
          }
          else {
            timeSentJob = undefined;
          }
        }
      }
    }
  }
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////

function loadDefaultContainers() {

  function onContainers () {
    try {
      var blob = JSON.parse(this.responseText);
      var newContainers = blob.containers;
      console.log('newContainers...');
      console.log(newContainers);
      if (newContainers) {
        saveContainers(newContainers);
      }
    }
    catch(error) {
      console.log(error);
    }
  }

    var containersFilepath = './data/containers.json';

  getAJAX(containersFilepath,onContainers);
}

////////
////////
////////

var labware_from_db  = {};

function saveContainers(newContainers) {
  for(var n in newContainers) {
    console.log('newContainer n = '+n);
    var cont = newContainers[n];
    var stringedCont = undefined;
    try {
      stringedCont = JSON.stringify(cont);
      console.log('stringedCont');
      console.log(stringedCont)
    }
    catch (error) {
      //
    }
    if(cont.locations && stringedCont) {
      console.log('saving cont '+cont+' to labware_from_db');
      labware_from_db[n] = stringedCont;
    }
  }
}

////////
////////
////////

function getAJAX(filepath,callback) {
  var oReq = new XMLHttpRequest();
  oReq.onload = callback;
  oReq.open("get", filepath, true);
  oReq.send();
}

/////////////////////////////////
/////////////////////////////////
/////////////////////////////////<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import ExpenseForm from './ExpenseForm';
import { addExpense } from '../actions/expenses';

const AddExpensePage = () => (

Add Expense

    <ExpenseForm
      onSubmit={(expense) => {
        props.dispatch(addExpense(expense));
        props.history.push('/'); // redirct to home page
      }}
      />

);

export default AddExpensePage;
<commit_msg>fix connect to redux to access dispatch<commit_after>import React from 'react';
import { connect } from 'react-redux';
import ExpenseForm from './ExpenseForm';
import { addExpense } from '../actions/expenses';

const AddExpensePage = (props) => (

Add Expense

    <ExpenseForm
      onSubmit={(expense) => {
        props.dispatch(addExpense(expense));
        props.history.push('/'); // redirct to home page
      }}
      />

);

export default connect()(AddExpensePage);
<|endoftext|>


<commit_before><commit_msg>remove routerState from context<commit_after><|endoftext|>


<commit_before>import React from 'react';
import {StyleSheet, Text, Image, ListView, ScrollView, View, TouchableHighlight} from 'react-native';

export default ({notifications, stateNavigator}) => {
  const dataSource = new ListView
    .DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
    .cloneWithRows(notifications);
  return (
    <View>
      <View style={styles.banner}>
        <Text style={styles.title}>Notifications</Text>
      </View>
      <ScrollView style={styles.view}>
        <ListView
          dataSource={dataSource}
          renderRow={({id, name, logo}) => (
            <TouchableHighlight
              underlayColor="white"
              onPress={() => {
                stateNavigator.navigate('timeline', {id});
            }}>
              <View style={styles.notification}>
                <Image style={styles.logo} source={logo} />
                <View style={styles.details}>
                  <Text style={styles.name}>{name}</Text>
                  <Text>followed you.</Text>
                </View>
              </View>
            </TouchableHighlight>
          )} />
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  banner: {
    paddingTop: 35,
    paddingLeft: 50,
    paddingBottom: 22,
    borderBottomWidth: 2,
    borderColor: '#ccd6dd',
  },
  title: {
    fontWeight: 'bold',
  },
  view: {
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: 10,
  },
});
<commit_msg>Styled notifications<commit_after>import React from 'react';
import {StyleSheet, Text, Image, ListView, ScrollView, View, TouchableHighlight} from 'react-native';

export default ({notifications, stateNavigator}) => {
  const dataSource = new ListView
    .DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
    .cloneWithRows(notifications);
  return (
    <View>
      <View style={styles.banner}>
        <Text style={styles.title}>Notifications</Text>
      </View>
      <ScrollView style={styles.view}>
        <ListView
          dataSource={dataSource}
          renderRow={({id, name, logo}) => (
            <TouchableHighlight
              underlayColor="white"
              onPress={() => {
                stateNavigator.navigate('timeline', {id});
            }}>
              <View style={styles.notification}>
                <Image style={styles.logo} source={logo} />
                <View style={styles.details}>
                  <Text style={styles.name}>{name}</Text>
                  <Text>followed you.</Text>
                </View>
              </View>
            </TouchableHighlight>
          )} />
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  banner: {
    paddingTop: 35,
    paddingLeft: 50,
    paddingBottom: 22,
    borderBottomWidth: 2,
    borderColor: '#ccd6dd',
  },
  title: {
    fontWeight: 'bold',
  },
  view: {
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: 10,
  },
  notification: {
    paddingTop: 10,
    paddingBottom: 15,
    borderBottomColor: '#ccd6dd',
    borderBottomWidth: 1,
  },
  details: {
    flexDirection: 'row',
  },
  name: {
    fontWeight: 'bold',
    paddingRight: 4,
  },
  logo: {
    width: 35,
    height: 35,
    borderRadius: 5,
    marginRight: 5,
    marginBottom: 10,
  },
});
<|endoftext|>


<commit_before>angular.module("jarl", [])
  .controller("jarlCtrl", ["$scope", "$location", function ($scope, $location) {
    // decode the URL if it is provided
    if (typeof($location.search().url) === "undefined") {
      $scope.fullUrl = "";
    } else {
      $scope.fullUrl = decodeURIComponent($location.search().url);
    }

    $scope.$watch("fullUrl", function (newVal, oldVal) {
      if (typeof(newVal) === "undefined") {
        $scope.baseUrl = "";
        $scope.shareableUrl = "";
        $scope.params = [];
        return;
      }

      var parts = newVal.split("?");

      if (newVal === "") {
        $scope.shareableUrl = "";
      } else {
        $scope.shareableUrl = $location.absUrl().split('#?')[0] + "#?url=" + encodeURIComponent(newVal);
      }

      $scope.baseUrl = parts[0];
      var paramStrings = parts[1];

      if (paramStrings) {
        var keyvals = paramStrings.split("&");

        var params = [];
        for (var i = 0; i < keyvals.length; i++) {
          var kv = keyvals[i].split("=");
          var key = kv[0];
          var val = decodeURIComponent(kv[1]);

          // lazily and flexibly check if it's base64
          // note, this will give false positives because we're not domain experts
          var isBase64;
          try {
            isBase64 = new RegExp(val + "=*").exec(btoa(atob(val)));
          } catch (e) {
            isBase64 = false;
          }

          if (isBase64) {
            params.push({
              key: key,
              val: val,
              isBase64: isBase64,
              decoded64: atob(val)
            });
          } else {
            params.push({
              key: key,
              val: val,
              isBase64: isBase64
            });
          }

        }

        $scope.params = params;
      } else {
        $scope.params = [];
      }
    });
  }]);
<commit_msg>filter out unreasonable results<commit_after>angular.module("jarl", [])
  .controller("jarlCtrl", ["$scope", "$location", function ($scope, $location) {
    // decode the URL if it is provided
    if (typeof($location.search().url) === "undefined") {
      $scope.fullUrl = "";
    } else {
      $scope.fullUrl = decodeURIComponent($location.search().url);
    }

    $scope.$watch("fullUrl", function (newVal, oldVal) {
      if (typeof(newVal) === "undefined") {
        $scope.baseUrl = "";
        $scope.shareableUrl = "";
        $scope.params = [];
        return;
      }

      var parts = newVal.split("?");

      if (newVal === "") {
        $scope.shareableUrl = "";
      } else {
        $scope.shareableUrl = $location.absUrl().split('#?')[0] + "#?url=" + encodeURIComponent(newVal);
      }

      $scope.baseUrl = parts[0];
      var paramStrings = parts[1];

      if (paramStrings) {
        var keyvals = paramStrings.split("&");

        var params = [];
        for (var i = 0; i < keyvals.length; i++) {
          var kv = keyvals[i].split("=");
          var key = kv[0];
          var val = decodeURIComponent(kv[1]);

          // lazily and (somewhat) flexibly check if it's base64
          // note, this will give false positives because we're not domain experts
          // right now we're looking for basic decodes + email addresses
          var isBase64, decodedVal;
          try {
            decodedVal = atob(val);

            isBase64 = /^[a-zA-Z0-9@.]+$/.exec(decodedVal) && new RegExp(val + "=*").exec(btoa(decodedVal));
          } catch (e) {
            isBase64 = false;
          }

          if (isBase64) {
            params.push({
              key: key,
              val: val,
              isBase64: isBase64,
              decoded64: decodedVal
            });
          } else {
            params.push({
              key: key,
              val: val,
              isBase64: isBase64
            });
          }

        }

        $scope.params = params;
      } else {
        $scope.params = [];
      }
    });
  }]);
<|endoftext|>


<commit_before>/** @flow */
import Immutable from 'immutable'
import React, { Component, PropTypes } from 'react'
import shallowCompare from 'react-addons-shallow-compare'
import { HashRouter, Match, Redirect } from 'react-router'

import ComponentLink from './ComponentLink'
import styles from './Application.css'
import NavLink from './NavLink'
import Wizard from './Wizard'
import { TYPES } from './Icon'
import { generateRandomList } from './utils'

import ArrowKeyStepperExample from '../ArrowKeyStepper/ArrowKeyStepper.example'
import AutoSizerExample from '../AutoSizer/AutoSizer.example'
import WindowScrollerExample from '../WindowScroller/WindowScroller.example'
import CellMeasurerExample from '../CellMeasurer/CellMeasurer.example'
import CollectionExample from '../Collection/Collection.example'
import ColumnSizerExample from '../ColumnSizer/ColumnSizer.example'
import GridExample from '../Grid/Grid.example'
import TableExample from '../Table/Table.example'
import InfiniteLoaderExample from '../InfiniteLoader/InfiniteLoader.example'
import ScrollSyncExample from '../ScrollSync/ScrollSync.example'
import ListExample from '../List/List.example'

const COMPONENT_EXAMPLES_MAP = {
  '/components/ArrowKeyStepper': ArrowKeyStepperExample,
  '/components/AutoSizer': AutoSizerExample,
  '/components/CellMeasurer': CellMeasurerExample,
  '/components/Collection': CollectionExample,
  '/components/ColumnSizer': ColumnSizerExample,
  '/components/Table': TableExample,
  '/components/Grid': GridExample,
  '/components/InfiniteLoader': InfiniteLoaderExample,
  '/components/ScrollSync': ScrollSyncExample,
  '/components/List': ListExample,
  '/components/WindowScroller': WindowScrollerExample
}

// HACK Generate arbitrary data for use in example components :)
const list = Immutable.List(generateRandomList())

export default class Application extends Component {
  static childContextTypes = {
    list: PropTypes.instanceOf(Immutable.List).isRequired
  };

  getChildContext () {
    return {
      list
    }
  }

  render () {
    return (
      <HashRouter basename=''>

                  React

                  Virtualized

                <NavLink to='/components/List' iconType={TYPES.COMPONENTS}>Components</NavLink>
                <NavLink to='/wizard' iconType={TYPES.WIZARD}>Wizard</NavLink>
                <NavLink href='https://github.com/bvaughn/react-virtualized' iconType={TYPES.SOURCE}>Source</NavLink>
                <NavLink href='https://github.com/bvaughn/react-virtualized/tree/master/docs#documentation' iconType={TYPES.DOCUMENTATION}>Documentation</NavLink>
                <NavLink href='https://github.com/bvaughn/react-virtualized/issues' iconType={TYPES.ISSUES}>Issues</NavLink>

              <ComponentLink to='/components/Collection'>Collection</ComponentLink>
              <ComponentLink to='/components/Grid'>Grid</ComponentLink>
              <ComponentLink to='/components/List'>List</ComponentLink>
              <ComponentLink to='/components/Table'>Table</ComponentLink>

              <ComponentLink to='/components/ArrowKeyStepper'>ArrowKeyStepper</ComponentLink>
              <ComponentLink to='/components/AutoSizer'>AutoSizer</ComponentLink>
              <ComponentLink to='/components/CellMeasurer'>CellMeasurer</ComponentLink>
              <ComponentLink to='/components/ColumnSizer'>ColumnSizer</ComponentLink>
              <ComponentLink to='/components/InfiniteLoader'>InfiniteLoader</ComponentLink>
              <ComponentLink to='/components/ScrollSync'>ScrollSync</ComponentLink>
              <ComponentLink to='/components/WindowScroller'>WindowScroller</ComponentLink>

              <Match pattern='/wizard' component={Wizard} />
              {Object.keys(COMPONENT_EXAMPLES_MAP).map((route) => (
                <Match
                  component={COMPONENT_EXAMPLES_MAP[route]}
                  key={route}
                  pattern={route}
                />
              ))}
              <Match
                exactly
                pattern='/'
                render={() => (
                  <Redirect to='/components/List' />
                )}
              />

      </HashRouter>
    )
  }

  shouldComponentUpdate (nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState)
  }
}
<commit_msg>Reverted HashRouter basename change<commit_after>/** @flow */
import Immutable from 'immutable'
import React, { Component, PropTypes } from 'react'
import shallowCompare from 'react-addons-shallow-compare'
import { HashRouter, Match, Redirect } from 'react-router'

import ComponentLink from './ComponentLink'
import styles from './Application.css'
import NavLink from './NavLink'
import Wizard from './Wizard'
import { TYPES } from './Icon'
import { generateRandomList } from './utils'

import ArrowKeyStepperExample from '../ArrowKeyStepper/ArrowKeyStepper.example'
import AutoSizerExample from '../AutoSizer/AutoSizer.example'
import WindowScrollerExample from '../WindowScroller/WindowScroller.example'
import CellMeasurerExample from '../CellMeasurer/CellMeasurer.example'
import CollectionExample from '../Collection/Collection.example'
import ColumnSizerExample from '../ColumnSizer/ColumnSizer.example'
import GridExample from '../Grid/Grid.example'
import TableExample from '../Table/Table.example'
import InfiniteLoaderExample from '../InfiniteLoader/InfiniteLoader.example'
import ScrollSyncExample from '../ScrollSync/ScrollSync.example'
import ListExample from '../List/List.example'

const COMPONENT_EXAMPLES_MAP = {
  '/components/ArrowKeyStepper': ArrowKeyStepperExample,
  '/components/AutoSizer': AutoSizerExample,
  '/components/CellMeasurer': CellMeasurerExample,
  '/components/Collection': CollectionExample,
  '/components/ColumnSizer': ColumnSizerExample,
  '/components/Table': TableExample,
  '/components/Grid': GridExample,
  '/components/InfiniteLoader': InfiniteLoaderExample,
  '/components/ScrollSync': ScrollSyncExample,
  '/components/List': ListExample,
  '/components/WindowScroller': WindowScrollerExample
}

// HACK Generate arbitrary data for use in example components :)
const list = Immutable.List(generateRandomList())

export default class Application extends Component {
  static childContextTypes = {
    list: PropTypes.instanceOf(Immutable.List).isRequired
  };

  getChildContext () {
    return {
      list
    }
  }

  render () {
    return (
      <HashRouter>

                  React

                  Virtualized

                <NavLink to='/components/List' iconType={TYPES.COMPONENTS}>Components</NavLink>
                <NavLink to='/wizard' iconType={TYPES.WIZARD}>Wizard</NavLink>
                <NavLink href='https://github.com/bvaughn/react-virtualized' iconType={TYPES.SOURCE}>Source</NavLink>
                <NavLink href='https://github.com/bvaughn/react-virtualized/tree/master/docs#documentation' iconType={TYPES.DOCUMENTATION}>Documentation</NavLink>
                <NavLink href='https://github.com/bvaughn/react-virtualized/issues' iconType={TYPES.ISSUES}>Issues</NavLink>

              <ComponentLink to='/components/Collection'>Collection</ComponentLink>
              <ComponentLink to='/components/Grid'>Grid</ComponentLink>
              <ComponentLink to='/components/List'>List</ComponentLink>
              <ComponentLink to='/components/Table'>Table</ComponentLink>

              <ComponentLink to='/components/ArrowKeyStepper'>ArrowKeyStepper</ComponentLink>
              <ComponentLink to='/components/AutoSizer'>AutoSizer</ComponentLink>
              <ComponentLink to='/components/CellMeasurer'>CellMeasurer</ComponentLink>
              <ComponentLink to='/components/ColumnSizer'>ColumnSizer</ComponentLink>
              <ComponentLink to='/components/InfiniteLoader'>InfiniteLoader</ComponentLink>
              <ComponentLink to='/components/ScrollSync'>ScrollSync</ComponentLink>
              <ComponentLink to='/components/WindowScroller'>WindowScroller</ComponentLink>

              <Match pattern='/wizard' component={Wizard} />
              {Object.keys(COMPONENT_EXAMPLES_MAP).map((route) => (
                <Match
                  component={COMPONENT_EXAMPLES_MAP[route]}
                  key={route}
                  pattern={route}
                />
              ))}
              <Match
                exactly
                pattern='/'
                render={() => (
                  <Redirect to='/components/List' />
                )}
              />

      </HashRouter>
    )
  }

  shouldComponentUpdate (nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState)
  }
}
<|endoftext|>


<commit_before>/**
*   Text Measure
*   Author: Leif Marcus
*   version: 1.0
*   Licenze: MIT
*/
(function(name, definition) {
    if (typeof define === 'function') {
        // define for AMD:
        define(definition);
    } else if (typeof module !== 'undefined' && module.exports) {
        // exports for Node.js
        module.exports = definition();
    } else {
        // using the module in the browser:
        var curModule = definition(),
        global = this,
        originalModule = global[name];
        curModule.noConflict = function() {
            global[name] = originalModule;
            return curModule;
        };
        global[name] = curModule;
    }
} ('textMeasure', function() {

    var ceil = Math.ceil;
    var checkWidth = ['width', 'margin-left', 'margin-right', 'padding-left', 'padding-right'];
    var checkHeight = ['height', 'margin-top', 'margin-bottom', 'padding-top', 'padding-bottom'];

    /**
    *   adds calculated style values together
    *   @param {object} compStyles - a CSSStyleDeclaration Object
    *   @param {array} arr - a list of css properties to go through
    *   @return {number} - returns the sum of all property values.
    */
    var addValues = function(compStyles, arr) {
        return arr.reduce(function(prev, curr) {
            return prev + parseFloat(compStyles.getPropertyValue(curr));
        }, 0);
    };
    /**
    *   measures the dimension of a dom element
    *   @param {object} node - the html element object (DOMNode)
    *   @return {object} - calculated width and height of the node
    */
    var measureElementDimension = function(node) {
        var compStyles = window.getComputedStyle(node, null);

        var width = addValues(compStyles, checkWidth);
        var height = addValues(compStyles, checkHeight);

        return {
            width: ceil(width),
            height: ceil(height),
        };
    };
    /**
    *   creates a dom node
    *   @param {string} className - a classname to append to the element
    *   @param {string} styles - style rules for the style attribute
    *   @param {string} html - some html to append to the element
    *   @return {object} - calculated width and height of the node
    */
    var createElement = function(className, styles, html) {
        var el = document.createElement('div');
        el.className = className || '';
        el.style.cssText = styles || '';
        if (html) { el.innerHTML = html; }
        return el;
    };
    var destroyElement = function(parent, child) {
        parent.removeChild(child);
    };

    var rootEl = document.getElementsByTagName('body')[0];
    var baseStyles = 'position:absolute !important;top:-9999px !important;' +
                     'left:-9999px !important;visibility:hidden; !important;';
    var baseElementStyles = 'display:inline-block !important;';

    return {
        /**
        *   counts the words of a given string
        *   @param {string} str - the string that should be analysed
        *   @return {number} - word count
        */
        wordsCount: function(str) {
            return this.words(str).length;
        },
        /**
        *   creates an array with all words
        *   @param {string} str - the string that should be analysed
        *   @return {array} - words in an array
        */
        words: function(str) {
            return str.split(' ');
        },
        /**
        *   gets the Word with the longest Width
        *   @param {string} str - the string that should be analysed
        *   @param {string} [elementClass] - optional
        *   @param {string} [containerClass] - optional
        *   @return {object} - the word and the width of it.
        */
        longestWord: function(str, elementClass, containerClass) {
            var words = this.words(str);
            var savedWidth = 0;
            var savedIndex = 0;
            words.forEach(function(word, index) {
                var width = this.getDimension(
                    word,
                    'auto',
                    'auto',
                    elementClass,
                    containerClass
                ).width;

                if (width > savedWidth) {
                    savedWidth = width;
                    savedIndex = index;
                }
            }, this);
            return {
                word: words[savedIndex],
                width: savedWidth
            };
        },
        /**
        *   gets a dimension of an element with text inside
        *   by a given max dimension
        *   @param {string} html - a string or html string
        *   @param {(number|string)} maxWidth - max width of the container
        *   @param {integer/string} maxHeight - max height of the container
        *   @param {string} [elementClass] - class for the element
        *   @param {string} [containerClass] - class for the container
        *   @return {object} - width and height of the text and text overflow
        */
        getDimension: function(html, maxWidth, maxHeight, elementClass, containerClass) {
            // base variables:

            // the container to append the element on:
            var container = createElement(
                containerClass,
                baseStyles +
                    'max-width:' + (isNaN(maxWidth) ? maxWidth : maxWidth + 'px') + ';' +
                    'max-height:' + (isNaN(maxHeight) ? maxHeight : maxHeight + 'px') + ';'
            );

            // the element to render text in:
            var element = createElement(
                elementClass,
                baseElementStyles,
                html
            );

            // append Elements to dom:
            container.appendChild(element);
            rootEl.appendChild(container);

            var compStyles = measureElementDimension(element);

            // remove child from measure element.
            destroyElement(rootEl, container);

            return {
                width: compStyles.width,
                height: compStyles.height,
                overflow: compStyles.height > maxHeight ||
                          compStyles.width > maxWidth
            };
        }
    };
}));
<commit_msg>comments<commit_after>/**
*   Text Measure
*   Author: Leif Marcus
*   version: 1.0
*   Licenze: MIT
*/
(function(name, definition) {
    if (typeof define === 'function') {
        // define for AMD:
        define(definition);
    } else if (typeof module !== 'undefined' && module.exports) {
        // exports for Node.js
        module.exports = definition();
    } else {
        // using the module in the browser:
        var curModule = definition(),
        global = this,
        originalModule = global[name];
        curModule.noConflict = function() {
            global[name] = originalModule;
            return curModule;
        };
        global[name] = curModule;
    }
} ('textMeasure', function() {

    var ceil = Math.ceil;
    var checkWidth = ['width', 'margin-left', 'margin-right', 'padding-left', 'padding-right'];
    var checkHeight = ['height', 'margin-top', 'margin-bottom', 'padding-top', 'padding-bottom'];

    /**
    *   adds calculated style values together
    *   @param {object} compStyles - a CSSStyleDeclaration Object
    *   @param {array} arr - a list of css properties to go through
    *   @returns {number} returns the sum of all property values.
    */
    var addValues = function(compStyles, arr) {
        return arr.reduce(function(prev, curr) {
            return prev + parseFloat(compStyles.getPropertyValue(curr));
        }, 0);
    };
    /**
    *   measures the dimension of a dom element
    *   @param {object} node - the html element object (DOMNode)
    *   @returns {object} calculated width and height of the node
    */
    var measureElementDimension = function(node) {
        var compStyles = window.getComputedStyle(node, null);

        var width = addValues(compStyles, checkWidth);
        var height = addValues(compStyles, checkHeight);

        return {
            width: ceil(width),
            height: ceil(height),
        };
    };
    /**
    *   creates a dom node
    *   @param {string} className - a classname to append to the element
    *   @param {string} styles - style rules for the style attribute
    *   @param {string} html - some html to append to the element
    *   @returns {object} calculated width and height of the node
    */
    var createElement = function(className, styles, html) {
        var el = document.createElement('div');
        el.className = className || '';
        el.style.cssText = styles || '';
        if (html) { el.innerHTML = html; }
        return el;
    };
    var destroyElement = function(parent, child) {
        parent.removeChild(child);
    };

    var rootEl = document.getElementsByTagName('body')[0];
    var baseStyles = 'position:absolute !important;top:-9999px !important;' +
                     'left:-9999px !important;visibility:hidden; !important;';
    var baseElementStyles = 'display:inline-block !important;';

    return {
        /**
        *   counts the words of a given string
        *   @param {string} str - the string that should be analysed
        *   @returns {number} word count
        */
        wordsCount: function(str) {
            return this.words(str).length;
        },
        /**
        *   creates an array with all words
        *   @param {string} str - the string that should be analysed
        *   @returns {array} words in an array
        */
        words: function(str) {
            return str.split(' ');
        },
        /**
        *   gets the Word with the longest Width
        *   @param {string} str - the string that should be analysed
        *   @param {string} [elementClass] - optional
        *   @param {string} [containerClass] - optional
        *   @returns {object} the word and the width of it.
        */
        longestWord: function(str, elementClass, containerClass) {
            var words = this.words(str);
            var savedWidth = 0;
            var savedIndex = 0;
            words.forEach(function(word, index) {
                var width = this.getDimension(
                    word,
                    'auto',
                    'auto',
                    elementClass,
                    containerClass
                ).width;

                if (width > savedWidth) {
                    savedWidth = width;
                    savedIndex = index;
                }
            }, this);
            return {
                word: words[savedIndex],
                width: savedWidth
            };
        },
        /**
        *   gets a dimension of an element with text inside
        *   by a given max dimension
        *   @param {string} html - a string or html string
        *   @param {number|string} maxWidth - max width of the container
        *   @param {number|string} maxHeight - max height of the container
        *   @param {string} [elementClass] - class for the element
        *   @param {string} [containerClass] - class for the container
        *   @returns {object} width and height of the text and text overflow
        */
        getDimension: function(html, maxWidth, maxHeight, elementClass, containerClass) {
            // base variables:

            // the container to append the element on:
            var container = createElement(
                containerClass,
                baseStyles +
                    'max-width:' + (isNaN(maxWidth) ? maxWidth : maxWidth + 'px') + ';' +
                    'max-height:' + (isNaN(maxHeight) ? maxHeight : maxHeight + 'px') + ';'
            );

            // the element to render text in:
            var element = createElement(
                elementClass,
                baseElementStyles,
                html
            );

            // append Elements to dom:
            container.appendChild(element);
            rootEl.appendChild(container);

            var compStyles = measureElementDimension(element);

            // remove child from measure element.
            destroyElement(rootEl, container);

            return {
                width: compStyles.width,
                height: compStyles.height,
                overflow: compStyles.height > maxHeight ||
                          compStyles.width > maxWidth
            };
        }
    };
}));
<|endoftext|>


<commit_before>
OpenLayers.GenomeBrowser = OpenLayers.Map;

OpenLayers.GenomeBrowser.prototype.pan = function(dx, dy) {
    // getCenter
    var centerPx = this.getViewPortPxFromLonLat(this.getCenter());

    // adjust
    var newCenterPx = centerPx.add(dx, 0);

    // only call setCenter if there has been a change
    if (newCenterPx.x != centerPx.x) {
        var newCenterLonLat = this.getLonLatFromViewPortPx(newCenterPx);
        // this is required or the tools wont cause map to pan
        newCenterLonLat.lat = 0
        this.setCenter(newCenterLonLat);
    }
};

OpenLayers.GenomeBrowser.prototype.centerLayerContainer = function(lonlat){
            var originPx = this.getViewPortPxFromLonLat(this.layerContainerOrigin);
            var newPx = this.getViewPortPxFromLonLat(lonlat);

            if ((originPx != null) && (newPx != null)) {
                this.layerContainerDiv.style.left = (originPx.x - newPx.x) + "px";
            }

};

OpenLayers.Control.PanZoom.prototype.draw = function(px) {
    // initialize our internal div
    OpenLayers.Control.prototype.draw.apply(this, arguments);
    px = this.position.clone();

    // place the controls
    this.buttons = new Array();

    var sz = new OpenLayers.Size(18,18);
    var centered = new OpenLayers.Pixel(px.x+sz.w/2, px.y);
    px.y = centered.y+sz.h;
    this._addButton("panleft", "west-mini.png", px, sz);
    this._addButton("panright", "east-mini.png", px.add(sz.w, 0), sz);
    this._addButton("zoomin", "zoom-plus-mini.png",
                    centered.add(0, sz.h*3+5), sz);
    this._addButton("zoomworld", "zoom-world-mini.png",
                    centered.add(0, sz.h*4+5), sz);
    this._addButton("zoomout", "zoom-minus-mini.png",
                    centered.add(0, sz.h*5+5), sz);
    return this.div;
};
OpenLayers.Control.PanZoomBar.prototype.draw = function(px) {
    // initialize our internal div
    OpenLayers.Control.prototype.draw.apply(this, arguments);
    px = this.position.clone();

    // place the controls
    this.buttons = new Array();
    var sz = new OpenLayers.Size(18,18);
    var centered = new OpenLayers.Pixel(px.x+sz.w/2, px.y);

    px.y = centered.y+sz.h;
    this._addButton("panleft", "west-mini.png", px, sz);
    this._addButton("panright", "east-mini.png", px.add(sz.w, 0), sz);
    this._addButton("zoomin", "zoom-plus-mini.png", centered.add(0, sz.h*3+5), sz);
    centered = this._addZoomBar(centered.add(0, sz.h*4 + 5));
    this._addButton("zoomout", "zoom-minus-mini.png", centered, sz);
    return this.div;
};

OpenLayers.Control.MousePosition.prototype.redraw = function(evt) {

    var lonLat;
    if (evt == null) {
        lonLat = new OpenLayers.LonLat(0, 0);
    } else {
        if (this.lastXy == null ||
            Math.abs(evt.xy.x - this.lastXy.x) > this.granularity)
        {
            this.lastXy = evt.xy;
            return;
        }

        lonLat = this.map.getLonLatFromPixel(evt.xy);
        this.lastXy = evt.xy;
    }

    var digits = parseInt(this.numdigits);
    var newHtml = parseInt(lonLat.lon) + this.map.units;

    if (newHtml != this.element.innerHTML) {
        this.element.innerHTML = newHtml;
    }
};

OpenLayers.BasePair = function(bp){
    var ll = new OpenLayers.LonLat(bp,0);
    ll.basepair = ll.x;
    return ll;
}

function jfetch(url,t,o) {
  var req = jfetch.xhr();
  req.open("GET",url,true);
  req.onreadystatechange = function() {
    if(req.readyState == 4){
      var rsp = req.responseText;
      if(t.constructor == Function) return t.apply(o,[rsp]);
      t = document.getElementById(t);
      t[t.value ==undefined ? 'innerHTML': 'value'] = rsp;
      req = null;
    }
  };
  req.send(null);
}
jfetch.xhr =
    (window.ActiveXObject)
   ? function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }
   : function(){ return new XMLHttpRequest()};
<commit_msg>updated to latest version<commit_after>
OpenLayers.GenomeBrowser = OpenLayers.Map;

OpenLayers.GenomeBrowser.prototype.pan = function(dx, dy) {
    // getCenter
    var centerPx = this.getViewPortPxFromLonLat(this.getCenter());

    // adjust
    var newCenterPx = centerPx.add(dx, 0);

    // only call setCenter if there has been a change
    if (newCenterPx.x != centerPx.x) {
        var newCenterLonLat = this.getLonLatFromViewPortPx(newCenterPx);
        // this is required or the tools wont cause map to pan
        newCenterLonLat.lat = 0
        this.setCenter(newCenterLonLat);
    }
};

OpenLayers.GenomeBrowser.prototype.centerLayerContainer = function(lonlat){
            var originPx = this.getViewPortPxFromLonLat(this.layerContainerOrigin);
            var newPx = this.getViewPortPxFromLonLat(lonlat);

            if ((originPx != null) && (newPx != null)) {
                this.layerContainerDiv.style.left = (originPx.x - newPx.x) + "px";
            }

};

OpenLayers.Control.PanZoom.prototype.draw = function(px) {
    // initialize our internal div
    OpenLayers.Control.prototype.draw.apply(this, arguments);
    px = this.position.clone();

    // place the controls
    this.buttons = new Array();

    var sz = new OpenLayers.Size(18,18);
    var centered = new OpenLayers.Pixel(px.x+sz.w/2, px.y);
    px.y = centered.y+sz.h;
    this._addButton("panleft", "west-mini.png", px, sz);
    this._addButton("panright", "east-mini.png", px.add(sz.w, 0), sz);
    this._addButton("zoomin", "zoom-plus-mini.png",
                    centered.add(0, sz.h*3+5), sz);
    this._addButton("zoomworld", "zoom-world-mini.png",
                    centered.add(0, sz.h*4+5), sz);
    this._addButton("zoomout", "zoom-minus-mini.png",
                    centered.add(0, sz.h*5+5), sz);
    return this.div;
};
OpenLayers.Control.PanZoomBar.prototype.draw = function(px) {
    // initialize our internal div
    OpenLayers.Control.prototype.draw.apply(this, arguments);
    px = this.position.clone();

    // place the controls
    this.buttons = new Array();
    var sz = new OpenLayers.Size(18,18);
    var centered = new OpenLayers.Pixel(px.x+sz.w/2, px.y);

    px.y = centered.y+sz.h;
    this._addButton("panleft", "west-mini.png", px, sz);
    this._addButton("panright", "east-mini.png", px.add(sz.w, 0), sz);
    this._addButton("zoomin", "zoom-plus-mini.png", centered.add(0, sz.h*3+5), sz);
    centered = this._addZoomBar(centered.add(0, sz.h*4 + 5));
    this._addButton("zoomout", "zoom-minus-mini.png", centered, sz);
    return this.div;
};

OpenLayers.Control.MousePosition.prototype.redraw = function(evt) {

    var lonLat;
    if (evt == null) {
        lonLat = new OpenLayers.LonLat(0, 0);
    } else {
        if (this.lastXy == null ||
            Math.abs(evt.xy.x - this.lastXy.x) > this.granularity)
        {
            this.lastXy = evt.xy;
            return;
        }

        lonLat = this.map.getLonLatFromPixel(evt.xy);
        this.lastXy = evt.xy;
    }

    var digits = parseInt(this.numdigits);
    var newHtml = parseInt(lonLat.lon) + this.map.units;

    if (newHtml != this.element.innerHTML) {
        this.element.innerHTML = newHtml;
    }
};

/**************************************************************/
/*  WHEN GETTING A PINK TILE, RELOAD FROM A DIFFERENT SERVER  */
/**************************************************************/
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
OpenLayers.Util.onImageLoadError = function() {
    this._attempts = (this._attempts) ? (this._attempts + 1) : 1;
    if(this._attempts <= OpenLayers.IMAGE_RELOAD_ATTEMPTS) {
        var urls = this.layer.url;
        if(urls instanceof Array && urls.length > 1){
            var src = this.src.toString();
            var current_url, k;
            for (k = 0; current_url = urls[k]; k++){
                if(src.indexOf(current_url) != -1){
                    break;
                }
            }
            var guess = Math.floor(urls.length * Math.random())
            var new_url = urls[guess];
            k = 0;
            while(new_url == current_url && k++ < 4){
                guess = Math.floor(urls.length * Math.random())
                new_url = urls[guess];
            }
            this.src = src.replace(current_url, new_url);
        } else {
            this.src = this.src;
        }
    } else {
        this.style.backgroundColor = OpenLayers.Util.onImageLoadErrorColor;
    }
    this.style.display = "";
};
OpenLayers.Tile.Image.prototype.destroy = function() {
        if (this.imgDiv != null)  {
            OpenLayers.Event.stopObservingElement(this.imgDiv.id);
            if (this.imgDiv.parentNode == this.frame) {
                this.frame.removeChild(this.imgDiv);
                this.imgDiv.map = null;
            }
            this.imgDiv.layer = null;
        }
        this.imgDiv = null;
        if ((this.frame != null) && (this.frame.parentNode == this.layer.div)) {
            this.layer.div.removeChild(this.frame);
        }
        this.frame = null;
        OpenLayers.Tile.prototype.destroy.apply(this, arguments);
    };

OpenLayers.Tile.Image.prototype.draw = function() {
        if (this.layer != this.layer.map.baseLayer && this.layer.reproject) {
            this.bounds = this.getBoundsFromBaseLayer(this.position);
        }
        if (!OpenLayers.Tile.prototype.draw.apply(this, arguments)) {
            return false;
        }

        if (this.isLoading) {
            //if we're already loading, send 'reload' instead of 'loadstart'.
            this.events.triggerEvent("reload");
        } else {
            this.isLoading = true;
            this.events.triggerEvent("loadstart");
        }

        if (this.imgDiv == null) {
            this.initImgDiv();
        }
        // ADDED FOR CHANGING URLS:
        this.imgDiv.layer = this.layer;

        this.imgDiv.viewRequestID = this.layer.map.viewRequestID;

        this.url = this.layer.getURL(this.bounds);
        // position the frame
        OpenLayers.Util.modifyDOMElement(this.frame,
                                         null, this.position, this.size);

        var imageSize = this.layer.getImageSize();
        if (this.layerAlphaHack) {
            OpenLayers.Util.modifyAlphaImageDiv(this.imgDiv,
                    null, null, imageSize, this.url);
        } else {
            this.imgDiv.src = this.url;
            OpenLayers.Util.modifyDOMElement(this.imgDiv,
                    null, null, imageSize) ;
        }
        return true;
    };

/********************************************************/

OpenLayers.BasePair = function(bp){
    var ll = new OpenLayers.LonLat(bp,0);
    ll.basepair = ll.x;
    return ll;
}

function jfetch(url,t,o) {
  var req = jfetch.xhr();
  req.open("GET",url,true);
  req.onreadystatechange = function() {
    if(req.readyState == 4){
      var rsp = req.responseText;
      if(t.constructor == Function) return t.apply(o,[rsp]);
      t = document.getElementById(t);
      t[t.value ==undefined ? 'innerHTML': 'value'] = rsp;
      req = null;
    }
  };
  req.send(null);
}
jfetch.xhr =
    (window.ActiveXObject)
   ? function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }
   : function(){ return new XMLHttpRequest()};
<|endoftext|>


<commit_before>
import commonjs from 'rollup-plugin-commonjs';
import html from 'rollup-plugin-html';
import nodeResolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';

export default {
  entry: 'dist/index.js',
  dest: 'dist/bundle.umd.js',
  exports: 'named',
  sourceMap: false,
  format: 'umd',
  moduleName: '@ngx-form/element',
  onwarn,
  plugins: [
    commonjs({
      namedExports: {
        'node_modules/rxjs/**': ['named']
      }
    }),
    html({
      include: '**/*.html',
      htmlMinifierOptions: {
        caseSensitive: true // need to do not lower letter
      }
    }),
    nodeResolve({
      // use "es2015" field for ES2015 modules with ES2015 code,
	    // if possible
      es2015: true, // Default: false

      // use "module" field for ES2015 modules with ES5 code,
      // if possible
      module: true, // Default: true

      // use "jsnext:main" if possible
      // – see https://github.com/rollup/rollup/wiki/jsnext:main
      jsnext: true,  // Default: false

      // use "main" field or index.js, even if it's not an ES6 module
      // (needs to be converted from CommonJS to ES6
      // – see https://github.com/rollup/rollup-plugin-commonjs
      main: true,  // Default: true

      extensions: [ '.js', '.json', 'html']
    }),
    typescript({
      typescript: require('./node_modules/typescript')
    }),
    uglify({}, minify)
  ],
  globals: {
    '@angular/core': 'ng.core'
  }
};

function onwarn(message) {
  const suppressed = [
    'UNRESOLVED_IMPORT',
    'THIS_IS_UNDEFINED'
  ];

  if (!suppressed.find(code => message.code === code)) {
    return console.warn(message.message);
  }
}
<commit_msg>chore:  rollup config remove globals, remove plugins.commonjs settings<commit_after>
// import angular from 'rollup-plugin-angular';
import commonjs from 'rollup-plugin-commonjs';
import html from 'rollup-plugin-html';
import nodeResolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';

export default {
  entry: 'dist/index.js',
  dest: 'dist/bundle.umd.js',
  exports: 'named',
  sourceMap: false,
  format: 'umd',
  moduleName: '@ngx-form/element',
  onwarn,
  plugins: [
    commonjs(),
    html({
      include: '**/*.html',
      htmlMinifierOptions: {
        caseSensitive: true // need to do not lower letter
      }
    }),
    nodeResolve({
      // use "es2015" field for ES2015 modules with ES2015 code,
	    // if possible
      es2015: true, // Default: false

      // use "module" field for ES2015 modules with ES5 code,
      // if possible
      module: true, // Default: true

      // use "jsnext:main" if possible
      // – see https://github.com/rollup/rollup/wiki/jsnext:main
      jsnext: true,  // Default: false

      // use "main" field or index.js, even if it's not an ES6 module
      // (needs to be converted from CommonJS to ES6
      // – see https://github.com/rollup/rollup-plugin-commonjs
      main: true,  // Default: true

      extensions: [ '.js', '.json' ]
    }),
    typescript({
      typescript: require('./node_modules/typescript')
    }),
    uglify({}, minify)
  ]
};

function onwarn(message) {
  const suppressed = [
    'UNRESOLVED_IMPORT',
    'THIS_IS_UNDEFINED'
  ];

  if (!suppressed.find(code => message.code === code)) {
    return console.warn(message.message);
  }
}
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/firebug",
    "firebug/lib/trace",
    "firebug/debugger/script/sourceFile",
    "firebug/debugger/script/sourceLink",
],
function(Firebug, FBTrace, SourceFile, SourceLink) {

"use strict"

// ********************************************************************************************* //
// Constants

var Cc = Components.classes;
var Ci = Components.interfaces;

var TraceError = FBTrace.toError();
var Trace = FBTrace.to("DBG_ERRORLOG");

// ********************************************************************************************* //
// ErrorMessageObj Implementation

/**
 * @object This object collects data about an error that happens in the content. It's used
 * by {@ErrorMessage} Domplate template as the data source.
 */
function ErrorMessageObj(message, href, lineNo, source, category, context,
    trace, msgId, colNumber)
{
    this.message = message;
    this.href = href;
    this.lineNo = lineNo;
    this.source = source;
    this.category = category;
    this.context = context;
    this.trace = trace;
    this.msgId = msgId || this.getId();
    this.colNumber = colNumber;
}

ErrorMessageObj.prototype =
{
    getSourceLine: function(callback)
    {
        if (this.source)
            return this.source;

        var sourceFile = SourceFile.getSourceFileByUrl(this.context, this.href);
        if (!sourceFile)
        {
            TraceError.sysout("errorMessageObj.getSourceLine; ERROR no source file! " +
                this.href);
            return;
        }

        this.sourceLoading = true;

        return sourceFile.getLine(this.lineNo - 1, (line) =>
        {
            this.sourceLoading = false;
            this.source = line;

            if (callback)
                callback(line);
        });
    },

    getSourceLink: function()
    {
        var ext = this.category == "css" ? "css" : "js";
        return this.lineNo ? new SourceLink(this.href, this.lineNo, ext,
            null, null, this.colNumber) : null;
    },

    resetSource: function()
    {
        if (this.href && this.lineNo != null)
            this.source = this.getSourceLine();
    },

    correctWithStackTrace: function(trace)
    {
        var frame = trace.frames[0];
        if (frame)
        {
            this.href = frame.href;
            this.lineNo = frame.line;
            this.trace = trace;
        }
    },

    getId: function()
    {
        return this.href + ":" + this.message + ":" + this.lineNo + ":" +
            (this.colNumber ? this.colNumber : "");
    }
};

// ********************************************************************************************* //
// Registration

return ErrorMessageObj;

// ********************************************************************************************* //
});
<commit_msg>Issue 7044: 	Source lines in console should be shown even when Script panel is disabled<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/firebug",
    "firebug/lib/trace",
    "firebug/lib/events",
    "firebug/lib/string",
    "firebug/debugger/debuggerLib",
    "firebug/debugger/script/sourceFile",
    "firebug/debugger/script/sourceLink",
],
function(Firebug, FBTrace, Events, Str, DebuggerLib, SourceFile, SourceLink) {

"use strict"

// ********************************************************************************************* //
// Constants

var Cc = Components.classes;
var Ci = Components.interfaces;

var TraceError = FBTrace.toError();
var Trace = FBTrace.to("DBG_ERRORLOG");

// ********************************************************************************************* //
// ErrorMessageObj Implementation

/**
 * @object This object collects data about an error that happens in the content. It's used
 * by {@ErrorMessage} Domplate template as the data source.
 */
function ErrorMessageObj(message, href, lineNo, source, category, context,
    trace, msgId, colNumber)
{
    this.message = message;
    this.href = href;
    this.lineNo = lineNo;
    this.source = source;
    this.category = category;
    this.context = context;
    this.trace = trace;
    this.msgId = msgId || this.getId();
    this.colNumber = colNumber;
    this.sourceLoaded = false;
}

ErrorMessageObj.prototype =
{
    getSourceLine: function(callback)
    {
        if (this.sourceLoaded)
            return this.source;

        var sourceFile = SourceFile.getSourceFileByUrl(this.context, this.href);
        if (!sourceFile)
        {
            if (this.sourceLoading)
                return;

            this.sourceLoading = true;

            SourceProvider.getSourceLine(this.context, this.href, this.lineNo, (line) =>
            {
                this.source = line
                this.sourceLoaded = true;
                this.sourceLoading = false;

                if (callback)
                    callback(line);
            });

            return;
        }

        this.sourceLoading = true;

        return sourceFile.getLine(this.lineNo - 1, (line) =>
        {
            this.sourceLoading = false;
            this.sourceLoaded = true;
            this.source = line;

            if (callback)
                callback(line);
        });
    },

    getSourceLink: function()
    {
        var ext = this.category == "css" ? "css" : "js";
        return this.lineNo ? new SourceLink(this.href, this.lineNo, ext,
            null, null, this.colNumber) : null;
    },

    resetSource: function()
    {
        if (this.href && this.lineNo != null)
            this.source = this.getSourceLine();
    },

    correctWithStackTrace: function(trace)
    {
        var frame = trace.frames[0];
        if (frame)
        {
            this.href = frame.href;
            this.lineNo = parseInt(frame.line, 10);
            this.trace = trace;
        }
    },

    getId: function()
    {
        return this.href + ":" + this.message + ":" + this.lineNo + ":" +
            (this.colNumber ? this.colNumber : "");
    }
};

// ********************************************************************************************* //
// Helper Source Provider

/**
 * Helper source provider used to display source line for errors in case when
 * the Script panel is disabled.
 */
var SourceProvider =
{
    getSourceLine: function(context, url, lineNo, callback)
    {
        TraceError.sysout("errorMessageObj.SourceProvider.getSourceLine; " +
            url + " (" + lineNo + ")");

        // Create debugger asynchronously, you can't start debugging when
        // a debuggee script is on the stack.
        context.setTimeout(this.onGetSourceLine.bind(this,
            context, url, lineNo, callback));
    },

    onGetSourceLine: function(context, url, lineNo, callback)
    {
        var dbg = DebuggerLib.makeDebuggerForContext(context);
        if (!dbg)
        {
            TraceError.sysout("errorMessageObj.SourceProvider.onGetSourceLine; " +
                "ERROR no debugger");
            return;
        }

        var scripts = dbg.findScripts({url: url, line: lineNo});
        if (!scripts.length)
        {
            Trace.sysout("errorMessageObj.SourceProvider.onGetSourceLine; " +
                "No script at this location " + url + " (" + lineNo + ")");

            DebuggerLib.destroyDebuggerForContext(context, dbg);
            return;
        }

        // xxxHonza: sometimes the top level script is not found (only child script) :-(
        var script = scripts[0];
        var startLine = script.startLine;
        var lines = Str.splitLines(script.source.text);

        Trace.sysout("errorMessageObj.SourceProvider.onGetSourceLine; scripts", scripts);

        // Don't forge to destroy the debugger.
        DebuggerLib.destroyDebuggerForContext(context, dbg);

        // Get particular line of the source code.
        var index = lineNo - startLine;
        if (index < 0 || index >= lines.length)
        {
            Trace.sysout("errorMessageObj.SourceProvider.onGetSourceLine; Line " + lineNo +
                " is out of range " + lines.length, source);
            return;
        }

        var line = lines[index];

        Trace.sysout("errorMessageObj.SourceProvider.onGetSourceLine; " +
            "return source for line: " + lineNo + ", index: " + index +
            ", source start: " + script.startLine, script.source.text);

        if (callback)
            callback(line);

        // Dispatch event with fake sourceFile object as an argument, so the UI
        // (mainly the Console UI) can be updated and the source displayed.
        // See e.g. {@link ErrorMessageUpdater}
        var sourceFile = {
            context: context,
            href: url,
            loaded: true,
            lines: lines,
            isBlackBoxed: false,
        };

        Events.dispatch(Firebug.modules, "onUpdateErrorObject", [sourceFile]);

        return line;
    },
}

// ********************************************************************************************* //
// Registration

return ErrorMessageObj;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>'use strict';
var http = require('http');
var port = 3001;

var routeMap = {};
var routeSupport = ['get', 'post', 'put', 'delete'];

var ROOT_ENDPOINT = /^\/$/i;
var API_ENDPOINT = /\/api/i;
var COLON_TOKEN = /(:\w+)/gi;
var COLON_REPLACE = '(' + '\\' + 'w+)';

var print = function(message) {
  console.log([new Date(), message].join(':: '));
};

var requestIsRoot = function(req) {
  return req.length === 0 || req.url.match(ROOT_ENDPOINT);
};

var requestIsAPIRoute = function(req) {
  return req.method.toLowerCase() === 'post' && req.url.match(API_ENDPOINT);
};

var isValidInt = function(value) {
  var n = parseInt(value, 10);
  return !isNaN(n) && value % 1 === 0;
};

var validateStatusCode = function(value) {
  // Enhancement: Validate as proper HTTP status code.
  return isValidInt(value) ? parseInt(value, 10) : Number.NaN;
};

var validateDelay = function(value) {
  // Enhancement: Validate as proper timespan.
  return isValidInt(value) ? parseInt(value, 10) : Number.NaN;
};

var tokenizeURI = function(uri) {
  return '^' + uri.replace(COLON_TOKEN, COLON_REPLACE);
};

var addRoute = function(route) {
  var normalizedMethod = route.method.toLowerCase();
  if(routeMap.hasOwnProperty(normalizedMethod)) {
    route.regex = new RegExp(tokenizeURI(route.uri));
    route.match = function(uri) {
      return uri.match(this.regex);
    };
    routeMap[normalizedMethod].push(route);
  }
};

var findRouteFromRequest = function(req) {
  var routeList = routeMap[req.method.toLowerCase()];
  var route;
  var index;
  if(routeList) {
    index = routeList.length;
    while(--index > -1) {
      route = routeList[index];
      if(route.match(req.url)) {
        return route;
      }
    }
  }
  return undefined;
};

var establishRouteMap = function() {
  while(routeSupport.length > 0) {
    routeMap[routeSupport.shift()] = [];
  }
};

var server = http.createServer(function(request, response) {
  var data = '';
  var body;

  // Cross Domain.
  response.setHeader('Access-Control-Allow-Origin', '*');
  response.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  request.setEncoding('utf8');
  request.on('data', function(chunk) {
    data += chunk;
  });

  if(request.method === 'OPTIONS') {
    request.on('end', function() {
      response.writeHead(200);
      response.end('\n');
      print('OPTIONS request.');
    });
  }
  else if(requestIsRoot(request)) {
    request.on('end', function() {
      body = JSON.stringify({result: 'hello, caddis!'}) + '\n';
      response.writeHead(200, {
        'Content-Type': 'application/json',
        'Content-Length': body.length
      });
      response.end(body);
      print('Root request.');
    });
  }
  else if(requestIsAPIRoute(request)) {
    request.on('end', function() {
      var route = JSON.parse(data);
      addRoute(route);
      body = JSON.stringify({result: true}) + '\n';
      response.writeHead(200, {
        'Content-Type': 'application/json',
        'Content-Length': body.length
      });
      response.end(body);
      print('Route added to ' + route.method + '.');
      print(JSON.stringify(route, null, 2));
    });
  }
  else {
    request.on('end', function() {
      var route;
      var delay;
      var statusCode;
      var timeout;
      var respond;

      route = findRouteFromRequest(request);
      if(route !== undefined) {
        delay = validateDelay(route.delay);
        statusCode = validateStatusCode(route.status);
        body = JSON.stringify(route.response) + '\n';
        respond = function() {
            response.writeHead(!isNaN(statusCode) ? statusCode : 200, {
              'Content-Type': 'application/json',
              'Content-Length': body.length
            });
          response.end(body);
        };
        print('Stored route found.');
        print('Returning: ' + body +
                    'after ' + (!isNaN(delay) ? delay : 0) +
                    ' milliseconds with status ' + (!isNaN(statusCode) ? statusCode : 200));
        if(!isNaN(delay)) {
          timeout = setTimeout(function() {
            clearTimeout(timeout);
            respond();
          }, delay);
        }
        else {
          respond();
        }
      }
      else {
        body = JSON.stringify({
          message: request.url + ' not implemented.'
        }) + '\n';
        response.writeHead(501, {
          'Content-Type': 'application/json',
          'Content-Length': body.length
        });
        response.end(body);
      }
    });
  }
});

establishRouteMap();
server.listen(port);

print(new Date() + ':: Caddis started on port ' + port + '.');<commit_msg>proper temrination on regex matching for uri on add route.<commit_after>'use strict';
var http = require('http');
var port = 3001;

var routeMap = {};
var routeSupport = ['get', 'post', 'put', 'delete'];

var ROOT_ENDPOINT = /^\/$/i;
var API_ENDPOINT = /\/api/i;
var COLON_TOKEN = /(:\w+)/gi;
var COLON_REPLACE = '(' + '\\' + 'w+)';

var print = function(message) {
  console.log([new Date(), message].join(':: '));
};

var requestIsRoot = function(req) {
  return req.length === 0 || req.url.match(ROOT_ENDPOINT);
};

var requestIsAPIRoute = function(req) {
  return req.method.toLowerCase() === 'post' && req.url.match(API_ENDPOINT);
};

var isValidInt = function(value) {
  var n = parseInt(value, 10);
  return !isNaN(n) && value % 1 === 0;
};

var validateStatusCode = function(value) {
  // Enhancement: Validate as proper HTTP status code.
  return isValidInt(value) ? parseInt(value, 10) : Number.NaN;
};

var validateDelay = function(value) {
  // Enhancement: Validate as proper timespan.
  return isValidInt(value) ? parseInt(value, 10) : Number.NaN;
};

var tokenizeURI = function(uri) {
  return '^' + uri.replace(COLON_TOKEN, COLON_REPLACE) + '$';
};

var addRoute = function(route) {
  var normalizedMethod = route.method.toLowerCase();
  if(routeMap.hasOwnProperty(normalizedMethod)) {
    route.regex = new RegExp(tokenizeURI(route.uri));
    route.match = function(uri) {
      return uri.match(this.regex);
    };
    routeMap[normalizedMethod].push(route);
  }
};

var findRouteFromRequest = function(req) {
  var routeList = routeMap[req.method.toLowerCase()];
  var route;
  var index;
  if(routeList) {
    index = routeList.length;
    while(--index > -1) {
      route = routeList[index];
      if(route.match(req.url)) {
        return route;
      }
    }
  }
  return undefined;
};

var establishRouteMap = function() {
  while(routeSupport.length > 0) {
    routeMap[routeSupport.shift()] = [];
  }
};

var server = http.createServer(function(request, response) {
  var data = '';
  var body;

  // Cross Domain.
  response.setHeader('Access-Control-Allow-Origin', '*');
  response.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  request.setEncoding('utf8');
  request.on('data', function(chunk) {
    data += chunk;
  });

  if(request.method === 'OPTIONS') {
    request.on('end', function() {
      response.writeHead(200);
      response.end('\n');
      print('OPTIONS request.');
    });
  }
  else if(requestIsRoot(request)) {
    request.on('end', function() {
      body = JSON.stringify({result: 'hello, caddis!'}) + '\n';
      response.writeHead(200, {
        'Content-Type': 'application/json',
        'Content-Length': body.length
      });
      response.end(body);
      print('Root request.');
    });
  }
  else if(requestIsAPIRoute(request)) {
    request.on('end', function() {
      var route = JSON.parse(data);
      addRoute(route);
      body = JSON.stringify({result: true}) + '\n';
      response.writeHead(200, {
        'Content-Type': 'application/json',
        'Content-Length': body.length
      });
      response.end(body);
      print('Route added to ' + route.method + '.');
      print(JSON.stringify(route, null, 2));
    });
  }
  else {
    request.on('end', function() {
      var route;
      var delay;
      var statusCode;
      var timeout;
      var respond;

      route = findRouteFromRequest(request);
      if(route !== undefined) {
        delay = validateDelay(route.delay);
        statusCode = validateStatusCode(route.status);
        body = JSON.stringify(route.response) + '\n';
        respond = function() {
            response.writeHead(!isNaN(statusCode) ? statusCode : 200, {
              'Content-Type': 'application/json',
              'Content-Length': body.length
            });
          response.end(body);
        };
        print('Stored route found.');
        print('Returning: ' + body +
                    'after ' + (!isNaN(delay) ? delay : 0) +
                    ' milliseconds with status ' + (!isNaN(statusCode) ? statusCode : 200));
        if(!isNaN(delay)) {
          timeout = setTimeout(function() {
            clearTimeout(timeout);
            respond();
          }, delay);
        }
        else {
          respond();
        }
      }
      else {
        body = JSON.stringify({
          message: request.url + ' not implemented.'
        }) + '\n';
        response.writeHead(501, {
          'Content-Type': 'application/json',
          'Content-Length': body.length
        });
        response.end(body);
      }
    });
  }
});

establishRouteMap();
server.listen(port);

print(new Date() + ':: Caddis started on port ' + port + '.');<|endoftext|>


<commit_before>'use strict';

// Based on Alex Arnell's inheritance implementation.

window.Class = (function () {

	function Subclass() {
		// The base Subclass implementation (does nothing).
	}

	function create() {
		var parent, properties, id;
		id = -1;
		parent = null;
		properties = iterate(arguments);
		if (typeOf(properties[0]) === 'function') {
			parent = properties.shift();
		}
		function Caste() {
			if (typeOf(this.initialize) === 'function') {
				this.initialize.apply(this, arguments);
			}
		}
		Object.extend(Caste, Class.Methods);
		Caste.superclass = parent;
		Caste.subclasses = [];
		if (parent) {
			Subclass.prototype = parent.prototype;
			Caste.prototype = new Subclass;
			parent.subclasses.push(Caste);
		}
		while (++id < properties.length) {
			Caste.implement(properties[id]);
		}
		if (!typeOf(Caste.prototype.initialize)) {
			Caste.prototype.initialize = function () {
				// No Operation
			};
		}
		Caste.prototype.constructor = Caste;
		return Caste;
	}

	function mutate(items) {
		// N/A yet.
	}

	function implement(source) {
		var ancestor, properties, id, property, value, method;
		ancestor = this.superclass && this.superclass.prototype;
		properties = Object.keys(source);
		id = -1;
		if (IS_DONTENUM_BUGGY) {
			if (source.toString != Object.prototype.toString) {
				properties.push('toString');
			}
			if (source.valueOf != Object.prototype.valueOf) {
				properties.push('valueOf');
			}
		}
		while (++id < properties.length) {
			property = properties[id];
			value = source[property];
			if (property === 'implements') {
				if (typeOf(value) === 'function') {
					// N/A yet.
				} else {
					// N/A yet.
				}
			}
			if (ancestor && typeOf(value) === 'function' && /\$super/g.test(value.argumentNames()[0])) {
				method = value;
				value = (function (fn) {
					return function () {
						return ancestor[fn].apply(this, arguments);
					};
				})(property).wrap(method);
				value.valueOf = (function (method) {
					return function () {
						return method.valueOf.call(method);
					};
				})(method);
				value.toString = (function (method) {
					return function () {
						return method.toString.call(method);
					};
				})(method);
			}
			this.prototype[property] = value;
		}
		return this;
	}

	return {
		create: create,
		Methods: {
			extend: Object.extend,
			implement: implement
		}
	};

}());

// Externalize
window.Class.getDefinitionName = getDefinitionName;
window.Class.typeOf = typeOf;
<commit_msg>v0.0.2<commit_after>'use strict';

// Based on Alex Arnell's inheritance implementation.

window.Class = (function () {

	function Subclass() {
		// The base Subclass implementation (does nothing).
	}

	function create() {
		var parent, properties, id;
		id = -1;
		parent = null;
		properties = iterate(arguments);
		if (typeOf(properties[0]) === 'function') {
			parent = properties.shift();
		}
		function Caste() {
			if (typeOf(this.initialize) === 'function') {
				this.initialize.apply(this, arguments);
			}
		}
		Object.extend(Caste, Class.Methods);
		Caste.superclass = parent;
		Caste.subclasses = [];
		if (parent) {
			Subclass.prototype = parent.prototype;
			Caste.prototype = new Subclass;
			parent.subclasses.push(Caste);
		}
		while (++id < properties.length) {
			Caste.implement(properties[id]);
		}
		if (!typeOf(Caste.prototype.initialize)) {
			Caste.prototype.initialize = function () {
				// No Operation
			};
		}
		Caste.prototype.constructor = Caste;
		return Caste;
	}

	function mutate(items) {
		// N/A yet.
	}

	function implement(source) {
		var ancestor, properties, id, property, value, method;
		ancestor = this.superclass && this.superclass.prototype;
		properties = Object.keys(source);
		id = -1;
		if (IS_DONTENUM_BUGGY) {
			if (source.toString != Object.prototype.toString) {
				properties.push('toString');
			}
			if (source.valueOf != Object.prototype.valueOf) {
				properties.push('valueOf');
			}
		}
		while (++id < properties.length) {
			property = properties[id];
			value = source[property];
			if (property === 'implements') {
				if (typeOf(value) === 'function') {
					// N/A yet.
				} else {
					// N/A yet.
				}
			}
			if (ancestor && typeOf(value) === 'function' && /\$super/g.test(value.argumentNames()[0])) {
				method = value;
				value = (function (fn) {
					return function () {
						return ancestor[fn].apply(this, arguments);
					};
				})(property).wrap(method);
				value.valueOf = (function (method) {
					return function () {
						return method.valueOf.call(method);
					};
				})(method);
				value.toString = (function (method) {
					return function () {
						return method.toString.call(method);
					};
				})(method);
			}
			this.prototype[property] = value;
		}
		return this;
	}

	return {
		create: create,
		Methods: {
			extend: Object.extend,
			implement: implement
		}
	};

}());

// Externalize
window.Class.getDefinitionName = getDefinitionName;
window.Class.typeOf = typeOf;
<|endoftext|>


<commit_before>import json from 'rollup-plugin-json';

var path = require('path');
var pkg = require('./package.json');
var external = Object.keys(pkg.dependencies);

function glsl () {
  return {
    transform: function( code, id ) {
      if ( !/\.(glsl|frag|vert)$/.test( id ) ) return;
      var src, key;
      if( path.basename( path.dirname( id ) ) === 'shader' ){
        src = "../globals.js";
        key = "shader/" + path.basename( id );
      }else{
        src = "../../globals.js";
        key = "shader/chunk/" + path.basename( id );
      }
      var registryImport = 'import { ShaderRegistry } from "' + src + '";';
      var shader = JSON.stringify(
        code
          .replace( /[ \t]*\/\/.*\n/g, '' )
          .replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' )
          .replace( /\n{2,}/g, '\n' )
          .replace( /\t/g, ' ' )
          .replace( / {2,}/g, ' ' )
          .replace( / *\n */g, '\n' )
      );
      var register = "ShaderRegistry.add('" + key + "', " + shader + ");";
      return registryImport + register;
    }
  };
}

function text () {
  return {
    transform: function( code, id ) {
      if ( !/\.(txt)$/.test( id ) ) return;
      return 'export default ' + JSON.stringify( code ) + ';';
    }
  };
}

export default {
  entry: 'src/ngl.js',
  plugins: [
    glsl(),
    text(),
    json()
  ],
  external: external,
  targets: [
    {
      dest: "build/js/ngl.dev.js",
      format: 'umd',
      moduleName: 'NGL',
      sourceMap: false
    }
  ]
};<commit_msg>added source map support<commit_after>import json from 'rollup-plugin-json';

var path = require('path');
var pkg = require('./package.json');
var external = Object.keys(pkg.dependencies);

function glsl () {
  return {
    name: "glsl",
    transform: function( code, id ) {
      if ( !/\.(glsl|frag|vert)$/.test( id ) ) return;
      var src, key;
      if( path.basename( path.dirname( id ) ) === 'shader' ){
        src = "../globals.js";
        key = "shader/" + path.basename( id );
      }else{
        src = "../../globals.js";
        key = "shader/chunk/" + path.basename( id );
      }
      var registryImport = 'import { ShaderRegistry } from "' + src + '";';
      var shader = JSON.stringify(
        code
          .replace( /[ \t]*\/\/.*\n/g, '' )
          .replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' )
          .replace( /\n{2,}/g, '\n' )
          .replace( /\t/g, ' ' )
          .replace( / {2,}/g, ' ' )
          .replace( / *\n */g, '\n' )
      );
      var register = "ShaderRegistry.add('" + key + "', " + shader + ");";
      code = registryImport + register;
      return { code: code, map: { mappings: "" } };
    }
  };
}

function text () {
  return {
    name: "text",
    transform: function( code, id ) {
      if ( !/\.(txt)$/.test( id ) ) return;
      code = 'export default ' + JSON.stringify( code ) + ';';
      return { code: code, map: { mappings: "" } };
    }
  };
}

export default {
  entry: 'src/ngl.js',
  plugins: [
    glsl(),
    text(),
    json()
  ],
  external: external,
  targets: [
    {
      dest: "build/js/ngl.dev.js",
      format: 'umd',
      moduleName: 'NGL',
      sourceMap: true
    }
  ]
};<|endoftext|>