<commit_before>// this is mostly the editor implemented by @SergioBenitez for graydon/rust-www
// plus small modifications to accommodate a "Reset" button

// ECMAScript 6 Backwards compatability
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function(str) {
    return this.slice(0, str.length) == str;
  };
}

// Regex for finding new lines
var newLineRegex = /(?:\r\n|\r|\n)/g;

// Fetching DOM items
var activeCode = document.getElementById("active-code");
var editorDiv = document.getElementById("editor");
var resetButton = document.getElementById("reset-code");
var runButton = document.getElementById("run-code");
var resultDiv = document.getElementById("result");

// Background colors for program result on success/error
var successColor = "#E2EEF6";
var errorColor = "#F6E2E2";
var warningColor = "#FFFBCB";

// Error message to return when there's a server failure
var errMsg = "The server encountered an error while running the program.";

// Stores ACE editor markers (highights) for errors
var markers = [];

// Status codes, because there are no enums in Javascript
var SUCCESS = 0;
var ERROR = 1;
var WARNING = 2;

// JS exists, display ACE editor
activeCode.style.display = "block";

// Setting up ace editor
var editor = ace.edit("editor");
var Range = ace.require('ace/range').Range;
editor.setTheme("ace/theme/chrome");
editor.getSession().setMode("ace/mode/rust");
editor.setShowPrintMargin(false);
editor.renderer.setShowGutter(false);
editor.setHighlightActiveLine(false);

// Store original source code
var originalCode = editor.getSession().getValue();

// Changes the height of the editor to match its contents
function updateEditorHeight() {
  // http://stackoverflow.com/questions/11584061/
  var newHeight = editor.getSession().getScreenLength()
    * editor.renderer.lineHeight
    + editor.renderer.scrollBar.getWidth();

  editorDiv.style.height = Math.ceil(newHeight).toString() + "px";
  editor.resize();
};

// Set initial size to match initial content
updateEditorHeight();

function escapeHTML(unsafe) {
  return unsafe
    .replace(/&/g, "&")
    .replace(/</g, "<")
    .replace(/>/g, ">")
    .replace(/"/g, """)
    .replace(/'/g, "'")
    .replace(newLineRegex, '
');
}

// Dispatches a XMLHttpRequest to the Rust playpen, running the program, and
// issues a callback to `callback` with the result (or null on error)
function runProgram(program, callback) {
  var req = new XMLHttpRequest();
  var data = JSON.stringify({
    version: "master",
      optimize: "2",
      code: program
  });

  // console.log("Sending", data);
  req.open('POST', "http://play.rust-lang.org/evaluate.json", true);
  req.onload = function(e) {
    if (req.readyState === 4 && req.status === 200) {
      var result = JSON.parse(req.response).result;

      // Need server support to get an accurate version of this.
      var statusCode = SUCCESS;
      if (result.indexOf("error:") !== -1) {
        statusCode = ERROR;
      } else if (result.indexOf("warning:") !== -1) {
        statusCode = WARNING;
      }

      callback(statusCode, result);
    } else {
      callback(false, null);
    }
  };

  req.onerror = function(e) {
    callback(false, null);
  }

  req.setRequestHeader("Content-Type", "application/json");
  req.send(data);
}

// The callback to runProgram
function handleResult(statusCode, message) {
  // Dispatch depending on result type
  if (result == null) {
    resultDiv.style.backgroundColor = errorColor;
    resultDiv.innerHTML = errMsg;
  } else if (statusCode == SUCCESS) {
    handleSuccess(message);
  } else if (statusCode == WARNING) {
    handleWarning(message);
  } else {
    handleError(message);
  }
}

// Called on successful program run
function handleSuccess(message) {
  resultDiv.style.backgroundColor = successColor;
  resultDiv.innerHTML = escapeHTML(message);
}

// Called when program run results in warning(s)
function handleWarning(message) {
  resultDiv.style.backgroundColor = warningColor;
  handleProblem(message, "warning");
}

// Called when program run results in error(s)
function handleError(message) {
  resultDiv.style.backgroundColor = errorColor;
  handleProblem(message, "error");
}

// Called on unsuccessful program run. Detects and prints problems (either
// warnings or errors) in program output and highlights relevant lines and text
// in the code.
function handleProblem(message, problem) {
  // Getting list of ranges with problems
  var lines = message.split(newLineRegex);

  // Cleaning up the message: keeps only relevant problem output
  var cleanMessage = lines.map(function(line) {
    if (line.startsWith("<anon>") || line.indexOf("^") !== -1) {
      var errIndex = line.indexOf(problem + ": ");
      if (errIndex !== -1) return line.slice(errIndex);
      return "";
    }

    // Discard playpen messages, keep the rest
    if (line.startsWith("playpen:")) return "";
    return line;
  }).filter(function(line) {
    return line !== "";
  }).map(function(line) {
    return escapeHTML(line);
  }).join("
");

  // Setting message
  resultDiv.innerHTML = cleanMessage;

  // Highlighting the lines
  var ranges = parseProblems(lines);
  markers = ranges.map(function(range) {
    return editor.getSession().addMarker(range, "ace-" + problem + "-line",
      "fullLine", false);
  });

  // Highlighting the specific text
  markers = markers.concat(ranges.map(function(range) {
    return editor.getSession().addMarker(range, "ace-" + problem + "-text",
      "text", false);
  }));
}

// Parses a problem message returning a list of ranges (row:col, row:col) where
// problems in the code have occured.
function parseProblems(lines) {
  var ranges = [];
  for (var i in lines) {
    var line = lines[i];
    if (line.startsWith("<anon>:") && line.indexOf(": ") !== -1) {
      var parts = line.split(/:\s?|\s+/, 5).slice(1, 5);
      var ip = parts.map(function(p) { return parseInt(p, 10) - 1; });
      // console.log("line:", line, parts, ip);
      ranges.push(new Range(ip[0], ip[1], ip[2], ip[3]));
    }
  }

  return ranges;
}

// Registering handler for run button click
runButton.addEventListener("click", function(ev) {
  resultDiv.style.display = "block";
  resultDiv.innerHTML = "Running...";

  // clear previous markers, if any
  markers.map(function(id) { editor.getSession().removeMarker(id); });

  // Get the code, run the program
  var program = editor.getValue();
  runProgram(program, handleResult);
});

// Registering handler for reset button click
resetButton.addEventListener("click", function(ev) {
  editor.getSession().setValue(originalCode);
  resultDiv.style.display = "none";
});

// Highlight active line when focused
editor.on('focus', function() {
  editor.setHighlightActiveLine(true);
});

// Don't when not
editor.on('blur', function() {
  editor.setHighlightActiveLine(false);
});
<commit_msg>Fix: editor reinitialization upon navigation<commit_after>// this is mostly the editor implemented by @SergioBenitez for graydon/rust-www
// plus small modifications to accommodate a "Reset" button

// ECMAScript 6 Backwards compatability
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function(str) {
    return this.slice(0, str.length) == str;
  };
}

// Regex for finding new lines
var newLineRegex = /(?:\r\n|\r|\n)/g;

// DOM items
var activeCode;
var editorDiv;
var resetButton;
var runButton;
var resultDiv;

// Background colors for program result on success/error
var successColor = "#E2EEF6";
var errorColor = "#F6E2E2";
var warningColor = "#FFFBCB";

// Error message to return when there's a server failure
var errMsg = "The server encountered an error while running the program.";

// Stores ACE editor markers (highights) for errors
var markers = [];

// Status codes, because there are no enums in Javascript
var SUCCESS = 0;
var ERROR = 1;
var WARNING = 2;

// Ace editor
var editor;
var Range;

// Original source code
var originalCode;

function initEditor()
{
  // Fetching DOM items
  activeCode = document.getElementById("active-code");
  editorDiv = document.getElementById("editor");
  resetButton = document.getElementById("reset-code");
  runButton = document.getElementById("run-code");
  resultDiv = document.getElementById("result");

  if (editorDiv === null)
    return; // No editor on this page

  // Setup ace editor
  editor = ace.edit("editor");
  Range = ace.require('ace/range').Range;

  // JS exists, display ACE editor
  activeCode.style.display = "block";

  editor.setTheme("ace/theme/chrome");
  editor.getSession().setMode("ace/mode/rust");
  editor.setShowPrintMargin(false);
  editor.renderer.setShowGutter(false);
  editor.setHighlightActiveLine(false);

  originalCode = editor.getSession().getValue();

  // Set initial size to match initial content
  updateEditorHeight();

  // Registering handler for run button click
  runButton.addEventListener("click", function(ev) {
    resultDiv.style.display = "block";
    resultDiv.innerHTML = "Running...";

    // clear previous markers, if any
    markers.map(function(id) { editor.getSession().removeMarker(id); });

    // Get the code, run the program
    var program = editor.getValue();
    runProgram(program, handleResult);
  });

  // Registering handler for reset button click
  resetButton.addEventListener("click", function(ev) {
    editor.getSession().setValue(originalCode);
    resultDiv.style.display = "none";
  });

  // Highlight active line when focused
  editor.on('focus', function() {
    editor.setHighlightActiveLine(true);
  });

  // Don't when not
  editor.on('blur', function() {
    editor.setHighlightActiveLine(false);
  });
}

initEditor();

require(["gitbook"], function(gitbook) {
  gitbook.events.bind("page.change", function() {
    initEditor();
  })
});

// Changes the height of the editor to match its contents
function updateEditorHeight() {
  // http://stackoverflow.com/questions/11584061/
  var newHeight = editor.getSession().getScreenLength()
    * editor.renderer.lineHeight
    + editor.renderer.scrollBar.getWidth();

  editorDiv.style.height = Math.ceil(newHeight).toString() + "px";
  editor.resize();
};

function escapeHTML(unsafe) {
  return unsafe
    .replace(/&/g, "&")
    .replace(/</g, "<")
    .replace(/>/g, ">")
    .replace(/"/g, """)
    .replace(/'/g, "'")
    .replace(newLineRegex, '
');
}

// Dispatches a XMLHttpRequest to the Rust playpen, running the program, and
// issues a callback to `callback` with the result (or null on error)
function runProgram(program, callback) {
  var req = new XMLHttpRequest();
  var data = JSON.stringify({
    version: "master",
      optimize: "2",
      code: program
  });

  // console.log("Sending", data);
  req.open('POST', "http://play.rust-lang.org/evaluate.json", true);
  req.onload = function(e) {
    if (req.readyState === 4 && req.status === 200) {
      var result = JSON.parse(req.response).result;

      // Need server support to get an accurate version of this.
      var statusCode = SUCCESS;
      if (result.indexOf("error:") !== -1) {
        statusCode = ERROR;
      } else if (result.indexOf("warning:") !== -1) {
        statusCode = WARNING;
      }

      callback(statusCode, result);
    } else {
      callback(false, null);
    }
  };

  req.onerror = function(e) {
    callback(false, null);
  }

  req.setRequestHeader("Content-Type", "application/json");
  req.send(data);
}

// The callback to runProgram
function handleResult(statusCode, message) {
  // Dispatch depending on result type
  if (result == null) {
    resultDiv.style.backgroundColor = errorColor;
    resultDiv.innerHTML = errMsg;
  } else if (statusCode == SUCCESS) {
    handleSuccess(message);
  } else if (statusCode == WARNING) {
    handleWarning(message);
  } else {
    handleError(message);
  }
}

// Called on successful program run
function handleSuccess(message) {
  resultDiv.style.backgroundColor = successColor;
  resultDiv.innerHTML = escapeHTML(message);
}

// Called when program run results in warning(s)
function handleWarning(message) {
  resultDiv.style.backgroundColor = warningColor;
  handleProblem(message, "warning");
}

// Called when program run results in error(s)
function handleError(message) {
  resultDiv.style.backgroundColor = errorColor;
  handleProblem(message, "error");
}

// Called on unsuccessful program run. Detects and prints problems (either
// warnings or errors) in program output and highlights relevant lines and text
// in the code.
function handleProblem(message, problem) {
  // Getting list of ranges with problems
  var lines = message.split(newLineRegex);

  // Cleaning up the message: keeps only relevant problem output
  var cleanMessage = lines.map(function(line) {
    if (line.startsWith("<anon>") || line.indexOf("^") !== -1) {
      var errIndex = line.indexOf(problem + ": ");
      if (errIndex !== -1) return line.slice(errIndex);
      return "";
    }

    // Discard playpen messages, keep the rest
    if (line.startsWith("playpen:")) return "";
    return line;
  }).filter(function(line) {
    return line !== "";
  }).map(function(line) {
    return escapeHTML(line);
  }).join("
");

  // Setting message
  resultDiv.innerHTML = cleanMessage;

  // Highlighting the lines
  var ranges = parseProblems(lines);
  markers = ranges.map(function(range) {
    return editor.getSession().addMarker(range, "ace-" + problem + "-line",
      "fullLine", false);
  });

  // Highlighting the specific text
  markers = markers.concat(ranges.map(function(range) {
    return editor.getSession().addMarker(range, "ace-" + problem + "-text",
      "text", false);
  }));
}

// Parses a problem message returning a list of ranges (row:col, row:col) where
// problems in the code have occured.
function parseProblems(lines) {
  var ranges = [];
  for (var i in lines) {
    var line = lines[i];
    if (line.startsWith("<anon>:") && line.indexOf(": ") !== -1) {
      var parts = line.split(/:\s?|\s+/, 5).slice(1, 5);
      var ip = parts.map(function(p) { return parseInt(p, 10) - 1; });
      // console.log("line:", line, parts, ip);
      ranges.push(new Range(ip[0], ip[1], ip[2], ip[3]));
    }
  }

  return ranges;
}
<|endoftext|>


<commit_before>var hours = ['06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00'];

var pikePlace = {
  name: 'Pike Place Market',
  minCustomers: 14,
  maxCustomers: 55,
  avgHourlyCups: 1.2,
  avgHourlyLbs: 3.7,
  totalDailyLbs: 0,
};

var capitolHill = {
  name: 'Capitol Hill',
  minCustomers: 32,
  maxCustomers: 48,
  avgHourlyCups: 3.2,
  avgHourlyLbs: 0.4,
  totalDailyLbs: 0,
};

var seaPublicLibrary = {
  name: 'Seattle Public Library',
  minCustomers: 49,
  maxCustomers: 75,
  avgHourlyCups: 2.6,
  avgHourlyLbs: 30.2,
  totalDailyLbs: 0,
};

var southLakeUnion = {
  name: 'South Lake Union',
  minCustomers: 38,
  maxCustomers: 88,
  avgHourlyCups: 1.3,
  avgHourlyLbs: 3.7,
  totalDailyLbs: 0,
};

var seatacAirport = {
  name: 'Sea-Tac Airport',
  minCustomers: 68,
  maxCustomers: 124,
  avgHourlyCups: 1.1,
  avgHourlyLbs: 2.7,
  totalDailyLbs: 0,
};

var websiteSales = {
  name: 'Website Sales',
  minCustomers: 3,
  maxCustomers: 6,
  avgHourlyCups: 0,
  avgHourlyLbs: 6.7,
  totalDailyLbs: 0,
  hourlyCustomersArray: [],
  hourlyCupsArray: [],
  hourlyTogoLbsArray: [],
  lbsFromCupsArray: [],
  totalHourlyLbsArray: [],
  hourlyCustomers: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCustomersArray.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
    }
  },
  hourlyCups: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCupsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyCups);
    }
  },
  hourlyTogoLbs: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyTogoLbsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyLbs);
    }
  },
  lbsFromCups: function() {
    for (var i = 0; i < hours.length; i++) {
      this.lbsFromCupsArray.push(this.hourlyCupsArray[i] / 20);
    }
  },
  calcTotalHourlyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalHourlyLbsArray.push(this.hourlyTogoLbsArray[i] + this.lbsFromCupsArray[i]);
    }
  },
  calcTotalDailyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalDailyLbs += this.totalHourlyLbsArray[i];
    }
  }
}
<commit_msg>copied arrays and methods to each location<commit_after>var hours = ['06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00'];

var pikePlace = {
  name: 'Pike Place Market',
  minCustomers: 14,
  maxCustomers: 55,
  avgHourlyCups: 1.2,
  avgHourlyLbs: 3.7,
  totalDailyLbs: 0,
  hourlyCustomersArray: [],
  hourlyCupsArray: [],
  hourlyTogoLbsArray: [],
  lbsFromCupsArray: [],
  totalHourlyLbsArray: [],

  hourlyCustomers: function () {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCustomersArray.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
    }
  },
  hourlyCups: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCupsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyCups);
    }
  },
  hourlyTogoLbs: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyTogoLbsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyLbs);
    }
  },
  lbsFromCups: function() {
    for (var i = 0; i < hours.length; i++) {
      this.lbsFromCupsArray.push(this.hourlyCupsArray[i] / 20);
    }
  },
  calcTotalHourlyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalHourlyLbsArray.push(this.hourlyTogoLbsArray[i] + this.lbsFromCupsArray[i]);
    }
  },
  calcTotalDailyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalDailyLbs += this.totalHourlyLbsArray[i];
    }
    return this.totalDailyLbs;
  }
};

var capitolHill = {
  name: 'Capitol Hill',
  minCustomers: 32,
  maxCustomers: 48,
  avgHourlyCups: 3.2,
  avgHourlyLbs: 0.4,
  totalDailyLbs: 0,
  hourlyCustomersArray: [],
  hourlyCupsArray: [],
  hourlyTogoLbsArray: [],
  lbsFromCupsArray: [],
  totalHourlyLbsArray: [],

  hourlyCustomers: function () {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCustomersArray.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
    }
  },
  hourlyCups: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCupsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyCups);
    }
  },
  hourlyTogoLbs: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyTogoLbsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyLbs);
    }
  },
  lbsFromCups: function() {
    for (var i = 0; i < hours.length; i++) {
      this.lbsFromCupsArray.push(this.hourlyCupsArray[i] / 20);
    }
  },
  calcTotalHourlyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalHourlyLbsArray.push(this.hourlyTogoLbsArray[i] + this.lbsFromCupsArray[i]);
    }
  },
  calcTotalDailyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalDailyLbs += this.totalHourlyLbsArray[i];
    }
    return this.totalDailyLbs;
  }
};

var seaPublicLibrary = {
  name: 'Seattle Public Library',
  minCustomers: 49,
  maxCustomers: 75,
  avgHourlyCups: 2.6,
  avgHourlyLbs: 30.2,
  totalDailyLbs: 0,
  hourlyCustomersArray: [],
  hourlyCupsArray: [],
  hourlyTogoLbsArray: [],
  lbsFromCupsArray: [],
  totalHourlyLbsArray: [],

  hourlyCustomers: function () {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCustomersArray.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
    }
  },
  hourlyCups: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCupsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyCups);
    }
  },
  hourlyTogoLbs: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyTogoLbsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyLbs);
    }
  },
  lbsFromCups: function() {
    for (var i = 0; i < hours.length; i++) {
      this.lbsFromCupsArray.push(this.hourlyCupsArray[i] / 20);
    }
  },
  calcTotalHourlyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalHourlyLbsArray.push(this.hourlyTogoLbsArray[i] + this.lbsFromCupsArray[i]);
    }
  },
  calcTotalDailyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalDailyLbs += this.totalHourlyLbsArray[i];
    }
    return this.totalDailyLbs;
  }
};

var southLakeUnion = {
  name: 'South Lake Union',
  minCustomers: 38,
  maxCustomers: 88,
  avgHourlyCups: 1.3,
  avgHourlyLbs: 3.7,
  totalDailyLbs: 0,
  hourlyCustomersArray: [],
  hourlyCupsArray: [],
  hourlyTogoLbsArray: [],
  lbsFromCupsArray: [],
  totalHourlyLbsArray: [],

  hourlyCustomers: function () {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCustomersArray.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
    }
  },
  hourlyCups: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCupsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyCups);
    }
  },
  hourlyTogoLbs: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyTogoLbsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyLbs);
    }
  },
  lbsFromCups: function() {
    for (var i = 0; i < hours.length; i++) {
      this.lbsFromCupsArray.push(this.hourlyCupsArray[i] / 20);
    }
  },
  calcTotalHourlyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalHourlyLbsArray.push(this.hourlyTogoLbsArray[i] + this.lbsFromCupsArray[i]);
    }
  },
  calcTotalDailyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalDailyLbs += this.totalHourlyLbsArray[i];
    }
    return this.totalDailyLbs;
  }
};

var seatacAirport = {
  name: 'Sea-Tac Airport',
  minCustomers: 68,
  maxCustomers: 124,
  avgHourlyCups: 1.1,
  avgHourlyLbs: 2.7,
  totalDailyLbs: 0,
  hourlyCustomersArray: [],
  hourlyCupsArray: [],
  hourlyTogoLbsArray: [],
  lbsFromCupsArray: [],
  totalHourlyLbsArray: [],

  hourlyCustomers: function () {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCustomersArray.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
    }
  },
  hourlyCups: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCupsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyCups);
    }
  },
  hourlyTogoLbs: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyTogoLbsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyLbs);
    }
  },
  lbsFromCups: function() {
    for (var i = 0; i < hours.length; i++) {
      this.lbsFromCupsArray.push(this.hourlyCupsArray[i] / 20);
    }
  },
  calcTotalHourlyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalHourlyLbsArray.push(this.hourlyTogoLbsArray[i] + this.lbsFromCupsArray[i]);
    }
  },
  calcTotalDailyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalDailyLbs += this.totalHourlyLbsArray[i];
    }
    return this.totalDailyLbs;
  }
};

var websiteSales = {
  name: 'Website Sales',
  minCustomers: 3,
  maxCustomers: 6,
  avgHourlyCups: 0,
  avgHourlyLbs: 6.7,
  totalDailyLbs: 0,
  hourlyCustomersArray: [],
  hourlyCupsArray: [],
  hourlyTogoLbsArray: [],
  lbsFromCupsArray: [],
  totalHourlyLbsArray: [],

  hourlyCustomers: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCustomersArray.push(Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
    }
  },
  hourlyCups: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyCupsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyCups);
    }
  },
  hourlyTogoLbs: function() {
    for(var i = 0; i < hours.length; i++) {
      this.hourlyTogoLbsArray.push(this.hourlyCustomersArray[i] * this.avgHourlyLbs);
    }
  },
  lbsFromCups: function() {
    for (var i = 0; i < hours.length; i++) {
      this.lbsFromCupsArray.push(this.hourlyCupsArray[i] / 20);
    }
  },
  calcTotalHourlyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalHourlyLbsArray.push(this.hourlyTogoLbsArray[i] + this.lbsFromCupsArray[i]);
    }
  },
  calcTotalDailyLbs: function() {
    for (var i = 0; i < hours.length; i++) {
      this.totalDailyLbs += this.totalHourlyLbsArray[i];
    }
    return this.totalDailyLbs;
  }
}
<|endoftext|>


<commit_before>'use strict';

angular.module('grudgeApp.services', [])
    .value('version', '0.1');
angular.module('grudgeApp.filters', []);
angular.module('grudgeApp.controllers', []);
angular.module('grudgeApp.directives', []);
angular.module('grudgeApp', [
    'ui.router',
    'grudgeApp.controllers',
    'grudgeApp.filters',
    'grudgeApp.services',
    'grudgeApp.directives'
]).config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/list');
    $stateProvider
        .state('list', {
            url: '/list',
            templateUrl: 'partials/battle_list.html'
        })
        .state('edit', {
            url: '/edit',
            templateUrl: 'partials/battle_edit.html'
        })
        .state('view', {
            url: '/view',
            templateUrl: 'partials/battle_view.html'
        });
});

<commit_msg>Removed edit/view urls.<commit_after>'use strict';

angular.module('grudgeApp.services', [])
    .value('version', '0.1');
angular.module('grudgeApp.filters', []);
angular.module('grudgeApp.controllers', []);
angular.module('grudgeApp.directives', []);
angular.module('grudgeApp', [
    'ui.router',
    'grudgeApp.controllers',
    'grudgeApp.filters',
    'grudgeApp.services',
    'grudgeApp.directives'
]).config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/list');
    $stateProvider
        .state('list', {
            url: '/list',
            templateUrl: 'partials/battle_list.html'
        })
        .state('edit', {
            // url: '/edit',
            templateUrl: 'partials/battle_edit.html'
        })
        .state('view', {
            // url: '/view',
            templateUrl: 'partials/battle_view.html'
        });
});

<|endoftext|>


<commit_before>var Morearty = require('morearty');
var React = window.React = require('react/addons');
var Router = require('director').Router;
var Immutable = require('immutable');

var NOW_SHOWING = Object.freeze({ ALL: 'all', ACTIVE: 'active', COMPLETED: 'completed' });
var currentId = 2;

var App = React.createClass({
  displayName: 'App',

  mixins: [Morearty.Mixin],

  componentDidMount: function () {
    var binding = this.getDefaultBinding();
    Router({
      '/': binding.set.bind(binding, 'nowShowing', NOW_SHOWING.ALL),
      '/active': binding.set.bind(binding, 'nowShowing', NOW_SHOWING.ACTIVE),
      '/completed': binding.set.bind(binding, 'nowShowing', NOW_SHOWING.COMPLETED)
    }).init();
  },

  render: function () {
    var binding = this.getDefaultBinding();
    var _ = React.DOM;
    return  _.section({ id: 'todoapp' },
      Header({ binding: binding }),
      TodoList({ binding: binding }),
      Footer({ binding: binding })
    );
  }
});

var Header = React.createClass({
  displayName: 'Header',
  mixins: [Morearty.Mixin],

  componentDidMount: function () {
    this.refs.newTodo.getDOMNode().focus(); // focus on show
  },

  onAddTodo: function (event) {
    var title = event.target.value;
    if (title) {
      this.getDefaultBinding().update('items', function (todos) { // add new item
        return todos.push(Immutable.Map({
          id: currentId++,
          title: title,
          completed: false,
          editing: false
        }));
      });
      event.target.value = '';
    }
  },

  render: function () {
    var _ = React.DOM;
    return _.header({ id: 'header' },
      _.h1(null, 'todos'),
      _.input({ // requestAnimationFrame-friendly wrapper around input
        id: 'new-todo',
        ref: 'newTodo',
        placeholder: 'What needs to be done?',
        onKeyDown: Morearty.Callback.onEnter(this.onAddTodo)
      })
    );
  }
});

var TodoList = React.createClass({
  displayName: 'TodoList',

  mixins: [Morearty.Mixin],

  onToggleAll: function (event) {
    var completed = event.target.checked;
    this.getDefaultBinding().update('items', function (items) {
      return items.map(function (item) {
        return item.set('completed', completed);
      }).toVector();
    });
  },

  render: function () {
    var binding = this.getDefaultBinding();
    var nowShowing = binding.val('nowShowing');
    var itemsBinding = binding.sub('items');
    var items = itemsBinding.val();

    var isShown = function (item) {
      switch (nowShowing) {
        case NOW_SHOWING.ALL:
          return true;
        case NOW_SHOWING.ACTIVE:
          return !item.get('completed');
        case NOW_SHOWING.COMPLETED:
          return item.get('completed');
      }
    };

    var renderTodo = function (item, index) {
      var itemBinding = itemsBinding.sub(index);
      return isShown(item) ? TodoItem({ binding: itemBinding, key: itemBinding.toJS('id') }) : null;
    };

    var allCompleted = !items.find(function (item) {
      return !item.get('completed');
    });

    var _ = React.DOM;
    var ctx = this.getMoreartyContext();
    return _.section({ id: 'main' },
      items.length ? _.input({ id: 'toggle-all', type: 'checkbox', checked: allCompleted, onChange: this.onToggleAll }) : null,
      _.ul({ id: 'todo-list' },
        items.map(renderTodo).toArray()
      )
    );
  }
});

var TodoItem = React.createClass({
  displayName: 'TodoItem',

  mixins: [Morearty.Mixin],

  componentDidUpdate: function () {
    var ctx = this.getMoreartyContext();
    if (ctx.isChanged(this.getDefaultBinding().sub('editing'))) {
      var node = this.refs.editField.getDOMNode();
      node.focus();
      node.setSelectionRange(0, node.value.length);
    }
  },

  onToggleCompleted: function (event) {
    this.getDefaultBinding().set('completed', event.target.checked);
    return false;
  },

  onToggleEditing: function (editing) {
    this.getDefaultBinding().set('editing', editing);
    return false;
  },

  onEnter: function (event) {
    this.getDefaultBinding().atomically()
      .set('title', event.target.value)
      .set('editing', false)
      .commit();
    return false;
  },

  render: function () {
    var binding = this.getDefaultBinding();
    var item = binding.val();

    var liClass = React.addons.classSet({
      completed: item.get('completed'),
      editing: item.get('editing')
    });
    var title = item.get('title');

    var _ = React.DOM;
    var ctx = this.getMoreartyContext();
    return _.li({ className: liClass },
      _.div({ className: 'view' },
        _.input({
          className: 'toggle',
          type: 'checkbox',
          checked: item.get('completed'),
          onChange: this.onToggleCompleted
        }),
        _.label({ onClick: this.onToggleEditing.bind(null, true) }, title),
        _.button({ className: 'destroy', onClick: binding.delete.bind(binding, '') })
      ),
      _.input({
        className: 'edit',
        ref: 'editField',
        value: title,
        onChange: Morearty.Callback.set(binding, 'title'),
        onKeyDown: Morearty.Callback.onEnter(this.onEnter),
        onBlur: this.onToggleEditing.bind(null, false)
      })
    );
  }
});

var Footer = React.createClass({
  displayName: 'Footer',

  mixins: [Morearty.Mixin],

  onClearCompleted: function () {
    this.getDefaultBinding().update('items', function (items) {
      return items.filter(function (item) {
        return !item.get('completed');
      }).toVector();
    });
  },

  render: function () {
    var binding = this.getDefaultBinding();
    var nowShowing = binding.val('nowShowing');

    var items = binding.val('items');
    var completedItemsCount = items.reduce(function (acc, item) {
      return item.get('completed') ? acc + 1 : acc;
    }, 0);

    var _ = React.DOM;
    return _.footer({ id: 'footer' },
      _.span({ id: 'todo-count' }, items.length - completedItemsCount + ' items left'),
      _.ul({ id: 'filters' },
        _.li(null, _.a({ className: nowShowing === NOW_SHOWING.ALL ? 'selected' : '', href: '#/' }, 'All')),
        _.li(null, _.a({ className: nowShowing === NOW_SHOWING.ACTIVE ? 'selected' : '', href: '#/active' }, 'Active')),
        _.li(null, _.a({ className: nowShowing === NOW_SHOWING.COMPLETED ? 'selected' : '', href: '#/completed' }, 'Completed'))
      ),
      completedItemsCount ?
        _.button({ id: 'clear-completed', onClick: this.onClearCompleted },
            'Clear completed (' + completedItemsCount + ')'
        ) :
        null
    );
  }
});

module.exports = App;
<commit_msg>Revert back RAF-friendly input wrappers.<commit_after>var Morearty = require('morearty');
var React = window.React = require('react/addons');
var Router = require('director').Router;
var Immutable = require('immutable');

var NOW_SHOWING = Object.freeze({ ALL: 'all', ACTIVE: 'active', COMPLETED: 'completed' });
var currentId = 2;

var App = React.createClass({
  displayName: 'App',

  mixins: [Morearty.Mixin],

  componentDidMount: function () {
    var binding = this.getDefaultBinding();
    Router({
      '/': binding.set.bind(binding, 'nowShowing', NOW_SHOWING.ALL),
      '/active': binding.set.bind(binding, 'nowShowing', NOW_SHOWING.ACTIVE),
      '/completed': binding.set.bind(binding, 'nowShowing', NOW_SHOWING.COMPLETED)
    }).init();
  },

  render: function () {
    var binding = this.getDefaultBinding();
    var _ = React.DOM;
    return  _.section({ id: 'todoapp' },
      Header({ binding: binding }),
      TodoList({ binding: binding }),
      Footer({ binding: binding })
    );
  }
});

var Header = React.createClass({
  displayName: 'Header',
  mixins: [Morearty.Mixin],

  componentDidMount: function () {
    this.refs.newTodo.getDOMNode().focus(); // focus on show
  },

  onAddTodo: function (event) {
    var title = event.target.value;
    if (title) {
      this.getDefaultBinding().update('items', function (todos) { // add new item
        return todos.push(Immutable.Map({
          id: currentId++,
          title: title,
          completed: false,
          editing: false
        }));
      });
      event.target.value = '';
    }
  },

  render: function () {
    var _ = React.DOM;
    return _.header({ id: 'header' },
      _.h1(null, 'todos'),
      Morearty.DOM.input({ // requestAnimationFrame-friendly wrapper around input
        id: 'new-todo',
        ref: 'newTodo',
        placeholder: 'What needs to be done?',
        onKeyDown: Morearty.Callback.onEnter(this.onAddTodo)
      })
    );
  }
});

var TodoList = React.createClass({
  displayName: 'TodoList',

  mixins: [Morearty.Mixin],

  onToggleAll: function (event) {
    var completed = event.target.checked;
    this.getDefaultBinding().update('items', function (items) {
      return items.map(function (item) {
        return item.set('completed', completed);
      }).toVector();
    });
  },

  render: function () {
    var binding = this.getDefaultBinding();
    var nowShowing = binding.val('nowShowing');
    var itemsBinding = binding.sub('items');
    var items = itemsBinding.val();

    var isShown = function (item) {
      switch (nowShowing) {
        case NOW_SHOWING.ALL:
          return true;
        case NOW_SHOWING.ACTIVE:
          return !item.get('completed');
        case NOW_SHOWING.COMPLETED:
          return item.get('completed');
      }
    };

    var renderTodo = function (item, index) {
      var itemBinding = itemsBinding.sub(index);
      return isShown(item) ? TodoItem({ binding: itemBinding, key: itemBinding.toJS('id') }) : null;
    };

    var allCompleted = !items.find(function (item) {
      return !item.get('completed');
    });

    var _ = React.DOM;
    var ctx = this.getMoreartyContext();
    return _.section({ id: 'main' },
      items.length ?
        Morearty.DOM.input({ id: 'toggle-all', type: 'checkbox', checked: allCompleted, onChange: this.onToggleAll }) :
        null,
      _.ul({ id: 'todo-list' },
        items.map(renderTodo).toArray()
      )
    );
  }
});

var TodoItem = React.createClass({
  displayName: 'TodoItem',

  mixins: [Morearty.Mixin],

  componentDidUpdate: function () {
    var ctx = this.getMoreartyContext();
    if (ctx.isChanged(this.getDefaultBinding().sub('editing'))) {
      var node = this.refs.editField.getDOMNode();
      node.focus();
      node.setSelectionRange(0, node.value.length);
    }
  },

  onToggleCompleted: function (event) {
    this.getDefaultBinding().set('completed', event.target.checked);
    return false;
  },

  onToggleEditing: function (editing) {
    this.getDefaultBinding().set('editing', editing);
    return false;
  },

  onEnter: function (event) {
    this.getDefaultBinding().atomically()
      .set('title', event.target.value)
      .set('editing', false)
      .commit();
    return false;
  },

  render: function () {
    var binding = this.getDefaultBinding();
    var item = binding.val();

    var liClass = React.addons.classSet({
      completed: item.get('completed'),
      editing: item.get('editing')
    });
    var title = item.get('title');

    var _ = React.DOM;
    var ctx = this.getMoreartyContext();
    return _.li({ className: liClass },
      _.div({ className: 'view' },
        Morearty.DOM.input({
          className: 'toggle',
          type: 'checkbox',
          checked: item.get('completed'),
          onChange: this.onToggleCompleted
        }),
        _.label({ onClick: this.onToggleEditing.bind(null, true) }, title),
        _.button({ className: 'destroy', onClick: binding.delete.bind(binding, '') })
      ),
      Morearty.DOM.input({
        className: 'edit',
        ref: 'editField',
        value: title,
        onChange: Morearty.Callback.set(binding, 'title'),
        onKeyDown: Morearty.Callback.onEnter(this.onEnter),
        onBlur: this.onToggleEditing.bind(null, false)
      })
    );
  }
});

var Footer = React.createClass({
  displayName: 'Footer',

  mixins: [Morearty.Mixin],

  onClearCompleted: function () {
    this.getDefaultBinding().update('items', function (items) {
      return items.filter(function (item) {
        return !item.get('completed');
      }).toVector();
    });
  },

  render: function () {
    var binding = this.getDefaultBinding();
    var nowShowing = binding.val('nowShowing');

    var items = binding.val('items');
    var completedItemsCount = items.reduce(function (acc, item) {
      return item.get('completed') ? acc + 1 : acc;
    }, 0);

    var _ = React.DOM;
    return _.footer({ id: 'footer' },
      _.span({ id: 'todo-count' }, items.length - completedItemsCount + ' items left'),
      _.ul({ id: 'filters' },
        _.li(null, _.a({ className: nowShowing === NOW_SHOWING.ALL ? 'selected' : '', href: '#/' }, 'All')),
        _.li(null, _.a({ className: nowShowing === NOW_SHOWING.ACTIVE ? 'selected' : '', href: '#/active' }, 'Active')),
        _.li(null, _.a({ className: nowShowing === NOW_SHOWING.COMPLETED ? 'selected' : '', href: '#/completed' }, 'Completed'))
      ),
      completedItemsCount ?
        _.button({ id: 'clear-completed', onClick: this.onClearCompleted },
            'Clear completed (' + completedItemsCount + ')'
        ) :
        null
    );
  }
});

module.exports = App;
<|endoftext|>


<commit_before>

$(document).ready(function() {

  $( "input[data-olswidget='multisearch']" ).each(function() {

    var relativePath = $(this).data("selectpath") ? $(this).data("selectpath") : '';
    var ontology =   $(this).data("olsontology") ? $(this).data("olsontology") : '';
    var type =   $(this).data("olstype") ? $(this).data("olstype") : '';

    var source = [{
                name: 'suggestion',
                source: getSuggestHound(relativePath),
                display: 'value'
              },
              {
                name: 'selection',
                source: getSelectHound(relativePath, ontology, type),
                display: 'value',
                templates: getSuggestTemplate()
              }];
    createTypeAhead($(this), relativePath, source);
  });

  $( "input[data-olswidget='select']" ).each(function() {

    var relativePath = $(this).data("selectpath") ? $(this).data("selectpath") : '';
    var ontology =   $(this).data("olsontology") ? $(this).data("olsontology") : '';
    var type =   $(this).data("olstype") ? $(this).data("olstype") : '';

    var source = [
              {
                name: 'selection',
                source: getSelectHound(relativePath, ontology, type),
                display: 'value',
                templates: getSuggestTemplate()
              }];
    createTypeAhead($(this), relativePath, source);
  });

});

function createTypeAhead (element, relativePath, source) {

  element.bind('typeahead:select', function(ev, suggestion) {

        if (suggestion.data != undefined) {
          var type = getUrlType(suggestion.data.type);
          if (type=='ontology') {
            window.location.href = relativePath + 'ontologies/' + suggestion.data.ontology;
          }
          else {
            var encoded = encodeURIComponent(suggestion.data.iri);
            window.location.href = relativePath + 'ontologies/' + suggestion.data.ontology + "/" + type + '?iri=' + encoded;
          }
        }
        else {
          ev.target.form.submit();
        }
      })
      .typeahead({
            hint: false,
            highlight: true,
            minLength: 3,
            limit: 4,
            async: true,

          },
          source
      ).focus()

}

function getSuggestTemplate () {

  return {
    header: '

Jump to
',
    suggestion: function(suggestion) {

      var label = suggestion.data.label ;

      var extra = "";
      if (suggestion.data.synonym != "") {
        label =  suggestion.data.synonym;
        extra = "
synonym for " + suggestion.value + "
"
      }

      var objectTypeHtml = "
" + suggestion.data.prefix + "
"
      var type = getUrlType(suggestion.data.type);

      if (type != 'ontology') {
        objectTypeHtml+="
" + suggestion.data.shortForm + "
";

      }

      return "

" + label + "
" + extra + "

" + objectTypeHtml + "

";

      //Handlebars.compile('
{{value}} – {{data.ontology}}
');

    },
    footer:  Handlebars.compile('

Search OLS for {{query}}
')

  };
}

function getSelectHound (relativePath, ontology, type) {

  var ontologyParam ='';
  if (ontology) {
    ontologyParam = '&ontology=' + ontology;
  }
  if (type) {
    ontologyParam += '&type=' + type;
  }
  return new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    identify: function(obj) { return obj.id; },
    remote: {
      url: relativePath + 'api/select?q=%QUERY' + ontologyParam,
      wildcard: "%QUERY",
      transform: function (response) {
          return selectResponse(response)
      }
    }
  });

}

function getSuggestHound (relativePath) {
  return new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: relativePath + 'api/suggest?q=%QUERY',
      wildcard: "%QUERY",
      transform: function (response) {
        // Map the remote source JSON array to a JavaScript object array
        return $.map(response.response.docs, function (dataItem) {
          return {
            value: dataItem.autosuggest
          };
        });
      }
    }
  });
}

function selectResponse (response) {
  // Map the remote source JSON array to a JavaScript object array
  var query = response.responseHeader.params.q;
  return $.map(response.response.docs, function (dataItem) {

    var id =   dataItem.id;

    var label = dataItem.label;

    var synonym = "";
    var cantHighlight = true;
    if (response.highlighting[id].label_autosuggest != undefined) {
      label = response.highlighting[id].label_autosuggest[0];
      cantHighlight = false;

    }
    else if (response.highlighting[id].label != undefined) {
      label = response.highlighting[id].label[0];
      cantHighlight = false;

    }

    if (cantHighlight) {
      if (response.highlighting[id].synonym_autosuggest != undefined) {
        synonym = response.highlighting[id].synonym_autosuggest[0];
      }
      else if (response.highlighting[id].synonym != undefined) {
        synonym = response.highlighting[id].synonym[0];
      }
    }

    var shortId = dataItem.obo_id;
    if (shortId == undefined) {
      shortId = dataItem.short_form;
    }
    return {
      id: id,
      value: dataItem.label,
      data: {ontology: dataItem.ontology_name, prefix: dataItem.ontology_prefix, iri : dataItem.iri, label: label,synonym: synonym, shortForm: shortId, type: dataItem.type},
      query: query
    };
  });
}

// constructs the suggestion engine
<commit_msg>small fix to make autocmplete footer clickable<commit_after>

$(document).ready(function() {

  $( "input[data-olswidget='multisearch']" ).each(function() {

    var relativePath = $(this).data("selectpath") ? $(this).data("selectpath") : '';
    var ontology =   $(this).data("olsontology") ? $(this).data("olsontology") : '';
    var type =   $(this).data("olstype") ? $(this).data("olstype") : '';

    var source = [{
                name: 'suggestion',
                source: getSuggestHound(relativePath),
                display: 'value'
              },
              {
                name: 'selection',
                source: getSelectHound(relativePath, ontology, type),
                display: 'value',
                templates: getSuggestTemplate()
              }];
    createTypeAhead($(this), relativePath, source);
  });

  $( "input[data-olswidget='select']" ).each(function() {

    var relativePath = $(this).data("selectpath") ? $(this).data("selectpath") : '';
    var ontology =   $(this).data("olsontology") ? $(this).data("olsontology") : '';
    var type =   $(this).data("olstype") ? $(this).data("olstype") : '';

    var source = [
              {
                name: 'selection',
                source: getSelectHound(relativePath, ontology, type),
                display: 'value',
                templates: getSuggestTemplate()
              }];
    createTypeAhead($(this), relativePath, source);
  });

});

function createTypeAhead (element, relativePath, source) {

  element.bind('typeahead:select', function(ev, suggestion) {

        if (suggestion.data != undefined) {
          var type = getUrlType(suggestion.data.type);
          if (type=='ontology') {
            window.location.href = relativePath + 'ontologies/' + suggestion.data.ontology;
          }
          else {
            var encoded = encodeURIComponent(suggestion.data.iri);
            window.location.href = relativePath + 'ontologies/' + suggestion.data.ontology + "/" + type + '?iri=' + encoded;
          }
        }
        else {
          ev.target.form.submit();
        }
      })
      .typeahead({
            hint: false,
            highlight: true,
            minLength: 3,
            limit: 4,
            async: true,

          },
          source
      ).focus()

}

function getSuggestTemplate () {

  return {
    header: '

Jump to
',
    suggestion: function(suggestion) {

      var label = suggestion.data.label ;

      var extra = "";
      if (suggestion.data.synonym != "") {
        label =  suggestion.data.synonym;
        extra = "
synonym for " + suggestion.value + "
"
      }

      var objectTypeHtml = "
" + suggestion.data.prefix + "
"
      var type = getUrlType(suggestion.data.type);

      if (type != 'ontology') {
        objectTypeHtml+="
" + suggestion.data.shortForm + "
";

      }

      return "

" + label + "
" + extra + "

" + objectTypeHtml + "

";

      //Handlebars.compile('
{{value}} – {{data.ontology}}
');

    },
    footer:  Handlebars.compile('

Search OLS for {{query}}
')

  };
}

function getSelectHound (relativePath, ontology, type) {

  var ontologyParam ='';
  if (ontology) {
    ontologyParam = '&ontology=' + ontology;
  }
  if (type) {
    ontologyParam += '&type=' + type;
  }
  return new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    identify: function(obj) { return obj.id; },
    remote: {
      url: relativePath + 'api/select?q=%QUERY' + ontologyParam,
      wildcard: "%QUERY",
      transform: function (response) {
          return selectResponse(response)
      }
    }
  });

}

function getSuggestHound (relativePath) {
  return new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: relativePath + 'api/suggest?q=%QUERY',
      wildcard: "%QUERY",
      transform: function (response) {
        // Map the remote source JSON array to a JavaScript object array
        return $.map(response.response.docs, function (dataItem) {
          return {
            value: dataItem.autosuggest
          };
        });
      }
    }
  });
}

function selectResponse (response) {
  // Map the remote source JSON array to a JavaScript object array
  var query = response.responseHeader.params.q;
  return $.map(response.response.docs, function (dataItem) {

    var id =   dataItem.id;

    var label = dataItem.label;

    var synonym = "";
    var cantHighlight = true;
    if (response.highlighting[id].label_autosuggest != undefined) {
      label = response.highlighting[id].label_autosuggest[0];
      cantHighlight = false;

    }
    else if (response.highlighting[id].label != undefined) {
      label = response.highlighting[id].label[0];
      cantHighlight = false;

    }

    if (cantHighlight) {
      if (response.highlighting[id].synonym_autosuggest != undefined) {
        synonym = response.highlighting[id].synonym_autosuggest[0];
      }
      else if (response.highlighting[id].synonym != undefined) {
        synonym = response.highlighting[id].synonym[0];
      }
    }

    var shortId = dataItem.obo_id;
    if (shortId == undefined) {
      shortId = dataItem.short_form;
    }
    return {
      id: id,
      value: dataItem.label,
      data: {ontology: dataItem.ontology_name, prefix: dataItem.ontology_prefix, iri : dataItem.iri, label: label,synonym: synonym, shortForm: shortId, type: dataItem.type},
      query: query
    };
  });
}

// constructs the suggestion engine
<|endoftext|>


<commit_before>/*global define*/
define(['underscore', 'oroentity/js/field-choice', 'oroui/js/mediator', 'orotranslation/js/translator'],
    function (_, $, mediator, __) {
        'use strict';

        /**
         * @export ororeport/js/chart_options
         * @class  ororeport.ChartOptions
         */
        return {

            /**
             * @property {Object}
             */
            options: {
                childTemplate: '[id^=<%= id %>_]',
                fieldChoiceOptions: {
                    select2: {
                        placeholder: __('oro.entity.form.choose_entity_field')
                    },
                    util: {},
                    exclude: [],
                    fields: []
                },
                fieldsLoaderSelector: '#oro_report_form_entity',
                events: [
                    'items-manager:table:add',
                    'items-manager:table:change',
                    'items-manager:table:remove',
                    'items-manager:table:reset'
                ]
            },

            /**
             * @param {String} id
             * @param {Array} options
             */
            initialize: function (id, options) {
                var self = this;
                this.options = _.extend({}, this.options, options);

                _.each(this.options.events, function (event) {
                    mediator.on(event, function (collection) {
                        self.updateFields(collection);

                        self.updateFilters(id);
                    });
                });
            },

            /**
             * @param {String} id
             */
            updateFilters: function (id) {
                var self = this;
                var childSelector = _.template(self.options.childTemplate, {id: id});
                var items = $('#' + id).find(childSelector);

                _.each(items, function (item) {
                    self.options.fieldChoiceOptions.exclude = $(item).data('type-filter');
                    $(item).fieldChoice(self.options.fieldChoiceOptions);
                });
            },

            /**
             * @param {Array} collection
             */
            updateFields: function (collection) {
                var self = this;
                var fieldsList = $(self.options.fieldsLoaderSelector).fieldsLoader('getFieldsData');

                self.options.fieldChoiceOptions.fields = [];
                _.each(collection.models, function (model) {
                    var name = model.get('name');
                    self._addFieldByPath(fieldsList, self.options.fieldChoiceOptions.fields, name);
                });
            },

            /**
             * @param {Array} fields
             * @param {Array} root
             * @param {String} name
             */
            _addFieldByPath: function (fields, root, name) {
                var self = this;
                var chain = name.split('+');
                var fieldName = _.last(_.first(chain).split('::'));

                var field = _.findWhere(fields, {name: fieldName});
                if (field) {
                    var rootField = _.findWhere(root, {name: fieldName});
                    if (!rootField) {
                        rootField = _.clone(field);
                        rootField.related_entity_fields = [];

                        root.push(rootField);
                    }

                    if (chain.length > 1) {
                        var childName = _.rest(chain).join('+');
                        self._addFieldByPath(
                            field.related_entity_fields,
                            rootField.related_entity_fields,
                            childName
                        );
                    }
                }
            }
        };
    });
<commit_msg>BAP-4130: Add possibility to filter chart data schema columns by supported types - store functions<commit_after>/*global define*/
define(['underscore', 'oroentity/js/field-choice', 'oroui/js/mediator', 'orotranslation/js/translator'],
    function (_, $, mediator, __) {
        'use strict';

        /**
         * @export ororeport/js/chart_options
         * @class  ororeport.ChartOptions
         */
        return {

            /**
             * @property {Object}
             */
            options: {
                childTemplate: '[id^=<%= id %>_]',
                optionsTemplate: '<%= field %>(<%= group %>,<%= name %>,<%= type %>)',
                fieldChoiceOptions: {
                    select2: {
                        placeholder: __('oro.entity.form.choose_entity_field')
                    },
                    util: {},
                    exclude: [],
                    fields: []
                },
                fieldsLoaderSelector: '#oro_report_form_entity',
                events: [
                    'items-manager:table:add',
                    'items-manager:table:change',
                    'items-manager:table:remove',
                    'items-manager:table:reset'
                ]
            },

            /**
             * @param {String} id
             * @param {Array} options
             */
            initialize: function (id, options) {
                var self = this;
                this.options = _.extend({}, this.options, options);

                _.each(this.options.events, function (event) {
                    mediator.on(event, function (collection) {
                        self.updateFields(collection);

                        self.updateFilters(id);
                    });
                });
            },

            /**
             * @param {String} id
             */
            updateFilters: function (id) {
                var self = this;
                var childSelector = _.template(self.options.childTemplate, {id: id});
                var items = $('#' + id).find(childSelector);

                _.each(items, function (item) {
                    self.options.fieldChoiceOptions.exclude = $(item).data('type-filter');
                    $(item).fieldChoice(self.options.fieldChoiceOptions);
                });
            },

            /**
             * @param {Array} collection
             */
            updateFields: function (collection) {
                var self = this;
                var fieldsList = $(self.options.fieldsLoaderSelector).fieldsLoader('getFieldsData');

                self.options.fieldChoiceOptions.fields = [];
                _.each(collection.models, function (model) {
                    var name = model.get('name');
                    var options = model.get('func');
                    self._addFieldByPath(fieldsList, self.options.fieldChoiceOptions.fields, name, options);
                });
            },

            /**
             * @param {Array} fields
             * @param {Array} root
             * @param {String} name
             * @param {Array} options
             */
            _addFieldByPath: function (fields, root, name, options) {
                var self = this;
                var chain = name.split('+');
                var fieldName = _.last(_.first(chain).split('::'));
                var lastFieldName = _.last(_.last(chain).split('::'));
                var hasOptions = fieldName == lastFieldName;

                var field = _.findWhere(fields, {name: fieldName});
                if (field) {
                    var rootField = _.findWhere(root, {name: fieldName});
                    if (!rootField) {
                        rootField = _.clone(field);
                        rootField.related_entity_fields = [];

                        if (options && hasOptions) {
                            var optionedName = _.template(
                                self.options.optionsTemplate,
                                {
                                    field: rootField.name,
                                    group: options.name,
                                    name: options.group_name,
                                    type: options.group_type
                                }
                            );

                            rootField.name = optionedName;
                        }

                        root.push(rootField);
                    }

                    if (chain.length > 1) {
                        var childName = _.rest(chain).join('+');
                        self._addFieldByPath(
                            field.related_entity_fields,
                            rootField.related_entity_fields,
                            childName,
                            options
                        );
                    }
                }
            }
        };
    });
<|endoftext|>


<commit_before>(function (window, document, undefined) {

  util = {};

  util.emptyNode = function emptyNode(node) {
    while (node.firstChild) {
      node.removeChild(node.firstChild);
    }
  };

  window.util = util;

}(window, document));

(function (util) {

  // <chart-pie> demo
  var showPie = function showPie(e) {
    if (Boolean(e.fragment.getAttribute('data-pie'))) {
      var slide = Reveal.getCurrentSlide();
      var pie = document.createElement('chart-pie');
      slide.appendChild(pie);
      Reveal.removeEventListener('fragmentshown', showPie);
    }
  };

  Reveal.addEventListener('fragmentshown', showPie);

  var demos = {};

  demos.template = function template() {
    var section = Reveal.getCurrentSlide();
    var template = section.querySelector('#my-widget');
    template.content.querySelector('img').src = 'http://localhost:3000/img/corgi.gif';
    section.appendChild(template.content.cloneNode(true));
  };

  demos.shadowRoot = function shadowRoot() {
    var section = Reveal.getCurrentSlide();
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.innerHTML = 'I\'m inside yr div!';
  };

  demos.styleEncapsulation = function styleEncapsulation() {
    var section = document.querySelector('#demo-style-encapsulation');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.styleEncapsulation();

  demos.doAuthorStyles = true;
  demos.applyAuthorStyles = function applyAuthorStyles() {
    var section = document.querySelector('#demo-applyAuthorStyles');
    var output = section.querySelector('#isAuthorStyles');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    util.emptyNode(root);
    this.doAuthorStyles = !this.doAuthorStyles;
    root.applyAuthorStyles = this.doAuthorStyles;
    output.textContent = this.doAuthorStyles;
    root.appendChild(template.content.cloneNode(true));
  };
  demos.applyAuthorStyles();

  demos.doResetStyles = true;
  demos.resetStyleInheritance = function resetStyleInheritance() {
    var section = document.querySelector('#demo-resetStyleInheritance');
    var output = section.querySelector('#isStyleInheritance');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    util.emptyNode(root);
    this.doResetStyles = !this.doResetStyles;
    root.resetStyleInheritance = this.doResetStyles;
    output.textContent = this.doResetStyles;
    root.appendChild(template.content.cloneNode(true));
  };
  demos.resetStyleInheritance();

  demos.parts = function parts() {
    var section = document.querySelector('#demo-parts');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.parts();

  demos.hostStyle = function hostStyle() {
    var section = document.querySelector('#demo-host');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget-borderless');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.hostStyle();

  demos.theming = function theming() {
    var section = document.querySelector('#demo-theming');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.theming();

  demos.customProps = function customProps() {
    var section = document.querySelector('#demo-custom-props');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.customProps();

  demos.insertionPoints = function insertionPoints() {
    var section = document.querySelector('#demo-insertion-points');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget .pokemon');
    host.classList.remove('hidden');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
    // var jigglypuff = section.querySelector('.jigglypuff');
    // setTimeout(function() {
    //   jigglypuff.classList.add('in');
    // }, 2000);
  };
  demos.insertionPoints();

  demos.select = function select() {
    var section = document.querySelector('#demo-select');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.select();

  // demos.retargetedEvents = function retargetedEvents() {
  //   var section = document.querySelector('#demo-retargeted-events');
  //   var clickable = section.querySelector('.clickable');
  //   var template = section.querySelector('template');
  //   var host = section.querySelector('.widget #host');
  //   var root = host.createShadowRoot();
  //   root.applyAuthorStyles = true;
  //   root.appendChild(template.content.cloneNode(true));

  //   var logElement = function(e) {
  //     alert('#' + e.target.id + ' clicked!');
  //   };

  //   clickable.addEventListener('click', logElement);
  // };
  // demos.retargetedEvents();

  // demos.basicImports = function() {
  //   var section = document.querySelector('#demo-basic-import');
  //   var link = document.querySelector('link[href="./imports/blog-post.html"]');
  //   var template = link.import.querySelector('#blog-post');
  //   var host = section.querySelector('.widget');
  //   host.appendChild(template.content.cloneNode(true));
  // };
  // demos.basicImports();

  window.demos = demos;

}(window.util));

(function () {

  document.addEventListener('keydown', function(e) {
    // Kill keyboard events on slides with text input
    if (e.target.getAttribute('data-disable-events')) {
      e.stopImmediatePropagation();
      return;
    }

    // Make all fragments visible
    if (e.keyCode === 74) { // j key
      var fragments = Reveal.getCurrentSlide().querySelectorAll('.fragment');
      Array.prototype.forEach.call(fragments, function(fragment) {
        fragment.classList.toggle('force-focus');
      });
    }

  }, true);

}());<commit_msg>hacked the charred-trail plugin<commit_after>(function (window, document, undefined) {

  util = {};

  util.emptyNode = function emptyNode(node) {
    while (node.firstChild) {
      node.removeChild(node.firstChild);
    }
  };

  window.util = util;

}(window, document));

(function (util) {

  // <chart-pie> demo
  var showPie = function showPie(e) {
    if (Boolean(e.fragment.getAttribute('data-pie'))) {
      var slide = Reveal.getCurrentSlide();
      var pie = document.createElement('chart-pie');
      slide.appendChild(pie);
      Reveal.removeEventListener('fragmentshown', showPie);
    }
  };

  Reveal.addEventListener('fragmentshown', showPie);

  var demos = {};

  demos.template = function template() {
    var section = Reveal.getCurrentSlide();
    var template = section.querySelector('#my-widget');
    template.content.querySelector('img').src = 'http://localhost:3000/img/corgi.gif';
    section.appendChild(template.content.cloneNode(true));
  };

  demos.shadowRoot = function shadowRoot() {
    var section = Reveal.getCurrentSlide();
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.innerHTML = 'I\'m inside yr div!';
  };

  demos.styleEncapsulation = function styleEncapsulation() {
    var section = document.querySelector('#demo-style-encapsulation');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.styleEncapsulation();

  demos.doAuthorStyles = true;
  demos.applyAuthorStyles = function applyAuthorStyles() {
    var section = document.querySelector('#demo-applyAuthorStyles');
    var output = section.querySelector('#isAuthorStyles');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    util.emptyNode(root);
    this.doAuthorStyles = !this.doAuthorStyles;
    root.applyAuthorStyles = this.doAuthorStyles;
    output.textContent = this.doAuthorStyles;
    root.appendChild(template.content.cloneNode(true));
  };
  demos.applyAuthorStyles();

  demos.doResetStyles = true;
  demos.resetStyleInheritance = function resetStyleInheritance() {
    var section = document.querySelector('#demo-resetStyleInheritance');
    var output = section.querySelector('#isStyleInheritance');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    util.emptyNode(root);
    this.doResetStyles = !this.doResetStyles;
    root.resetStyleInheritance = this.doResetStyles;
    output.textContent = this.doResetStyles;
    root.appendChild(template.content.cloneNode(true));
  };
  demos.resetStyleInheritance();

  demos.parts = function parts() {
    var section = document.querySelector('#demo-parts');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.parts();

  demos.hostStyle = function hostStyle() {
    var section = document.querySelector('#demo-host');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget-borderless');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.hostStyle();

  demos.theming = function theming() {
    var section = document.querySelector('#demo-theming');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.theming();

  demos.customProps = function customProps() {
    var section = document.querySelector('#demo-custom-props');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.customProps();

  demos.insertionPoints = function insertionPoints() {
    var section = document.querySelector('#demo-insertion-points');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget .pokemon');
    host.classList.remove('hidden');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
    // var jigglypuff = section.querySelector('.jigglypuff');
    // setTimeout(function() {
    //   jigglypuff.classList.add('in');
    // }, 2000);
  };
  demos.insertionPoints();

  demos.select = function select() {
    var section = document.querySelector('#demo-select');
    var template = section.querySelector('template');
    var host = section.querySelector('.widget');
    var root = host.createShadowRoot();
    root.appendChild(template.content.cloneNode(true));
  };
  demos.select();

  // demos.retargetedEvents = function retargetedEvents() {
  //   var section = document.querySelector('#demo-retargeted-events');
  //   var clickable = section.querySelector('.clickable');
  //   var template = section.querySelector('template');
  //   var host = section.querySelector('.widget #host');
  //   var root = host.createShadowRoot();
  //   root.applyAuthorStyles = true;
  //   root.appendChild(template.content.cloneNode(true));

  //   var logElement = function(e) {
  //     alert('#' + e.target.id + ' clicked!');
  //   };

  //   clickable.addEventListener('click', logElement);
  // };
  // demos.retargetedEvents();

  // demos.basicImports = function() {
  //   var section = document.querySelector('#demo-basic-import');
  //   var link = document.querySelector('link[href="./imports/blog-post.html"]');
  //   var template = link.import.querySelector('#blog-post');
  //   var host = section.querySelector('.widget');
  //   host.appendChild(template.content.cloneNode(true));
  // };
  // demos.basicImports();

  window.demos = demos;

}(window.util));

(function () {

  // This code was written in the wee hours...
  // It is horrible.

  var focusedSlide;

  function focusOn() {
    focusedSlide = Reveal.getCurrentSlide();
    var fragments = focusedSlide.querySelectorAll('.fragment');
    Array.prototype.forEach.call(fragments, function(fragment) {
      fragment.classList.add('force-focus');
    });
    document.addEventListener('keydown', focusOff);
  }

  function focusOff() {
    console.log('focusOff running...');
    var fragments = focusedSlide.querySelectorAll('.fragment');
    Array.prototype.forEach.call(fragments, function(fragment) {
      fragment.classList.remove('force-focus');
    });
    document.removeEventListener('keydown', focusOff);
  }

  Reveal.addEventListener('slidechanged', function(e) {
    // e.previousSlide, e.currentSlide, e.indexh, e.indexv
    var fragments = e.currentSlide.querySelectorAll('.fragment');
    var focusedFragments = e.currentSlide.querySelectorAll('.fragment.focus');
    if (fragments.length && fragments.length > 1 && !focusedFragments.length) {
      focusOn();
    }
  });

  document.addEventListener('keydown', function(e) {
    // Kill keyboard events on slides with text input
    if (e.target.getAttribute('data-disable-events')) {
      e.stopImmediatePropagation();
      return;
    }

    // Make all fragments visible
    if (e.keyCode === 74) { // j key
      focusOn(e);
    }

  }, true);

}());<|endoftext|>


<commit_before>define(function() {
    "use strict";

    var config = {
        "css": true,
        "lang": (navigator.language || navigator.userLanguage).split("-")[0],
        "reply-to-self": false,
        "max-comments-top": "10",
        "max-comments-nested": "5",
        "reveal-on-click": "5",
        "avatar-bg": "#f0f0f0",
        "avatar-fg": ["#9abf88", "#5698c4", "#e279a3", "#9163b6",
                      "#be5168", "#f19670", "#e4bf80", "#447c69"].join(" ")
    };

    var js = document.getElementsByTagName("script");

    for (var i = 0; i < js.length; i++) {
        [].forEach.call(js[i].attributes, function(attr) {
            if (/^data-isso-/.test(attr.name)) {
                try {
                    config[attr.name.substring(10)] = JSON.parse(attr.value);
                } catch (ex) {
                    config[attr.name.substring(10)] = attr.value;
                }
            }
        });
    }

    // split avatar-fg on whitespace
    config["avatar-fg"] = config["avatar-fg"].split(" ");

    return config;

});
<commit_msg>use numerical values in default configuration to match user-provided values<commit_after>define(function() {
    "use strict";

    var config = {
        "css": true,
        "lang": (navigator.language || navigator.userLanguage).split("-")[0],
        "reply-to-self": false,
        "max-comments-top": 10,
        "max-comments-nested": 5,
        "reveal-on-click": 5,
        "avatar-bg": "#f0f0f0",
        "avatar-fg": ["#9abf88", "#5698c4", "#e279a3", "#9163b6",
                      "#be5168", "#f19670", "#e4bf80", "#447c69"].join(" ")
    };

    var js = document.getElementsByTagName("script");

    for (var i = 0; i < js.length; i++) {
        [].forEach.call(js[i].attributes, function(attr) {
            if (/^data-isso-/.test(attr.name)) {
                try {
                    config[attr.name.substring(10)] = JSON.parse(attr.value);
                } catch (ex) {
                    config[attr.name.substring(10)] = attr.value;
                }
            }
        });
    }

    // split avatar-fg on whitespace
    config["avatar-fg"] = config["avatar-fg"].split(" ");

    return config;

});
<|endoftext|>


<commit_before>angular.module('afpClientApp', ['ngRoute'])
  .constant("appVars", {
    afpApiEndpoint: "http://afp.rz.is/afp-api/latest/"
  })
  .config(['$routeProvider',
    function ($routeProvider) {
      $routeProvider.
      when('/console/:account/:role', {
        templateUrl: 'templates/console.html',
        controller: 'ConsoleController'
      }).
      otherwise({
        templateUrl: 'templates/resultlist.html',
        controller: 'AccountlistController'
      });
    }]);<commit_msg>correct host<commit_after>angular.module('afpClientApp', ['ngRoute'])
  .constant("appVars", {
    afpApiEndpoint: "/afp-api/latest/"
  })
  .config(['$routeProvider',
    function ($routeProvider) {
      $routeProvider.
      when('/console/:account/:role', {
        templateUrl: 'templates/console.html',
        controller: 'ConsoleController'
      }).
      otherwise({
        templateUrl: 'templates/resultlist.html',
        controller: 'AccountlistController'
      });
    }]);<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');
var Joi = require('joi');
var calendar = require('./calendar');
var station = require('./station');
var config = require('./config');

exports.plugin = {
    name: 'OpenERZ Routing',
    version: config.version(),
    multiple: false,
    once: true,
    register: async (server, options) => {
        await generateRoutes(server);
    }
};

// eslint-disable-next-line max-lines-per-function, complexity
async function generateRoutes(server) {
    /* Add static routes */
    try {
        addStaticRoutes(server);
    } catch(err) {
        console.error('Error while adding static routes');
        throw err;
    }

    /* Add routes needed for the API docs */
    try {
        addApiDocRoutes(server);
    } catch(err) {
        console.error('Error while adding api docs routes');
        throw err;
    }

    /* Add a route for the collection stations */
    try {
        addStationRoutes(server);
    } catch(err) {
        console.error('Error while adding station routes');
        throw err;
    }

    /* Add routes for the calendars */
    try {
        addCalendarRoutes(server);
    } catch(err) {
        console.error('Error while adding calendar routes');
        throw err;
    }

    /* Add routes for the regions */
    try {
        addRegionRoutes(server);
    } catch(err) {
        console.error('Error while adding region routes');
        throw err;
    }

    /* Add routes for the regions */
    try {
        addParamRoutes(server);
    } catch(err) {
        console.error('Error while adding parameter routes');
        throw err;
    }
}

function addStaticRoutes(server) {
    /* Server everything in the 'public' directory at /static/ */
    server.route({
        method: 'GET',
        path: '/static/{param*}',
        handler: {
            directory: {
                path: 'public',
                index: true,
                redirectToSlash: true
            }
        }
    });

    server.route({
        method: 'GET',
        path: '/favicon.ico',
        handler: {
            file: 'public/favicon.ico'
        }
    });

    /* Status route for monitoring */
    server.route({
        method: 'GET',
        path: '/isalive',
        handler: (request, h) => 'Is up and running!'
    });
}

function addApiDocRoutes(server) {
    /* catch all route to serve api docs */
    var apiDocsRoutes = [
        '/{path*}',
        '/doc',
        '/api',
    ];
    _.each(apiDocsRoutes, function(path) {
        server.route({
            method: 'GET',
            path: path,
            handler: redirectToDocs()
        });
    });

    server.route({
        method: 'GET',
        path: '/apis.json',
        handler: {
            file: 'public/apis.json'
        }
    });
}

function redirectToDocs() {
    return function(request, h) {
        var protocol = 'http';

        var host = request.headers.host;
        if ('openerz.metaodi.ch' === host) {
            protocol = 'https';
        }
        return h.redirect(protocol + '://' + host + '/documentation');
    };
}

function addStationRoutes(server) {
    server.route({
        method: 'GET',
        path: '/api/stations{format?}',
        config: {
            description: 'Get stations',
            notes: 'Return all waste collection stations (Sammelstellen)',
            tags: [ 'api', 'station' ],
            jsonp: 'callback',
            validate: {
                /* eslint-disable max-len */
                params: Joi.object({
                    format: Joi.string().allow('', '.json').description('The format in which the ressource should be returned, only `json` is supported').default('.json')
                }),
                query: Joi.object({
                    region: Joi.string().valid('zurich', 'thalwil', 'basel', 'stgallen').description('The region of the station'),
                    zip: Joi.number().integer().min(1000).max(9999).description('The zip code of the station (not all regions provide zip codes)'),
                    name: Joi.string().description('Case insensitive search for the station name, supports regex'),
                    glass: Joi.boolean().description('Whether the station provides glass container or not'),
                    oil: Joi.boolean().description('Whether the station provides an oil container or not'),
                    metal: Joi.boolean().description('Whether the station provides a metal container or not'),
                    textile: Joi.boolean().description('Whether the station provides a textile container or not'),
                    sort: Joi.string().optional().description('Sort order for result, e.g. `zip` or `name:desc`. Multiple values can be comma-separated.'),
                    offset: Joi.number().optional().description('Offset from all results, together with `limit` this can be used for pagination.').default(0),
                    limit: Joi.number().optional().description('Limit the amount of returned records.').default(0)
                })
                /* eslint-enable max-len */
            }
        },
        handler: station.handler()
    });
}

function addCalendarRoutes(server) {
    var params = config.parameter();
    _.each(config.calendar(), function(routeEntry) {
        server.route({
            method: 'GET',
            path: '/api/calendar' + (routeEntry.type ? '/' + routeEntry.type : '') + '{format?}',
            config: {
                description: routeEntry.description,
                notes: routeEntry.notes,
                tags: [ 'api', 'calendar' ],
                jsonp: 'callback',
                validate: {
                    /* eslint-disable max-len */
                    params: Joi.object({
                        format: Joi.string().allow('', '.ics', '.json').description('The format of the returned ressource, either `json` or `ics`').default('.json')
                    }),
                    query: Joi.object(_.pick(params, routeEntry.params))
                    /* eslint-enable max-len */
                }
            },
            handler: calendar.handler(routeEntry.type)
        });
    });
}

function addRegionRoutes(server) {
    _.each(config.region(), function(regionEntry) {
        var params = _.omit(config.parameter(regionEntry['types']), regionEntry['omitParams']);
        _.each(config.calendar(), function(routeEntry) {
            if (routeEntry.type && !regionEntry.types.includes(routeEntry.type)) {
                return;
            }
            server.route({
                /* eslint-disable max-len */
                method: 'GET',
                path: '/api/region/' + regionEntry.route + '/calendar' + (routeEntry.type ? '/' + routeEntry.type : '') + '{format?}',
                config: {
                    description: routeEntry.description,
                    notes: routeEntry.notes,
                    tags: [ 'api', 'region-' + regionEntry.route ],
                    jsonp: 'callback',
                    validate: {
                        params: Joi.object({
                            format: Joi.string().allow('', '.ics', '.json').description('The format of the returned ressource, either `json` or `ics`').default('.json')
                        }),
                        query: Joi.object(_.pick(params, routeEntry.params))
                    }
                },
                handler: calendar.handler(routeEntry.type, regionEntry.route)
                /* eslint-enable max-len */
            });
        });
    });
}

function addParamRoutes(server) {
    var params = config.parameter();
    var regions = config.region();
    var regionList = _.keys(regions).sort();
    server.route({
        /* eslint-disable max-len */
        method: 'GET',
        path: '/api/parameter/regions',
        config: {
            description: 'Values for the `region` parameter',
            notes: 'Returns a list of string values for the `region` parameter of the calendar endpoint.',
            tags: [ 'api', 'parameter' ],
            jsonp: 'callback',
        },
        handler: function (request, h) {
            var result = {
                '_metadata': {
                    'total_count': regionList.length
                },
                'result': regionList
            };
            return result;
        }
        /* eslint-enable max-len */
    });

    var allTypes = config.types();
    server.route({
        /* eslint-disable max-len */
        method: 'GET',
        path: '/api/parameter/types',
        config: {
            description: 'Values for the `types` parameter',
            notes: 'Returns a list of string values for the `types` parameter (by region if the `region` query parameter is given).',
            tags: [ 'api', 'parameter' ],
            jsonp: 'callback',
            validate: {
                query: Joi.object(_.pick(params, ['region']))
            }
        },
        handler: function (request, h) {
            var region = request.query.region;
            var docs = undefined;
            if (region) {
                docs = regions[region]['types'];
            } else {
                docs = allTypes;
            }
            var result = {
                '_metadata': {
                    'total_count': docs.length
                },
                'result': docs
            };
            return result;
        }
        /* eslint-enable max-len */
    });
}
<commit_msg>Allow long function<commit_after>'use strict';

var _ = require('underscore');
var Joi = require('joi');
var calendar = require('./calendar');
var station = require('./station');
var config = require('./config');

exports.plugin = {
    name: 'OpenERZ Routing',
    version: config.version(),
    multiple: false,
    once: true,
    register: async (server, options) => {
        await generateRoutes(server);
    }
};

// eslint-disable-next-line max-lines-per-function, complexity
async function generateRoutes(server) {
    /* Add static routes */
    try {
        addStaticRoutes(server);
    } catch(err) {
        console.error('Error while adding static routes');
        throw err;
    }

    /* Add routes needed for the API docs */
    try {
        addApiDocRoutes(server);
    } catch(err) {
        console.error('Error while adding api docs routes');
        throw err;
    }

    /* Add a route for the collection stations */
    try {
        addStationRoutes(server);
    } catch(err) {
        console.error('Error while adding station routes');
        throw err;
    }

    /* Add routes for the calendars */
    try {
        addCalendarRoutes(server);
    } catch(err) {
        console.error('Error while adding calendar routes');
        throw err;
    }

    /* Add routes for the regions */
    try {
        addRegionRoutes(server);
    } catch(err) {
        console.error('Error while adding region routes');
        throw err;
    }

    /* Add routes for the regions */
    try {
        addParamRoutes(server);
    } catch(err) {
        console.error('Error while adding parameter routes');
        throw err;
    }
}

function addStaticRoutes(server) {
    /* Server everything in the 'public' directory at /static/ */
    server.route({
        method: 'GET',
        path: '/static/{param*}',
        handler: {
            directory: {
                path: 'public',
                index: true,
                redirectToSlash: true
            }
        }
    });

    server.route({
        method: 'GET',
        path: '/favicon.ico',
        handler: {
            file: 'public/favicon.ico'
        }
    });

    /* Status route for monitoring */
    server.route({
        method: 'GET',
        path: '/isalive',
        handler: (request, h) => 'Is up and running!'
    });
}

function addApiDocRoutes(server) {
    /* catch all route to serve api docs */
    var apiDocsRoutes = [
        '/{path*}',
        '/doc',
        '/api',
    ];
    _.each(apiDocsRoutes, function(path) {
        server.route({
            method: 'GET',
            path: path,
            handler: redirectToDocs()
        });
    });

    server.route({
        method: 'GET',
        path: '/apis.json',
        handler: {
            file: 'public/apis.json'
        }
    });
}

function redirectToDocs() {
    return function(request, h) {
        var protocol = 'http';

        var host = request.headers.host;
        if ('openerz.metaodi.ch' === host) {
            protocol = 'https';
        }
        return h.redirect(protocol + '://' + host + '/documentation');
    };
}

function addStationRoutes(server) {
    server.route({
        method: 'GET',
        path: '/api/stations{format?}',
        config: {
            description: 'Get stations',
            notes: 'Return all waste collection stations (Sammelstellen)',
            tags: [ 'api', 'station' ],
            jsonp: 'callback',
            validate: {
                /* eslint-disable max-len */
                params: Joi.object({
                    format: Joi.string().allow('', '.json').description('The format in which the ressource should be returned, only `json` is supported').default('.json')
                }),
                query: Joi.object({
                    region: Joi.string().valid('zurich', 'thalwil', 'basel', 'stgallen').description('The region of the station'),
                    zip: Joi.number().integer().min(1000).max(9999).description('The zip code of the station (not all regions provide zip codes)'),
                    name: Joi.string().description('Case insensitive search for the station name, supports regex'),
                    glass: Joi.boolean().description('Whether the station provides glass container or not'),
                    oil: Joi.boolean().description('Whether the station provides an oil container or not'),
                    metal: Joi.boolean().description('Whether the station provides a metal container or not'),
                    textile: Joi.boolean().description('Whether the station provides a textile container or not'),
                    sort: Joi.string().optional().description('Sort order for result, e.g. `zip` or `name:desc`. Multiple values can be comma-separated.'),
                    offset: Joi.number().optional().description('Offset from all results, together with `limit` this can be used for pagination.').default(0),
                    limit: Joi.number().optional().description('Limit the amount of returned records.').default(0)
                })
                /* eslint-enable max-len */
            }
        },
        handler: station.handler()
    });
}

function addCalendarRoutes(server) {
    var params = config.parameter();
    _.each(config.calendar(), function(routeEntry) {
        server.route({
            method: 'GET',
            path: '/api/calendar' + (routeEntry.type ? '/' + routeEntry.type : '') + '{format?}',
            config: {
                description: routeEntry.description,
                notes: routeEntry.notes,
                tags: [ 'api', 'calendar' ],
                jsonp: 'callback',
                validate: {
                    /* eslint-disable max-len */
                    params: Joi.object({
                        format: Joi.string().allow('', '.ics', '.json').description('The format of the returned ressource, either `json` or `ics`').default('.json')
                    }),
                    query: Joi.object(_.pick(params, routeEntry.params))
                    /* eslint-enable max-len */
                }
            },
            handler: calendar.handler(routeEntry.type)
        });
    });
}

function addRegionRoutes(server) {
    _.each(config.region(), function(regionEntry) {
        var params = _.omit(config.parameter(regionEntry['types']), regionEntry['omitParams']);
        _.each(config.calendar(), function(routeEntry) {
            if (routeEntry.type && !regionEntry.types.includes(routeEntry.type)) {
                return;
            }
            server.route({
                /* eslint-disable max-len */
                method: 'GET',
                path: '/api/region/' + regionEntry.route + '/calendar' + (routeEntry.type ? '/' + routeEntry.type : '') + '{format?}',
                config: {
                    description: routeEntry.description,
                    notes: routeEntry.notes,
                    tags: [ 'api', 'region-' + regionEntry.route ],
                    jsonp: 'callback',
                    validate: {
                        params: Joi.object({
                            format: Joi.string().allow('', '.ics', '.json').description('The format of the returned ressource, either `json` or `ics`').default('.json')
                        }),
                        query: Joi.object(_.pick(params, routeEntry.params))
                    }
                },
                handler: calendar.handler(routeEntry.type, regionEntry.route)
                /* eslint-enable max-len */
            });
        });
    });
}

// eslint-disable-next-line max-lines-per-function
function addParamRoutes(server) {
    var params = config.parameter();
    var regions = config.region();
    var regionList = _.keys(regions).sort();
    server.route({
        /* eslint-disable max-len */
        method: 'GET',
        path: '/api/parameter/regions',
        config: {
            description: 'Values for the `region` parameter',
            notes: 'Returns a list of string values for the `region` parameter of the calendar endpoint.',
            tags: [ 'api', 'parameter' ],
            jsonp: 'callback',
        },
        handler: function (request, h) {
            var result = {
                '_metadata': {
                    'total_count': regionList.length
                },
                'result': regionList
            };
            return result;
        }
        /* eslint-enable max-len */
    });

    var allTypes = config.types();
    server.route({
        /* eslint-disable max-len */
        method: 'GET',
        path: '/api/parameter/types',
        config: {
            description: 'Values for the `types` parameter',
            notes: 'Returns a list of string values for the `types` parameter (by region if the `region` query parameter is given).',
            tags: [ 'api', 'parameter' ],
            jsonp: 'callback',
            validate: {
                query: Joi.object(_.pick(params, ['region']))
            }
        },
        handler: function (request, h) {
            var region = request.query.region;
            var docs = undefined;
            if (region) {
                docs = regions[region]['types'];
            } else {
                docs = allTypes;
            }
            var result = {
                '_metadata': {
                    'total_count': docs.length
                },
                'result': docs
            };
            return result;
        }
        /* eslint-enable max-len */
    });
}
<|endoftext|>