<commit_before>'use strict';

//Create an object for a salmon cookie store
var storeOne = { //starting with store one
  minCustomer: 23, //min customers, value given in problem domain
  maxCustomer: 65, //max customers given in problem domain
  avgCookiesCustomer: 6.3, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var i = 0; i < storeOne.hours.length; i++) {//this takes the total cookies per hour and pushes into an array
  storeOne.cookiesEachHour.push(storeOne.cookiesSoldPerHour());
  console.log(storeOne.cookiesEachHour[i]);
};

var storeOneHourlyTotals = [];
for(var j = 0; j < storeOne.hours.length; j++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeOneHourlyTotals.push('
' + storeOne.hours[j] + ': ' + Math.floor(storeOne.cookiesEachHour[j]) + ' cookies sold
');
  console.log(storeOneHourlyTotals[j]);
};

var dailyTotal = [];
var total = 0; //this will calculate total cookies sold by end of day
for(var k = 0; k < storeOne.hours.length; k++) {
  total += Math.floor(storeOne.cookiesEachHour[k]);
  dailyTotal.push('
Total Cookies sold: ' + total + '
');
  console.log(dailyTotal[dailyTotal.length - 1]); //this is the total number of cookies sold
};

function storeOneDom (){ //Adding list to sales.html
  var containerOne = document.createElement('div');
  containerOne.innerHTML = '
1st and Pike
';
  document.body.appendChild(containerOne);

  var listOne = document.createElement('ul');
  var listOneArr = [];

  for(var a = 0; a < storeOneHourlyTotals.length; a++) {
    listOneArr.push(storeOneHourlyTotals[a]);
  }
  listOneArr.push(dailyTotal[dailyTotal.length - 1]);
  listOne.innerHTML = listOneArr.join('');
  document.body.appendChild(listOne);

  // var storeOneTotal = document.createElement('li');
  // storeOneTotal.innerHTML = 'Total cookies sold: ' + dailyTotal[14];
  // document.body.appendChild(storeOneTotal);
};
storeOneDom();

//store two
var storeTwo = { //starting with store one
  minCustomer: 3, //min customers, value given in problem domain
  maxCustomer: 24, //max customers given in problem domain
  avgCookiesCustomer: 1.2, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var l = 0; l < storeTwo.hours.length; l++) {//this takes the total cookies per hour and pushes into an array
  storeTwo.cookiesEachHour.push(storeTwo.cookiesSoldPerHour());
  console.log(storeTwo.cookiesEachHour[l]);
};

var storeTwoHourlyTotals = [];
for(var m = 0; m < storeTwo.hours.length; m++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeTwoHourlyTotals.push('
' + storeTwo.hours[m] + ': ' + Math.floor(storeTwo.cookiesEachHour[m]) + ' cookies sold
');
  console.log(storeTwoHourlyTotals[m]);
};

var dailyTotalTwo = [];
var totalTwo = 0; //this will calculate total cookies sold by end of day
for(var n = 0; n < storeTwo.hours.length; n++) {
  totalTwo += Math.floor(storeTwo.cookiesEachHour[n]);
  dailyTotalTwo.push('
Total Cookies sold: ' + totalTwo + '
');
  console.log(dailyTotalTwo[dailyTotalTwo.length - 1]); //this is the total number of cookies sold
};

function storeTwoDom (){ //Adding list to sales.html
  var containerTwo = document.createElement('div');
  containerTwo.innerHTML = '
SeaTac Airport
';
  document.body.appendChild(containerTwo);

  var listTwo = document.createElement('ul');
  var listTwoArr = [];

  for(var b = 0; b < storeTwoHourlyTotals.length; b++) {
    listTwoArr.push(storeTwoHourlyTotals[b]);
  }
  listTwoArr.push(dailyTotalTwo[dailyTotalTwo.length - 1]);
  listTwo.innerHTML = listTwoArr.join('');
  document.body.appendChild(listTwo);

  // var storeTwoTotal = document.createElement('li');
  // storeTwoTotal.innerHTML = 'Total cookies sold: ' + dailyTotalTwo[14];
  // document.body.appendChild(storeTwoTotal);
};
storeTwoDom();

//store 3
var storeThree = { //starting with store one
  minCustomer: 11, //min customers, value given in problem domain
  maxCustomer: 38, //max customers given in problem domain
  avgCookiesCustomer: 3.7, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var o = 0; o < storeThree.hours.length; o++) {//this takes the total cookies per hour and pushes into an array
  storeThree.cookiesEachHour.push(storeThree.cookiesSoldPerHour());
  console.log(storeThree.cookiesEachHour[o]);
};

var storeThreeHourlyTotals = [];
for(var p = 0; p < storeThree.hours.length; p++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeThreeHourlyTotals.push('
' + storeThree.hours[p] + ': ' + Math.floor(storeThree.cookiesEachHour[p]) + ' cookies sold
');
  console.log(storeThreeHourlyTotals[p]);
};

var dailyTotalThree = [];
var totalThree = 0; //this will calculate total cookies sold by end of day
for(var q = 0; q < storeThree.hours.length; q++) {
  totalThree += Math.floor(storeThree.cookiesEachHour[q]);
  dailyTotalThree.push('
Total Cookies sold: ' + totalThree + '
');
  console.log(dailyTotalThree[dailyTotalThree.length - 1]); //this is the total number of cookies sold
};

function storeThreeDom (){ //Adding list to sales.html
  var containerThree = document.createElement('div');
  containerThree.innerHTML = '
Seattle Center
';
  document.body.appendChild(containerThree);

  var listThree = document.createElement('ul');
  var listThreeArr = [];

  for(var c = 0; c < storeThreeHourlyTotals.length; c++) {
    listThreeArr.push(storeThreeHourlyTotals[c]);
  }
  listThreeArr.push(dailyTotalThree[dailyTotalThree.length - 1]);
  listThree.innerHTML = listThreeArr.join('');
  document.body.appendChild(listThree);

  // var storeThreeTotal = document.createElement('li');
  // storeThreeTotal.innerHTML = 'Total cookies sold: ' + dailyTotalThree[14];
  // document.body.appendChild(storeThreeTotal);
};
storeThreeDom();

//store four
var storeFour = { //starting with store one
  minCustomer: 20, //min customers, value given in problem domain
  maxCustomer: 38, //max customers given in problem domain
  avgCookiesCustomer: 2.3, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var r = 0; r < storeFour.hours.length; r++) {//this takes the total cookies per hour and pushes into an array
  storeFour.cookiesEachHour.push(storeFour.cookiesSoldPerHour());
  console.log(storeFour.cookiesEachHour[r]);
};

var storeFourHourlyTotals = [];
for(var s = 0; s < storeFour.hours.length; s++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeFourHourlyTotals.push('
' + storeFour.hours[s] + ': ' + Math.floor(storeFour.cookiesEachHour[s]) + ' cookies sold
');
  console.log(storeFourHourlyTotals[s]);
};

var dailyTotalFour = [];
var totalFour = 0; //this will calculate total cookies sold by end of day
for(var t = 0; t < storeFour.hours.length; t++) {
  totalFour += Math.floor(storeFour.cookiesEachHour[t]);
  dailyTotalFour.push('
Total Cookies sold: ' + totalFour + '
');
  console.log(dailyTotalFour[dailyTotalFour.length - 1]); //this is the total number of cookies sold
};

function storeFourDom (){ //Adding list to sales.html
  var containerFour = document.createElement('div');
  containerFour.innerHTML = '
Capitol Hill
';
  document.body.appendChild(containerFour);

  var listFour = document.createElement('ul');
  var listFourArr = [];

  for(var d = 0; d < storeFourHourlyTotals.length; d++) {
    listFourArr.push(storeFourHourlyTotals[d]);
  }
  listFourArr.push(dailyTotalFour[dailyTotalFour.length - 1]);
  listFour.innerHTML = listFourArr.join('');
  document.body.appendChild(listFour);

  // var storeFourTotal = document.createElement('li');
  // storeFourTotal.innerHTML = 'Total cookies sold: ' + dailyTotalFour[14];
  // document.body.appendChild(storeFourTotal);
};
storeFourDom();

//store five
var storeFive = { //starting with store one
  minCustomer: 2, //min customers, value given in problem domain
  maxCustomer: 16, //max customers given in problem domain
  avgCookiesCustomer: 4.6, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var u = 0; u < storeFive.hours.length; u++) {//this takes the total cookies per hour and pushes into an array
  storeFive.cookiesEachHour.push(storeFive.cookiesSoldPerHour());
  console.log(storeFive.cookiesEachHour[u]);
};

var storeFiveHourlyTotals = [];
for(var v = 0; v < storeFive.hours.length; v++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeFiveHourlyTotals.push('
' + storeFive.hours[v] + ': ' + Math.floor(storeFive.cookiesEachHour[v]) + ' cookies sold
');
  console.log(storeFiveHourlyTotals[v]);
};

var dailyTotalFive = [];
var totalFive = 0; //this will calculate total cookies sold by end of day
for(var w = 0; w < storeFive.hours.length; w++) {
  totalFive += Math.floor(storeFive.cookiesEachHour[w]);
  dailyTotalFive.push('
Total Cookies sold: ' + totalFive + '
');
  console.log(dailyTotalFive[dailyTotalFive.length - 1]); //this is the total number of cookies sold
};

function storeFiveDom (){ //Adding list to sales.html
  var containerFive = document.createElement('div');
  containerFive.innerHTML = '
Alki
';
  document.body.appendChild(containerFive);

  var listFive = document.createElement('ul');
  var listFiveArr = [];

  for(var e = 0; e < storeFiveHourlyTotals.length; e++) {
    listFiveArr.push(storeFiveHourlyTotals[e]);
  }
  listFiveArr.push(dailyTotalFive[dailyTotalFive.length - 1]);
  listFive.innerHTML = listFiveArr.join('');
  document.body.appendChild(listFive);

  var storeFiveTotal = document.createElement('li');
  storeFiveTotal.innerHTML = 'Total cookies sold: ' + dailyTotalFive[14];
  document.body.appendChild(storeFiveTotal);
};
storeFiveDom();
<commit_msg>saved latest update<commit_after>'use strict';

//Create an object for a salmon cookie store
var storeOne = { //starting with store one
  minCustomer: 23, //min customers, value given in problem domain
  maxCustomer: 65, //max customers given in problem domain
  avgCookiesCustomer: 6.3, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var i = 0; i < storeOne.hours.length; i++) {//this takes the total cookies per hour and pushes into an array
  storeOne.cookiesEachHour.push(storeOne.cookiesSoldPerHour());
  console.log(storeOne.cookiesEachHour[i]);
};

var storeOneHourlyTotals = [];
for(var j = 0; j < storeOne.hours.length; j++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeOneHourlyTotals.push('
' + storeOne.hours[j] + ': ' + Math.floor(storeOne.cookiesEachHour[j]) + ' cookies sold
');
  console.log(storeOneHourlyTotals[j]);
};

var dailyTotal = [];
var total = 0; //this will calculate total cookies sold by end of day
for(var k = 0; k < storeOne.hours.length; k++) {
  total += Math.floor(storeOne.cookiesEachHour[k]);
  dailyTotal.push('
Total Cookies sold: ' + total + '
');
  console.log(dailyTotal[dailyTotal.length - 1]); //this is the total number of cookies sold
};

function storeOneDom (){ //Adding list to sales.html
  var containerOne = document.createElement('div');
  containerOne.innerHTML = '
1st and Pike
';
  document.body.appendChild(containerOne);

  var listOne = document.createElement('ul');
  var listOneArr = [];

  for(var a = 0; a < storeOneHourlyTotals.length; a++) {
    listOneArr.push(storeOneHourlyTotals[a]);
  }
  listOneArr.push(dailyTotal[dailyTotal.length - 1]);
  listOne.innerHTML = listOneArr.join('');
  document.body.appendChild(listOne);

  // var storeOneTotal = document.createElement('li');
  // storeOneTotal.innerHTML = 'Total cookies sold: ' + dailyTotal[14];
  // document.body.appendChild(storeOneTotal);
};
storeOneDom();

//store two
var storeTwo = { //starting with store one
  minCustomer: 3, //min customers, value given in problem domain
  maxCustomer: 24, //max customers given in problem domain
  avgCookiesCustomer: 1.2, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var l = 0; l < storeTwo.hours.length; l++) {//this takes the total cookies per hour and pushes into an array
  storeTwo.cookiesEachHour.push(storeTwo.cookiesSoldPerHour());
  console.log(storeTwo.cookiesEachHour[l]);
};

var storeTwoHourlyTotals = [];
for(var m = 0; m < storeTwo.hours.length; m++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeTwoHourlyTotals.push('
' + storeTwo.hours[m] + ': ' + Math.floor(storeTwo.cookiesEachHour[m]) + ' cookies sold
');
  console.log(storeTwoHourlyTotals[m]);
};

var dailyTotalTwo = [];
var totalTwo = 0; //this will calculate total cookies sold by end of day
for(var n = 0; n < storeTwo.hours.length; n++) {
  totalTwo += Math.floor(storeTwo.cookiesEachHour[n]);
  dailyTotalTwo.push('
Total Cookies sold: ' + totalTwo + '
');
  console.log(dailyTotalTwo[dailyTotalTwo.length - 1]); //this is the total number of cookies sold
};

function storeTwoDom (){ //Adding list to sales.html
  var containerTwo = document.createElement('div');
  containerTwo.innerHTML = '
SeaTac Airport
';
  document.body.appendChild(containerTwo);

  var listTwo = document.createElement('ul');
  var listTwoArr = [];

  for(var b = 0; b < storeTwoHourlyTotals.length; b++) {
    listTwoArr.push(storeTwoHourlyTotals[b]);
  }
  listTwoArr.push(dailyTotalTwo[dailyTotalTwo.length - 1]);
  listTwo.innerHTML = listTwoArr.join('');
  document.body.appendChild(listTwo);

  // var storeTwoTotal = document.createElement('li');
  // storeTwoTotal.innerHTML = 'Total cookies sold: ' + dailyTotalTwo[14];
  // document.body.appendChild(storeTwoTotal);
};
storeTwoDom();

//store 3
var storeThree = { //starting with store one
  minCustomer: 11, //min customers, value given in problem domain
  maxCustomer: 38, //max customers given in problem domain
  avgCookiesCustomer: 3.7, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var o = 0; o < storeThree.hours.length; o++) {//this takes the total cookies per hour and pushes into an array
  storeThree.cookiesEachHour.push(storeThree.cookiesSoldPerHour());
  console.log(storeThree.cookiesEachHour[o]);
};

var storeThreeHourlyTotals = [];
for(var p = 0; p < storeThree.hours.length; p++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeThreeHourlyTotals.push('
' + storeThree.hours[p] + ': ' + Math.floor(storeThree.cookiesEachHour[p]) + ' cookies sold
');
  console.log(storeThreeHourlyTotals[p]);
};

var dailyTotalThree = [];
var totalThree = 0; //this will calculate total cookies sold by end of day
for(var q = 0; q < storeThree.hours.length; q++) {
  totalThree += Math.floor(storeThree.cookiesEachHour[q]);
  dailyTotalThree.push('
Total Cookies sold: ' + totalThree + '
');
  console.log(dailyTotalThree[dailyTotalThree.length - 1]); //this is the total number of cookies sold
};

function storeThreeDom (){ //Adding list to sales.html
  var containerThree = document.createElement('div');
  containerThree.innerHTML = '
Seattle Center
';
  document.body.appendChild(containerThree);

  var listThree = document.createElement('ul');
  var listThreeArr = [];

  for(var c = 0; c < storeThreeHourlyTotals.length; c++) {
    listThreeArr.push(storeThreeHourlyTotals[c]);
  }
  listThreeArr.push(dailyTotalThree[dailyTotalThree.length - 1]);
  listThree.innerHTML = listThreeArr.join('');
  document.body.appendChild(listThree);

  // var storeThreeTotal = document.createElement('li');
  // storeThreeTotal.innerHTML = 'Total cookies sold: ' + dailyTotalThree[14];
  // document.body.appendChild(storeThreeTotal);
};
storeThreeDom();

//store four
var storeFour = { //starting with store one
  minCustomer: 20, //min customers, value given in problem domain
  maxCustomer: 38, //max customers given in problem domain
  avgCookiesCustomer: 2.3, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var r = 0; r < storeFour.hours.length; r++) {//this takes the total cookies per hour and pushes into an array
  storeFour.cookiesEachHour.push(storeFour.cookiesSoldPerHour());
  console.log(storeFour.cookiesEachHour[r]);
};

var storeFourHourlyTotals = [];
for(var s = 0; s < storeFour.hours.length; s++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeFourHourlyTotals.push('
' + storeFour.hours[s] + ': ' + Math.floor(storeFour.cookiesEachHour[s]) + ' cookies sold
');
  console.log(storeFourHourlyTotals[s]);
};

var dailyTotalFour = [];
var totalFour = 0; //this will calculate total cookies sold by end of day
for(var t = 0; t < storeFour.hours.length; t++) {
  totalFour += Math.floor(storeFour.cookiesEachHour[t]);
  dailyTotalFour.push('
Total Cookies sold: ' + totalFour + '
');
  console.log(dailyTotalFour[dailyTotalFour.length - 1]); //this is the total number of cookies sold
};

function storeFourDom (){ //Adding list to sales.html
  var containerFour = document.createElement('div');
  containerFour.innerHTML = '
Capitol Hill
';
  document.body.appendChild(containerFour);

  var listFour = document.createElement('ul');
  var listFourArr = [];

  for(var d = 0; d < storeFourHourlyTotals.length; d++) {
    listFourArr.push(storeFourHourlyTotals[d]);
  }
  listFourArr.push(dailyTotalFour[dailyTotalFour.length - 1]);
  listFour.innerHTML = listFourArr.join('');
  document.body.appendChild(listFour);

  // var storeFourTotal = document.createElement('li');
  // storeFourTotal.innerHTML = 'Total cookies sold: ' + dailyTotalFour[14];
  // document.body.appendChild(storeFourTotal);
};
storeFourDom();

//store five
var storeFive = { //starting with store one
  minCustomer: 2, //min customers, value given in problem domain
  maxCustomer: 16, //max customers given in problem domain
  avgCookiesCustomer: 4.6, //average cookies per sale given in problem domain
  hours:['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'], //array for each hour store is open
  cookiesEachHour: [], //array for cookies sold based on random customers generated each hour

  randomCustomer: function () { //this generates a random number to represent the amount of customers in an hour
    var min = Math.ceil(this.minCustomer);
    var max = Math.floor(this.maxCustomer);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },

  cookiesSoldPerHour: function() { //this multiplies the random number by the average cookies to create cookies sold per hour
    return (this.randomCustomer() * this.avgCookiesCustomer);
    console.log(this.randomCustomer() * this.avgCookiesCustomer);
  },
};

for(var u = 0; u < storeFive.hours.length; u++) {//this takes the total cookies per hour and pushes into an array
  storeFive.cookiesEachHour.push(storeFive.cookiesSoldPerHour());
  console.log(storeFive.cookiesEachHour[u]);
};

var storeFiveHourlyTotals = [];
for(var v = 0; v < storeFive.hours.length; v++) { //this turns hour and cookies per hour data and pushes into an array as a string
  storeFiveHourlyTotals.push('
' + storeFive.hours[v] + ': ' + Math.floor(storeFive.cookiesEachHour[v]) + ' cookies sold
');
  console.log(storeFiveHourlyTotals[v]);
};

var dailyTotalFive = [];
var totalFive = 0; //this will calculate total cookies sold by end of day
for(var w = 0; w < storeFive.hours.length; w++) {
  totalFive += Math.floor(storeFive.cookiesEachHour[w]);
  dailyTotalFive.push('
Total Cookies sold: ' + totalFive + '
');
  console.log(dailyTotalFive[dailyTotalFive.length - 1]); //this is the total number of cookies sold
};

function storeFiveDom (){ //Adding list to sales.html
  var containerFive = document.createElement('div');
  containerFive.innerHTML = '
Alki
';
  document.body.appendChild(containerFive);

  var listFive = document.createElement('ul');
  var listFiveArr = [];

  for(var e = 0; e < storeFiveHourlyTotals.length; e++) {
    listFiveArr.push(storeFiveHourlyTotals[e]);
  }
  listFiveArr.push(dailyTotalFive[dailyTotalFive.length - 1]);
  listFive.innerHTML = listFiveArr.join('');
  document.body.appendChild(listFive);

  // var storeFiveTotal = document.createElement('li');
  // storeFiveTotal.innerHTML = 'Total cookies sold: ' + dailyTotalFive[14];
  // document.body.appendChild(storeFiveTotal);
};
storeFiveDom();
<|endoftext|>


<commit_before>var http = require('http');
var express = require('express');
var db = require('./model/db');
var resources = require('express-resource');
var namespace = require('express-namespace');
var path = require('path');
var passport = require('passport');
var RedisStore = require('connect-redis')(express);
var GitHubApi = require("github");
var github = new GitHubApi({ version: "3.0.0", timeout: 5000 });

var app = express();
app.set('host', process.env.IP || "127.0.0.1");
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
var options = {
	host: '127.0.0.1',//'nodejitsudb6553126701.redis.irstack.com',
	port: '6379'//,
	//pass: 'nodejitsudb6553126701.redis.irstack.com:f327cfe980c971946e80b8e975fbebb4'
};
app.use(express.session({ store: new RedisStore(options), secret: 'naviam-848h7f744fsY7' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
var routes = require('./routes/routes')(app, github, passport, db);
app.use(express.static(path.join(__dirname, 'public')));

http.createServer(app).listen(app.get('port'), app.get('host'), function() {
  console.log(
	'Express server listening on port ' + app.get('port') +
	' at host ' + app.get('host'));
});<commit_msg>migrate to mongostore for sessions<commit_after>var http = require('http');
var express = require('express');
var db = require('./model/db');
var resources = require('express-resource');
var namespace = require('express-namespace');
var path = require('path');
var passport = require('passport');
//var RedisStore = require('connect-redis')(express);
var MongoStore = require('connect-mongo')(express);
var GitHubApi = require("github");
var github = new GitHubApi(
{
	version: "3.0.0",
	timeout: 5000//,
	// schema: 'http',
	// host: 'github.servicechannel.com/api/v3',
	// port: 80,
	// debug: true
});

var app = express();
app.set('host', process.env.IP || "127.0.0.1");
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
// var options = {
//	host: '127.0.0.1',//'nodejitsudb6553126701.redis.irstack.com',
//	port: '6379'//,
//	//pass: 'nodejitsudb6553126701.redis.irstack.com:f327cfe980c971946e80b8e975fbebb4'
// };
app.use(express.session({
	store: new MongoStore({
		url: 'mongodb://localhost/naviam-session'
	}),
	secret: 'naviam-848h7f744fsY7' }));
// app.use(express.session({ store: new RedisStore(options), secret: 'naviam-848h7f744fsY7' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
var routes = require('./routes/routes')(app, github, passport, db);
app.use(express.static(path.join(__dirname, 'public')));

http.createServer(app).listen(app.get('port'), app.get('host'), function() {
  console.log(
	'Express server listening on port ' + app.get('port') +
	' at host ' + app.get('host'));
});<|endoftext|>


<commit_before>"use strict";
/*jslint node:true, nomen: true */

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer  = require('multer');
var _ = require('underscore');

var pseudo = require('./pseudo-request');

var socketio = require('socket.io');
var chat = require('./routes/chat');

var routes = require('./routes/index');
var site = require('./routes/site');

// FIXME: what belongs in app.locals vs app.set/get
// FIXME: maybe just add properties to app?
// FIXME: specifically, a function for collection resolution (relative to dbdir)

var app = express();
var isDev = app.get('env') === 'development';
// app.locals are directly available to templates.
app.locals.pretty = isDev;
app.locals.title = 'Ki1r0y';
app.locals.fbAppId = '234339356748266';
process.title = app.locals.title.toLowerCase(); // so we can kill the server with shell (pkill kilroy)
// W3C recommends not aging more than a year. Express/connect expresses time in milliseconds (as for node generally).
app.locals.oneYearSeconds = 60 * 60 * 24 * 365;
app.locals.oneYearMs = app.locals.oneYearSeconds * 1000;

// app.get/set operates on an extensible group of application settings.
// For efficient uploads, we fs.rename files from uploadDir to db, but that won't work if they are on different file systems.
app.set('dbdir', path.resolve(__dirname, '../db'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Alas, morgan isn't smart enough to turn off colors when not a tty.
var logger = morgan((isDev && process.stdin.isTTY) ? 'dev' : 'combined');
pseudo.configure(logger);
function mutable(collection) { return express.static(path.join(app.get('dbdir'), 'mutable', collection)); }
function immutable(collection) { return express.static(path.join(app.get('dbdir'), 'immutable', collection), {maxAge: app.locals.oneYearMs}); }

// Puns: We could make all get/post/delete be computed with its own function, specific to the particular route.  But if
// we make the routes look like they correspond directly to static files on a file system, it gives us the opportunity
// to actually implement them that way if we want to. In fact, 'get' is implemented by just grabbing the named file, and
// 'delete' is implemented by a generic middleware that just deletes the named file. (post is separate) In both 'get'
// and 'delete, respective the middlewares convert, e.g., /thing/123.json to ../db/immutable/thing/123.json. We could
// have gone even further and had them also add the .json file extension, so that browsers would not have to include
// those four extra characters in the url. Instead, we chose to make the extension an explicit part of the url (rather
// than implied), as this serves as documentation, and helps various options for middleware figure out what they need to
// do without having to right special machinery.  For example, if the file extension was implicit, we could still use
// express.static, and give it a special function to set the Content-Type header to application/json. By making the
// extension explicit in the url, we don't need to. This gives us more flexibility to, e.g., replace express.static with
// something like Amazon S3 (slow!), which might not have the hook we need to do the transformation. For media, it makes
// it easier to inspect the uploaded files. In other words, we're trying to be "normal" in our conventions.

app.use(favicon(path.join(__dirname, 'public/images/favicon.ico')));
app.use(logger); // After favicon so that it isn't logged.
app.get('/', function (req, res) { _.noop(req); res.redirect('/site/hot.html'); });
app.use('/site/:id.html', site.standard);
app.use('/browser', express.static(path.join(__dirname, 'browser'))); // Not cached yet. Should be cached in production, with versioned filenames.
app.use(express.static(path.join(__dirname, 'public')));

// Uniform length names makes it easy to visually grok logs.
// Singular names are internal resource transfers.
app.use('/thing', immutable('thing'));
app.use('/thumb', immutable('thumb'));
app.use('/place', mutable('place'));

// Peculiar toplevel 'files'.
// See http://developers.facebook.com/docs/reference/javascript
app.get('/channel.html', function (req, res) {
    _.noop(req);
    res.header({Pragma: 'public',
                'Cache-Control': 'max-age="' + app.locals.oneYearSeconds + '"',
                Expires: new Date(Date.now() + app.locals.oneYearMs).toUTCString()});
    res.send('<script src="//connect.facebook.net/en_US/all.js"></script>');
});

// Plural names are toplevel user requests.
app.get('/people/:userIdtag', routes.user);
app.get('/places/:sceneIdtag', routes.scene);
app.get('/things/:objectIdtag', routes.scene);

// Handy for testing:
app.get('/q/scenesContaining/:objectIdtag', routes.refs);
app.get('/q/hasWord/:text', routes.citations);
app.get('/q/search/:text', routes.search);

// These aren't needed for any of the above.
app.use(bodyParser.json());    //app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({dest: path.resolve(__dirname, '../uploads/'), putSingleFilesInArray: true}));
app.use(cookieParser());

app.use('/media', immutable('media'));
//      '/fbusr (person) download isn't needed, and it would create issues for access control and when there are large numbers of user-created scenes.
app.get('/xport/:objectIdtag', routes.exportMedia); // A dynamically generated .zip of the media associated with a (composite) thing.

// Correspond to a get with the same url. (E.g., therefore 'put', not 'post')
app.put('/place/:id.json', routes.uploadPlace);
app.put('/thing/:id.json', routes.uploadObject);
app.put('/thumb/:id.png', routes.uploadThumbnail);
app.put('/media/:id', routes.uploadMedia); // Note that the file ending is part of the id.
app.delete('/:collection/:id.:ext', routes.delete); // For testing

app.post('/fbusr/:id.json', routes.updateUser);
app.post('/pRefs/:id.json', routes.uploadRefs);
// compatability with old ids
app.post('/fbusr/:id', routes.updateUser);
app.post('/place/:id', routes.uploadPlace);
app.post('/thing/:id', routes.uploadObject);
app.post('/thumb/:id.png', routes.uploadThumbnail);
app.post('/media/:id', routes.uploadMedia);

// If we get this far, nothing has picked up the request. Give a 404 error to the error handler.
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    _.noop(req, res);
    err.status = 404;
    next(err);
});

// error handlers are distinguished by their arity.
app.use(function (err, req, res, next) {
    _.noop(req, next);
    if (isDev && (err.status !== 404)) { console.error(err.stack); }
    if (err.code === 'ENOENT') { err.status = 404; }
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: err
    });
});

require('./realtime-garbage-collector').pingPong(app.get('dbdir'), 2000);
var server = require('http').createServer(app);
chat.setup(socketio(server));
server.listen(3000);
<commit_msg>Unity posting is limited - deal with it.<commit_after>"use strict";
/*jslint node:true, nomen: true */

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer  = require('multer');
var _ = require('underscore');

var pseudo = require('./pseudo-request');

var socketio = require('socket.io');
var chat = require('./routes/chat');

var routes = require('./routes/index');
var site = require('./routes/site');

// FIXME: what belongs in app.locals vs app.set/get
// FIXME: maybe just add properties to app?
// FIXME: specifically, a function for collection resolution (relative to dbdir)

var app = express();
var isDev = app.get('env') === 'development';
// app.locals are directly available to templates.
app.locals.pretty = isDev;
app.locals.title = 'Ki1r0y';
app.locals.fbAppId = '234339356748266';
process.title = app.locals.title.toLowerCase(); // so we can kill the server with shell (pkill kilroy)
// W3C recommends not aging more than a year. Express/connect expresses time in milliseconds (as for node generally).
app.locals.oneYearSeconds = 60 * 60 * 24 * 365;
app.locals.oneYearMs = app.locals.oneYearSeconds * 1000;

// app.get/set operates on an extensible group of application settings.
// For efficient uploads, we fs.rename files from uploadDir to db, but that won't work if they are on different file systems.
app.set('dbdir', path.resolve(__dirname, '../db'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Alas, morgan isn't smart enough to turn off colors when not a tty.
var logger = morgan((isDev && process.stdin.isTTY) ? 'dev' : 'combined');
pseudo.configure(logger);
function mutable(collection) { return express.static(path.join(app.get('dbdir'), 'mutable', collection)); }
function immutable(collection) { return express.static(path.join(app.get('dbdir'), 'immutable', collection), {maxAge: app.locals.oneYearMs}); }

// Puns: We could make all get/post/delete be computed with its own function, specific to the particular route.  But if
// we make the routes look like they correspond directly to static files on a file system, it gives us the opportunity
// to actually implement them that way if we want to. In fact, 'get' is implemented by just grabbing the named file, and
// 'delete' is implemented by a generic middleware that just deletes the named file. (post is separate) In both 'get'
// and 'delete, respective the middlewares convert, e.g., /thing/123.json to ../db/immutable/thing/123.json. We could
// have gone even further and had them also add the .json file extension, so that browsers would not have to include
// those four extra characters in the url. Instead, we chose to make the extension an explicit part of the url (rather
// than implied), as this serves as documentation, and helps various options for middleware figure out what they need to
// do without having to right special machinery.  For example, if the file extension was implicit, we could still use
// express.static, and give it a special function to set the Content-Type header to application/json. By making the
// extension explicit in the url, we don't need to. This gives us more flexibility to, e.g., replace express.static with
// something like Amazon S3 (slow!), which might not have the hook we need to do the transformation. For media, it makes
// it easier to inspect the uploaded files. In other words, we're trying to be "normal" in our conventions.

app.use(favicon(path.join(__dirname, 'public/images/favicon.ico')));
app.use(logger); // After favicon so that it isn't logged.
app.get('/', function (req, res) { _.noop(req); res.redirect('/site/hot.html'); });
app.use('/site/:id.html', site.standard);
app.use('/browser', express.static(path.join(__dirname, 'browser'))); // Not cached yet. Should be cached in production, with versioned filenames.
app.use(express.static(path.join(__dirname, 'public')));

// Uniform length names makes it easy to visually grok logs.
// Singular names are internal resource transfers.
app.use('/thing', immutable('thing'));
app.use('/thumb', immutable('thumb'));
app.use('/place', mutable('place'));

// Peculiar toplevel 'files'.
// See http://developers.facebook.com/docs/reference/javascript
app.get('/channel.html', function (req, res) {
    _.noop(req);
    res.header({Pragma: 'public',
                'Cache-Control': 'max-age="' + app.locals.oneYearSeconds + '"',
                Expires: new Date(Date.now() + app.locals.oneYearMs).toUTCString()});
    res.send('<script src="//connect.facebook.net/en_US/all.js"></script>');
});

// Plural names are toplevel user requests.
app.get('/people/:userIdtag', routes.user);
app.get('/places/:sceneIdtag', routes.scene);
app.get('/things/:objectIdtag', routes.scene);

// Handy for testing:
app.get('/q/scenesContaining/:objectIdtag', routes.refs);
app.get('/q/hasWord/:text', routes.citations);
app.get('/q/search/:text', routes.search);

// These aren't needed for any of the above.
app.use(bodyParser.json());
app.use(multer({dest: path.resolve(__dirname, '../uploads/'), putSingleFilesInArray: true})); // Media file uploads
app.use(cookieParser());

app.use('/media', immutable('media'));
//      '/fbusr (person) download isn't needed, and it would create issues for access control and when there are large numbers of user-created scenes.
app.get('/xport/:objectIdtag', routes.exportMedia); // A dynamically generated .zip of the media associated with a (composite) thing.

// Correspond to a get with the same url. (E.g., therefore 'put', not 'post')
app.put('/place/:id.json', routes.uploadPlace);
app.put('/thing/:id.json', routes.uploadObject);
app.put('/thumb/:id.png', routes.uploadThumbnail);
app.put('/media/:id', routes.uploadMedia); // Note that the file ending is part of the id.
app.delete('/:collection/:id.:ext', routes.delete); // For testing

app.post('/fbusr/:id.json', routes.updateUser);
app.post('/pRefs/:id.json', routes.uploadRefs);
// compatability with old ids
// Alas, Unity WWW class cannot do 'PUT'.
var fakeJson = [
    bodyParser.urlencoded({ extended: false }),
    function treatBodyAsJson(req, res, next) {
        _.noop(res);
        req.body.data = JSON.parse(req.body.data);
        next();
    }];
app.post('/place/:id', fakeJson, routes.uploadPlace);
app.post('/thing/:id', fakeJson, routes.uploadObject);
app.post('/refs/:id', fakeJson, routes.uploadRefs); // Old name for pRefs.
app.post('/thumb/:id', routes.uploadThumbnail);
app.post('/media/:id', routes.uploadMedia);

// If we get this far, nothing has picked up the request. Give a 404 error to the error handler.
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    _.noop(req, res);
    err.status = 404;
    next(err);
});

// error handlers are distinguished by their arity.
app.use(function (err, req, res, next) {
    _.noop(req, next);
    if (isDev && (err.status !== 404)) { console.error(err.stack); }
    if (err.code === 'ENOENT') { err.status = 404; }
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: err
    });
});

require('./realtime-garbage-collector').pingPong(app.get('dbdir'), 2000);
var server = require('http').createServer(app);
chat.setup(socketio(server));
server.listen(3000);
<|endoftext|>


<commit_before>var app = (function () {
    'use strict';

    var app = {};

    // Common initialization function (to be called from each page)
    app.initialize = function () {
        $('body').append(
			'
' +
				'
' +
					'

' +
					'

' +
					'

' +
				'
' +
			'
');

        $('#notification-message-close').click(function () {
            $('#notification-message').hide();
        });

        // After initialization, expose a common notification function
        app.showNotification = function (header, text) {
            $('#notification-message-header').text(header);
            $('#notification-message-body').text(text);
            $('#notification-message').slideDown('fast');
        };
    };

    return app;
})();<commit_msg>do we need this?<commit_after><|endoftext|>


<commit_before>var express       = require('express');
var path          = require('path');
var favicon       = require('serve-favicon');
var logger        = require('morgan');
var cookieParser  = require('cookie-parser');
var bodyParser    = require('body-parser');
var fs            = require('fs');
var socket_io     = require( "socket.io" );
var io            = socket_io();
var spawn = require('child_process').spawn;
var proc;
var vision;
const aifileName = './stream/image_ai.jpg';
const streamingfileName = './stream/image_stream.jpg';

var app = express();

// expose io to www
app.io = io;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// setup streaming URL
app.use('/', express.static(path.join(__dirname, 'stream')));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// display the local UI
app.get('/RPGi', function(req, res) {
  res.sendFile(__dirname + '/public/RPGi.html');
});

// clean up any leftover files
if (fs.existsSync(aifileName)) {
    fs.unlink(aifileName);
}
if (fs.existsSync(streamingfileName)) {
    fs.unlink(streamingfileName);
}

var sockets = {};

// Start watching the door
startWatching();
startGarageVision();

io.on('connection', function(socket) {

    // on inital connection send some status updates
    sockets[socket.id] = socket;

    setTimeout(function() {
        socket.emit('totalConnected', Object.keys(sockets).length);
        sendDoorStatus();
    }, 2000);

    socket.on('disconnect', function () {
        delete sockets[socket.id];
        io.emit('totalConnected', Object.keys(sockets).length);

        // no more sockets, kill the stream and the garagevision watch
        if (Object.keys(sockets).length == 0) {
            app.set('streamingFile', false);
            fs.unwatchFile('vision.log');
            stopStreaming();
            startWatching();
        }
    });

    socket.on('start-stream', function () {
        stopWatching();
        startStreaming(io);
    });

    // setup file watch for out from GarageVision
    fs.watchFile('vision.log', function (event, filename) {
        fs.readFile('vision.log', 'utf8', function (err,data) {
            if (err) {
                return console.log(err);
            }
            io.sockets.emit('doorStatus', data);
        });
    });

    socket.on('openclose-door', function () {
        // toggle the door remote
        var Gpio = require('onoff').Gpio,
            door = new Gpio(4, 'out');
        door.writeSync(0);
        setTimeout(function() {
            door.writeSync(1);
        }, 2000);
    });
});

function sendDoorStatus() {
    // pull status from the file and return it
    fs.readFile('vision.log', 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        io.sockets.emit('doorStatus', data);
    });
}

function startStreaming(io) {

    stopWatching();

    if (app.get('streamingFile')) {
        io.sockets.emit('liveStream', 'image_stream.jpg?_t=' + (Math.random() * 100000));
    } else {
        console.log('starting...');
        var args = ["-w", "320", "-h", "240", "-q", "15", "-o", streamingfileName, "-t", "999999999", "-tl", "500", "-md", "5"];
        proc = spawn('raspistill', args);

        app.set('streamingFile', true);

        fs.watchFile(streamingfileName, function (event, filename) {
            io.sockets.emit('liveStream', 'image_stream.jpg?_t=' + (Math.random() * 100000));
        })
    }
}

function startWatching() {

    stopStreaming();

    var args = ["-w", "320", "-h", "240", "-q", "15", "-o", aifileName, "-t", "999999999", "-tl", "15000", "-md", "5"];
    proc = spawn('raspistill', args);

    app.set('watchingFile', true);

}

function stopWatching() {
    app.set('watchingFile', false);
    if (proc) proc.kill();
    fs.unwatchFile(aifileName);
}

function stopStreaming() {
    if (Object.keys(sockets).length == 0) {
        app.set('streamingFile', false);
        if (proc) proc.kill();
        fs.unwatchFile(streamingfileName);
        if(fs.existsSync(streamingfileName)) {
            fs.unlink(streamingfileName);
        }
    }
}

function startGarageVision() {

    var PythonShell = require('python-shell');
    var options = {
        mode: 'text',
        scriptPath: './garagevision',
        args: [aifileName]
    };
    PythonShell.run('vision.py', options, function (err, results) {
        startGarageVision();
    });
}

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  // next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  // res.render('error', {
  //  message: err.message,
  //   error: {}
  // });
});

module.exports = app;
<commit_msg>Another attempt to get the python code to keep running in the background.<commit_after>var express       = require('express');
var path          = require('path');
var favicon       = require('serve-favicon');
var logger        = require('morgan');
var cookieParser  = require('cookie-parser');
var bodyParser    = require('body-parser');
var fs            = require('fs');
var socket_io     = require( "socket.io" );
var io            = socket_io();
var spawn = require('child_process').spawn;
var proc;
var vision;
const aifileName = './stream/image_ai.jpg';
const streamingfileName = './stream/image_stream.jpg';

var app = express();

// expose io to www
app.io = io;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('garagevision', false);

// setup streaming URL
app.use('/', express.static(path.join(__dirname, 'stream')));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// display the local UI
app.get('/RPGi', function(req, res) {
  res.sendFile(__dirname + '/public/RPGi.html');
});

// clean up any leftover files
if (fs.existsSync(aifileName)) {
    fs.unlink(aifileName);
}
if (fs.existsSync(streamingfileName)) {
    fs.unlink(streamingfileName);
}

var sockets = {};

// Start watching the door
startWatching();
var garagevision = setInterval(function() {
    if(!app.get('garagevision')) {
        startGarageVision();
    }
}, 15000);

io.on('connection', function(socket) {

    // on inital connection send some status updates
    sockets[socket.id] = socket;

    setTimeout(function() {
        socket.emit('totalConnected', Object.keys(sockets).length);
        sendDoorStatus();
    }, 2000);

    socket.on('disconnect', function () {
        delete sockets[socket.id];
        io.emit('totalConnected', Object.keys(sockets).length);

        // no more sockets, kill the stream and the garagevision watch
        if (Object.keys(sockets).length == 0) {
            app.set('streamingFile', false);
            fs.unwatchFile('vision.log');
            stopStreaming();
            startWatching();
        }
    });

    socket.on('start-stream', function () {
        stopWatching();
        startStreaming(io);
    });

    // setup file watch for out from GarageVision
    fs.watchFile('vision.log', function (event, filename) {
        fs.readFile('vision.log', 'utf8', function (err,data) {
            if (err) {
                return console.log(err);
            }
            io.sockets.emit('doorStatus', data);
        });
    });

    socket.on('openclose-door', function () {
        // toggle the door remote
        var Gpio = require('onoff').Gpio,
            door = new Gpio(4, 'out');
        door.writeSync(0);
        setTimeout(function() {
            door.writeSync(1);
        }, 2000);
    });
});

function sendDoorStatus() {
    // pull status from the file and return it
    fs.readFile('vision.log', 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        io.sockets.emit('doorStatus', data);
    });
}

function startStreaming(io) {

    stopWatching();

    if (app.get('streamingFile')) {
        io.sockets.emit('liveStream', 'image_stream.jpg?_t=' + (Math.random() * 100000));
    } else {
        console.log('starting...');
        var args = ["-w", "320", "-h", "240", "-q", "15", "-o", streamingfileName, "-t", "999999999", "-tl", "500", "-md", "5"];
        proc = spawn('raspistill', args);

        app.set('streamingFile', true);

        fs.watchFile(streamingfileName, function (event, filename) {
            io.sockets.emit('liveStream', 'image_stream.jpg?_t=' + (Math.random() * 100000));
        })
    }
}

function startWatching() {

    stopStreaming();

    var args = ["-w", "320", "-h", "240", "-q", "15", "-o", aifileName, "-t", "999999999", "-tl", "15000", "-md", "5"];
    proc = spawn('raspistill', args);

    app.set('watchingFile', true);

}

function stopWatching() {
    app.set('watchingFile', false);
    if (proc) proc.kill();
    fs.unwatchFile(aifileName);
}

function stopStreaming() {
    if (Object.keys(sockets).length == 0) {
        app.set('streamingFile', false);
        if (proc) proc.kill();
        fs.unwatchFile(streamingfileName);
        if(fs.existsSync(streamingfileName)) {
            fs.unlink(streamingfileName);
        }
    }
}

function startGarageVision() {

    app.set('garagevision', true);

    var PythonShell = require('python-shell');
    var options = {
        mode: 'text',
        scriptPath: './garagevision',
        args: [aifileName]
    };
    PythonShell.run('vision.py', options, function (err, results) {
        app.set('garagevision', false);
    });
}

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  // next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  // res.render('error', {
  //  message: err.message,
  //   error: {}
  // });
});

module.exports = app;
<|endoftext|>


<commit_before>var vv = vv || {
    song: {}
};
vv.song = (function(){
    var tag = function(song, keys, other) {
        for (i in keys) {
            var key = keys[i];
            if (key in song) {
                return song[key];
            }
        }
        return other;
    }

    var getOrElse = function(song, key, other) {
       if (key in song) {
           return song[key];
       } else if (key == "AlbumSort") {
           return tag(song, ["Album"], other);
       } else if (key == "ArtistSort") {
           return tag(song, ["Artist"], other);
       } else if (key == "AlbumArtist") {
           return tag(song, ["Artist"], other);
       } else if (key == "AlbumArtistSort") {
           return tag(song, ["AlbumArtist", "Artist"], other);
       } else if (key == "AlbumSort") {
           return tag(song, ["Album"], other);
       } else {
           return other;
       }
    }

    var get = function(song, key) {
        return getOrElse(song, key, '[no ' + key + ']');
    }
    var str = function(song, keys) {
        var sortkey = '';
        for (i in keys) {
            sortkey += getOrElse(song, keys[i], ' ')
        }
        return sortkey;
    }
    return {
        getOrElse: getOrElse,
        get: get,
        str: str,
    };
}());

var TREE = {
    "AlbumArtist": {
        "sort":
            ["AlbumArtist", "Date", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["AlbumArtist", "plain"],
             ["Album", "album"],
             ["Title", "song"]
            ],
    },
    "Genre": {
        "sort":
            ["Genre", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["Genre", "plain"],
             ["Album", "album"],
             ["Title", "song"],
            ]
    },
    "date": {
        "sort":
            ["Date", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["Date", "plain"],
             ["Album", "album"],
             ["Title", "song"],
            ]
    }
}

var song_tree_list = function(tree) {
    if (!tree) {
        tree = JSON.parse(sessionStorage.tree);
    }
    var ls = [];
    if (tree.length == 0) {
        return _song_tree_list_root();
    } else {
        return _song_tree_list_child(tree);
    }
};
var song_tree_down = function(key, value) {
    var tree = JSON.parse(sessionStorage.tree);
    tree.push([key, value]);
    sessionStorage.tree = JSON.stringify(tree);
};
var song_tree_abs = function(song) {
    var tree = JSON.parse(sessionStorage.tree);
    var i, root, key, selected;
    if (tree.length != 0) {
        tree = [tree[0]];
        root = tree[0][1];
        selected = TREE[root]["tree"];
        for (i in selected) {
            if (i == selected.length - 1) {
                break;
            }
            key = selected[i][0];
            tree.push([key, vv.song.get(song, key)]);
        }
        sessionStorage.tree = JSON.stringify(tree);
    }
};
var song_tree_up = function() {
    var tree = JSON.parse(sessionStorage.tree)
    if (tree.length > 0) {
        tree.pop();
    }
    sessionStorage.tree = JSON.stringify(tree)
};
var _song_tree_list_root = function() {
    var ret = [];
    var rootname = "";
    for (rootname in TREE) {
        ret.push({"root": rootname});
    }
    return ["root", ret, "plain"];
}
var _song_tree_list_child = function(tree) {
    var root = tree[0][1],
        library = JSON.parse(sessionStorage["library_" + root]),
        filters = {},
        key = TREE[root]["tree"][tree.length - 1][0],
        style = TREE[root]["tree"][tree.length - 1][1],
        song = {};
    for (leef in tree) {
        if (leef == 0) { continue; }
        filters[tree[leef][0]] = tree[leef][1];
    }
    library = filterSongs(library, filters);
    library = uniqSongs(library, key);
    return [key, library, style];
};

var MainView = function() {
    var mainview = function() {};
    var p = mainview.prototype;
    p.show_current = function() {
        $("#list").hide();
        $("#current").show();
    }
    p.show_list = function() {
        $("#current").hide();
        p.update_tree();
        $("#list").show();
    }
    p.up_list = function() {
        if ($("#current").css("display") == "none") {
            song_tree_up();
        } else {
            var current = JSON.parse(sessionStorage.current);
            song_tree_abs(current);
        }
        p.update_tree();
    }

    p.update_tree = function() {
        var current = {};
        var control = {};
        var tree = JSON.parse(sessionStorage.tree);
        var key, songs, style;
        var song = {};
        var root = "";
        // [key, songs, style] = song_tree_list(tree);
        var keysongs = song_tree_list(tree);
        key = keysongs[0];
        songs = keysongs[1];
        style = keysongs[2];
        if (style == "song") {
            current = JSON.parse(sessionStorage.current);
            control = JSON.parse(sessionStorage.control);
        }
        if (tree.length != 0) {
            root = tree[0][1];
        }
        $("#list ol").empty();
        for (i in songs) {
            song = songs[i];
            $("#list ol").append("

");
            var added = $("#list ol li:last-child");
            added.attr("key", vv.song.get(song, key));
            added.attr("uri", song["file"]);
            if (style == "song") {
                added.append(""+vv.song.get(song, "TrackNumber")+"");
                added.append(""+vv.song.get(song, "Title")+"");
                if (vv.song.get(song, "Artist") != vv.song.get(song, "AlbumArtist")) {
                    added.append(""+vv.song.get(song, "Artist")+"");
                }
                if (vv.song.get(song, "file") == vv.song.get(current, "file")) {
                    added.append(""+vv.song.get(song, "Length")+"");
                    added.append("/");
                }
                added.append(""+vv.song.get(song, "Length")+"");
            } else if (style == "album") {
                added.append(""+vv.song.get(song, "Date")+"");
                added.append(""+vv.song.get(song, "Album")+"");
                added.append(""+vv.song.get(song, "AlbumArtist")+"");
            } else {
                added.text(vv.song.get(song, key));
            }
        }
        $("#list ol li").bind("click", function() {
            var value = $(this).attr("key"),
                uri = $(this).attr("uri");
            if (tree.length == 0 || tree.length != TREE[root]["tree"].length) {
                song_tree_down(key, value);
                p.show_list();
            } else {
                $.ajax({
                    type: "POST",
                    url: "/api/songs",
                    contentType: 'application/json',
                    data: JSON.stringify(
                            {"action": "sort",
                             "keys": TREE[root]["sort"],
                             "uri": uri
                            }),
                    cache: false,
                    success: function(data, status) {
				        if (status == "success" && data["errors"] == null) {
				        }
			        },
                });
            }
            return false;
        });
    };
    return mainview;
}();

var update_song_request = function() {
    $.ajax({
        type: "GET",
        url: "api/songs/current",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                sessionStorage.current = JSON.stringify(data["data"])
                $("#current .title").text(data["data"]["Title"])
                $("#current .artist").text(data["data"]["Artist"])
                var key;
                $("#current .detail").empty();
                for (key in data["data"]) {
                    if (key == "Title" || key == "Artist") {
                        continue;
                    }
                    $("#current .detail").append("
" + key + ": " + data["data"][key] + "
");
                }
                var tree = JSON.parse(sessionStorage.tree);
                if (tree.length != 0 && tree.length == TREE[tree[0][1]]["tree"].length) {
                    song_tree_abs(data["data"]);
                }
                // update elapsed tag
                mainview.update_tree();
			}
		},
    })
};

var update_control_data_request = function() {
    $.ajax({
        type: "GET",
        url: "api/control",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                sessionStorage.control = JSON.stringify(data["data"])
                refreash_control_data();
			}
		},
    })
    refreash_control_data();
};

var refreash_control_data = function() {
    data = JSON.parse(sessionStorage.control)
    if ('state' in data) {
        var elapsed = parseInt(data["song_elapsed"] * 1000)
        var current = elapsed
        var last_modified = parseInt(data["last_modified"] * 1000)
        var date = new Date()
        if (data["state"] == "play") {
            current += date.getTime() - last_modified
        }
        var label = parseSongTime(current / 1000);
        if ($(".elapsed").text() != label) {
            $(".elapsed").text(label);
        }
    }
};

var update_library_request = function() {
    $.ajax({
        type: "GET",
        url: "api/library",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                sessionStorage["library_AlbumArtist"] = JSON.stringify(
                    sortSongs(data["data"], TREE["AlbumArtist"]["sort"]));
                sessionStorage["library_Genre"] = JSON.stringify(
                    sortSongs(data["data"], TREE["Genre"]["sort"]));
			}
		},
    })
}

function parseSongTime(val) {
    var current = parseInt(val)
    var min = parseInt(current / 60)
    var sec = current % 60
    return min + ':' + ("0" + sec).slice(-2)
}

function sortSongs(songs, keys) {
    return songs.map(function(song) {
        return [song, vv.song.str(song, keys)]
    }).sort(function (a, b) {
        if (a[1] < b[1]) { return -1; } else { return 1; };
    }).map(function(s) { return s[0]; });
}
function uniqSongs(songs, key) {
    return songs.filter(function (song, i , self) {
        if (i == 0) {
            return true;
        } else if (vv.song.getOrElse(song, key, ' ') != vv.song.getOrElse(self[i - 1], key, ' ')) {
            return true;
        } else {
            return false;
        }
    });
}
function filterSongs(songs, filters) {
    return songs.filter(function(song, i, self) {
        for (f in filters) {
            if (vv.song.get(song, f) != filters[f]) {
                return false;
            }
        }
        return true;
    });
}

function getOrElse(m, k, v) {
    return k in m? m[k] : v;
}

$(document).ready(function(){
    mainview = new MainView();
    $("#menu .up").bind("click", function() {
        mainview.up_list();
        mainview.show_list();
        return false;
    });
    $("#menu .back").bind("click", function() {
        mainview.show_current();
        return false;
    });
    $("#menu .reset").bind("click", function() {
        sessionStorage.tree = "[]";
        sessionStorage.current = "{}";
        sessionStorage.control = "{}";
        sessionStorage.playlist = "[]";
        sessionStorage.library = "[]";
        sessionStorage.library_AlbumArtist = "[]";
        sessionStorage.library_Genre = "[]";
        return false;
    });
    $("#playback .prev").bind("click", function() {
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": "prev"},
            cache: false
        })
        return false;
    });
    $("#playback .play").bind("click", function() {
        var state = getOrElse(JSON.parse(sessionStorage.control), "state", "stopped");
        var action = state == "play" ? "pause" : "play"
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": action},
            cache: false
        })
        return false;
    });
    $("#playback .next").bind("click", function() {
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": "next"},
            cache: false
        })
        return false;
    });

    function polling() {
        update_song_request()
        update_control_data_request()
        update_library_request()
		setTimeout(polling, 1000);
    }
	polling();
});
<commit_msg>move xxSongs to vv.songs.xx<commit_after>var vv = vv || {
    song: {},
    songs: {},
};
vv.song = (function(){
    var tag = function(song, keys, other) {
        for (i in keys) {
            var key = keys[i];
            if (key in song) {
                return song[key];
            }
        }
        return other;
    }
    var getOrElse = function(song, key, other) {
       if (key in song) {
           return song[key];
       } else if (key == "AlbumSort") {
           return tag(song, ["Album"], other);
       } else if (key == "ArtistSort") {
           return tag(song, ["Artist"], other);
       } else if (key == "AlbumArtist") {
           return tag(song, ["Artist"], other);
       } else if (key == "AlbumArtistSort") {
           return tag(song, ["AlbumArtist", "Artist"], other);
       } else if (key == "AlbumSort") {
           return tag(song, ["Album"], other);
       } else {
           return other;
       }
    }
    var get = function(song, key) {
        return getOrElse(song, key, '[no ' + key + ']');
    }
    var str = function(song, keys) {
        var sortkey = '';
        for (i in keys) {
            sortkey += getOrElse(song, keys[i], ' ')
        }
        return sortkey;
    }
    return {
        getOrElse: getOrElse,
        get: get,
        str: str,
    };
}());
vv.songs = (function(){
    var sort = function(songs, keys) {
        return songs.map(function(song) {
            return [song, vv.song.str(song, keys)]
        }).sort(function (a, b) {
            if (a[1] < b[1]) { return -1; } else { return 1; };
        }).map(function(s) { return s[0]; });
    }
    var uniq = function(songs, key) {
        return songs.filter(function (song, i , self) {
            if (i == 0) {
                return true;
            } else if (vv.song.getOrElse(song, key, ' ') != vv.song.getOrElse(self[i - 1], key, ' ')) {
                return true;
            } else {
                return false;
            }
        });
    }
    var filter = function(songs, filters) {
        return songs.filter(function(song, i, self) {
            for (f in filters) {
                if (vv.song.get(song, f) != filters[f]) {
                    return false;
                }
            }
            return true;
        });
    }
    return {
        sort: sort,
        uniq: uniq,
        filter: filter,
    };
}());

var TREE = {
    "AlbumArtist": {
        "sort":
            ["AlbumArtist", "Date", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["AlbumArtist", "plain"],
             ["Album", "album"],
             ["Title", "song"]
            ],
    },
    "Genre": {
        "sort":
            ["Genre", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["Genre", "plain"],
             ["Album", "album"],
             ["Title", "song"],
            ]
    },
    "date": {
        "sort":
            ["Date", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["Date", "plain"],
             ["Album", "album"],
             ["Title", "song"],
            ]
    }
}

var song_tree_list = function(tree) {
    if (!tree) {
        tree = JSON.parse(sessionStorage.tree);
    }
    var ls = [];
    if (tree.length == 0) {
        return _song_tree_list_root();
    } else {
        return _song_tree_list_child(tree);
    }
};
var song_tree_down = function(key, value) {
    var tree = JSON.parse(sessionStorage.tree);
    tree.push([key, value]);
    sessionStorage.tree = JSON.stringify(tree);
};
var song_tree_abs = function(song) {
    var tree = JSON.parse(sessionStorage.tree);
    var i, root, key, selected;
    if (tree.length != 0) {
        tree = [tree[0]];
        root = tree[0][1];
        selected = TREE[root]["tree"];
        for (i in selected) {
            if (i == selected.length - 1) {
                break;
            }
            key = selected[i][0];
            tree.push([key, vv.song.get(song, key)]);
        }
        sessionStorage.tree = JSON.stringify(tree);
    }
};
var song_tree_up = function() {
    var tree = JSON.parse(sessionStorage.tree)
    if (tree.length > 0) {
        tree.pop();
    }
    sessionStorage.tree = JSON.stringify(tree)
};
var _song_tree_list_root = function() {
    var ret = [];
    var rootname = "";
    for (rootname in TREE) {
        ret.push({"root": rootname});
    }
    return ["root", ret, "plain"];
}
var _song_tree_list_child = function(tree) {
    var root = tree[0][1],
        library = JSON.parse(sessionStorage["library_" + root]),
        filters = {},
        key = TREE[root]["tree"][tree.length - 1][0],
        style = TREE[root]["tree"][tree.length - 1][1],
        song = {};
    for (leef in tree) {
        if (leef == 0) { continue; }
        filters[tree[leef][0]] = tree[leef][1];
    }
    library = vv.songs.filter(library, filters);
    library = vv.songs.uniq(library, key);
    return [key, library, style];
};

var MainView = function() {
    var mainview = function() {};
    var p = mainview.prototype;
    p.show_current = function() {
        $("#list").hide();
        $("#current").show();
    }
    p.show_list = function() {
        $("#current").hide();
        p.update_tree();
        $("#list").show();
    }
    p.up_list = function() {
        if ($("#current").css("display") == "none") {
            song_tree_up();
        } else {
            var current = JSON.parse(sessionStorage.current);
            song_tree_abs(current);
        }
        p.update_tree();
    }

    p.update_tree = function() {
        var current = {};
        var control = {};
        var tree = JSON.parse(sessionStorage.tree);
        var key, songs, style;
        var song = {};
        var root = "";
        // [key, songs, style] = song_tree_list(tree);
        var keysongs = song_tree_list(tree);
        key = keysongs[0];
        songs = keysongs[1];
        style = keysongs[2];
        if (style == "song") {
            current = JSON.parse(sessionStorage.current);
            control = JSON.parse(sessionStorage.control);
        }
        if (tree.length != 0) {
            root = tree[0][1];
        }
        $("#list ol").empty();
        for (i in songs) {
            song = songs[i];
            $("#list ol").append("

");
            var added = $("#list ol li:last-child");
            added.attr("key", vv.song.get(song, key));
            added.attr("uri", song["file"]);
            if (style == "song") {
                added.append(""+vv.song.get(song, "TrackNumber")+"");
                added.append(""+vv.song.get(song, "Title")+"");
                if (vv.song.get(song, "Artist") != vv.song.get(song, "AlbumArtist")) {
                    added.append(""+vv.song.get(song, "Artist")+"");
                }
                if (vv.song.get(song, "file") == vv.song.get(current, "file")) {
                    added.append(""+vv.song.get(song, "Length")+"");
                    added.append("/");
                }
                added.append(""+vv.song.get(song, "Length")+"");
            } else if (style == "album") {
                added.append(""+vv.song.get(song, "Date")+"");
                added.append(""+vv.song.get(song, "Album")+"");
                added.append(""+vv.song.get(song, "AlbumArtist")+"");
            } else {
                added.text(vv.song.get(song, key));
            }
        }
        $("#list ol li").bind("click", function() {
            var value = $(this).attr("key"),
                uri = $(this).attr("uri");
            if (tree.length == 0 || tree.length != TREE[root]["tree"].length) {
                song_tree_down(key, value);
                p.show_list();
            } else {
                $.ajax({
                    type: "POST",
                    url: "/api/songs",
                    contentType: 'application/json',
                    data: JSON.stringify(
                            {"action": "sort",
                             "keys": TREE[root]["sort"],
                             "uri": uri
                            }),
                    cache: false,
                    success: function(data, status) {
				        if (status == "success" && data["errors"] == null) {
				        }
			        },
                });
            }
            return false;
        });
    };
    return mainview;
}();

var update_song_request = function() {
    $.ajax({
        type: "GET",
        url: "api/songs/current",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                sessionStorage.current = JSON.stringify(data["data"])
                $("#current .title").text(data["data"]["Title"])
                $("#current .artist").text(data["data"]["Artist"])
                var key;
                $("#current .detail").empty();
                for (key in data["data"]) {
                    if (key == "Title" || key == "Artist") {
                        continue;
                    }
                    $("#current .detail").append("
" + key + ": " + data["data"][key] + "
");
                }
                var tree = JSON.parse(sessionStorage.tree);
                if (tree.length != 0 && tree.length == TREE[tree[0][1]]["tree"].length) {
                    song_tree_abs(data["data"]);
                }
                // update elapsed tag
                mainview.update_tree();
			}
		},
    })
};

var update_control_data_request = function() {
    $.ajax({
        type: "GET",
        url: "api/control",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                sessionStorage.control = JSON.stringify(data["data"])
                refreash_control_data();
			}
		},
    })
    refreash_control_data();
};

var refreash_control_data = function() {
    data = JSON.parse(sessionStorage.control)
    if ('state' in data) {
        var elapsed = parseInt(data["song_elapsed"] * 1000)
        var current = elapsed
        var last_modified = parseInt(data["last_modified"] * 1000)
        var date = new Date()
        if (data["state"] == "play") {
            current += date.getTime() - last_modified
        }
        var label = parseSongTime(current / 1000);
        if ($(".elapsed").text() != label) {
            $(".elapsed").text(label);
        }
    }
};

var update_library_request = function() {
    $.ajax({
        type: "GET",
        url: "api/library",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                sessionStorage["library_AlbumArtist"] = JSON.stringify(
                    vv.songs.sort(data["data"], TREE["AlbumArtist"]["sort"]));
                sessionStorage["library_Genre"] = JSON.stringify(
                    vv.songs.sort(data["data"], TREE["Genre"]["sort"]));
			}
		},
    })
}

function parseSongTime(val) {
    var current = parseInt(val)
    var min = parseInt(current / 60)
    var sec = current % 60
    return min + ':' + ("0" + sec).slice(-2)
}

function getOrElse(m, k, v) {
    return k in m? m[k] : v;
}

$(document).ready(function(){
    mainview = new MainView();
    $("#menu .up").bind("click", function() {
        mainview.up_list();
        mainview.show_list();
        return false;
    });
    $("#menu .back").bind("click", function() {
        mainview.show_current();
        return false;
    });
    $("#menu .reset").bind("click", function() {
        sessionStorage.tree = "[]";
        sessionStorage.current = "{}";
        sessionStorage.control = "{}";
        sessionStorage.playlist = "[]";
        sessionStorage.library = "[]";
        sessionStorage.library_AlbumArtist = "[]";
        sessionStorage.library_Genre = "[]";
        return false;
    });
    $("#playback .prev").bind("click", function() {
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": "prev"},
            cache: false
        })
        return false;
    });
    $("#playback .play").bind("click", function() {
        var state = getOrElse(JSON.parse(sessionStorage.control), "state", "stopped");
        var action = state == "play" ? "pause" : "play"
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": action},
            cache: false
        })
        return false;
    });
    $("#playback .next").bind("click", function() {
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": "next"},
            cache: false
        })
        return false;
    });

    function polling() {
        update_song_request()
        update_control_data_request()
        update_library_request()
		setTimeout(polling, 1000);
    }
	polling();
});
<|endoftext|>


<commit_before>var config = require('./config'),
    httpServer,
    express = require('express'),
    partials = require('express-partials'),
    Promise = require('promise'),
    authManager = require('./lib/authentication'),
    passport = authManager.passport,
    socketAuthenticator = require('./lib/socket-auth'),
    queue = require('./lib/pull-queue.js'),
    pullManager = require('./lib/pull-manager'),
    dbManager = require('./lib/db-manager'),
    gitManager = require('./lib/git-manager'),
    Pull = require('./models/pull'),
    Signature = require('./models/signature'),
    mainController = require('./controllers/main'),
    hooksController = require('./controllers/githubHooks'),
    reqLogger = require('debug')('pulldasher:server:request');
    resLogger = require('debug')('pulldasher:server:response');

var app = express();

httpServer = require('http').createServer(app)

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

/**
 * Middleware
 */
app.use("/public", express.static(__dirname + '/public'));
app.use(partials());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: config.session.secret}));
app.use(passport.initialize());
app.use(passport.session());

app.use(function(req, res, next) {
   reqLogger(req.headers);
   resLogger(res.headers);
   next();
});;

/**
 * Routes
 */
authManager.setupRoutes(app);
app.get('/',         mainController.index);
app.post('/hooks/main', hooksController.main);

/**
 * Accepts a promise that resolves to a pull, adds it to the view, updates the
 * DB to reflect any changes.
 */
function update(pullPromise) {
   return pullPromise.then(function(pull) {
      return dbManager.updatePull(pull).then(function() {
         var updates = [];

         if (pull.commitStatus) {
            updates.push(
               dbManager.updateCommitStatus(pull.commitStatus)
            );
         }

         updates.push(
            // Delete all signatures related to this pull from the DB
            // before we rewrite them to avoid duplicates.
            dbManager.deleteSignatures(pull.data.number).then(function() {
               pull.signatures.sort(Signature.compare);
               return dbManager.insertSignatures(pull.signatures);
            })
         );

         pull.comments.forEach(function(comment) {
            updates.push(
               dbManager.updateComment(comment)
            );
         });

         return Promise.all(updates);
      });
   });
}

/**
 * Refreshes the specified pull.
 */
function refresh(number) {
   var githubPull = gitManager.getPull(number);

   queue.pause();

   githubPull.done(function(gPull) {
      var pullPromise = gitManager.parse(gPull);
      update(pullPromise).done(function() {
         queue.resume();
      });
   });
}

/**
 * Refreshes all open pulls.
 */
function refreshAll() {
   var githubPulls = gitManager.getAllPulls();

   queue.pause();

   githubPulls.done(function(gPulls) {
      var pullsUpdated = gPulls.map(function(gPull) {
         var pull = gitManager.parse(gPull);

         return new Promise(function(resolve, reject) {
            update(pull).done(function() {
               resolve();
            });
         });
      });

      Promise.all(pullsUpdated).done(function() {
         queue.resume();
      });
   });
}

// Called, to populate app, on startup.
refreshAll();

/*
@TODO: Update pulls which were open last time Pulldasher ran but are closed now.
dbManager.closeStalePulls();
*/

//====================================================
// Socket.IO

var io = require('socket.io').listen(httpServer);
io.sockets.on('connection', function (socket) {
   socket.on('authenticate', function(token) {
      var user = socketAuthenticator.retrieveUser(token);
      if (user) {
         socket.emit('authenticated');
         pullManager.addSocket(socket);
         clearTimeout(autoDisconnect);
      } else {
         socket.disconnect();
      }
   });

   socket.on('refresh', function(number) {
      if (number) {
         refresh(number);
      } else {
         refreshAll();
      }
   });

   var autoDisconnect = setTimeout(function() {
      socket.disconnect();
   }, 10*1000);
});

httpServer.listen(config.port);
<commit_msg>Debugging: only log request method and url<commit_after>var config = require('./config'),
    httpServer,
    express = require('express'),
    partials = require('express-partials'),
    Promise = require('promise'),
    authManager = require('./lib/authentication'),
    passport = authManager.passport,
    socketAuthenticator = require('./lib/socket-auth'),
    queue = require('./lib/pull-queue.js'),
    pullManager = require('./lib/pull-manager'),
    dbManager = require('./lib/db-manager'),
    gitManager = require('./lib/git-manager'),
    Pull = require('./models/pull'),
    Signature = require('./models/signature'),
    mainController = require('./controllers/main'),
    hooksController = require('./controllers/githubHooks'),
    reqLogger = require('debug')('pulldasher:server:request');
    resLogger = require('debug')('pulldasher:server:response');

var app = express();

httpServer = require('http').createServer(app)

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

/**
 * Middleware
 */
app.use("/public", express.static(__dirname + '/public'));
app.use(partials());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: config.session.secret}));
app.use(passport.initialize());
app.use(passport.session());

app.use(function(req, res, next) {
   reqLogger("%s %s", req.method, req.url);
   next();
});;

/**
 * Routes
 */
authManager.setupRoutes(app);
app.get('/',         mainController.index);
app.post('/hooks/main', hooksController.main);

/**
 * Accepts a promise that resolves to a pull, adds it to the view, updates the
 * DB to reflect any changes.
 */
function update(pullPromise) {
   return pullPromise.then(function(pull) {
      return dbManager.updatePull(pull).then(function() {
         var updates = [];

         if (pull.commitStatus) {
            updates.push(
               dbManager.updateCommitStatus(pull.commitStatus)
            );
         }

         updates.push(
            // Delete all signatures related to this pull from the DB
            // before we rewrite them to avoid duplicates.
            dbManager.deleteSignatures(pull.data.number).then(function() {
               pull.signatures.sort(Signature.compare);
               return dbManager.insertSignatures(pull.signatures);
            })
         );

         pull.comments.forEach(function(comment) {
            updates.push(
               dbManager.updateComment(comment)
            );
         });

         return Promise.all(updates);
      });
   });
}

/**
 * Refreshes the specified pull.
 */
function refresh(number) {
   var githubPull = gitManager.getPull(number);

   queue.pause();

   githubPull.done(function(gPull) {
      var pullPromise = gitManager.parse(gPull);
      update(pullPromise).done(function() {
         queue.resume();
      });
   });
}

/**
 * Refreshes all open pulls.
 */
function refreshAll() {
   var githubPulls = gitManager.getAllPulls();

   queue.pause();

   githubPulls.done(function(gPulls) {
      var pullsUpdated = gPulls.map(function(gPull) {
         var pull = gitManager.parse(gPull);

         return new Promise(function(resolve, reject) {
            update(pull).done(function() {
               resolve();
            });
         });
      });

      Promise.all(pullsUpdated).done(function() {
         queue.resume();
      });
   });
}

// Called, to populate app, on startup.
refreshAll();

/*
@TODO: Update pulls which were open last time Pulldasher ran but are closed now.
dbManager.closeStalePulls();
*/

//====================================================
// Socket.IO

var io = require('socket.io').listen(httpServer);
io.sockets.on('connection', function (socket) {
   socket.on('authenticate', function(token) {
      var user = socketAuthenticator.retrieveUser(token);
      if (user) {
         socket.emit('authenticated');
         pullManager.addSocket(socket);
         clearTimeout(autoDisconnect);
      } else {
         socket.disconnect();
      }
   });

   socket.on('refresh', function(number) {
      if (number) {
         refresh(number);
      } else {
         refreshAll();
      }
   });

   var autoDisconnect = setTimeout(function() {
      socket.disconnect();
   }, 10*1000);
});

httpServer.listen(config.port);
<|endoftext|>


<commit_before>(function(){

var app = angular.module('wsi', ['ngMaterial'])
    .config(function($mdThemingProvider, $httpProvider) {
        $mdThemingProvider.theme('default')
            .primaryPalette('green')
            .accentPalette('blue');

		$httpProvider.defaults.headers.common = {};
		$httpProvider.defaults.headers.post = {};
		$httpProvider.defaults.headers.put = {};
		$httpProvider.defaults.headers.patch = {};
		$httpProvider.defaults.headers.common["Content-Type"] = "text/plain";
 		$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
 		$httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS';
		$httpProvider.defaults.headers.common['Ocp-Apim-Subscription-Key'] = '';
		$httpProvider.defaults.useXDomain = true;
		delete $httpProvider.defaults.headers.common['X-Requested-With'];

});

app.controller('WsiCtrl', function($scope, $http){

	$scope.ben = {
		marketCap: 1,
		currentAssets: 1,
		currentDebt: 1,
		longTermDebt: 1,
		workingCapital: 1,
		yrsPositiveIncome: '',
		yrsDividend: '',
		yrsGrowth: '',
		pe: 1,
		pb: 1,
		dividend: 1
	};

	$scope.ratios = {};

	$scope.calculate = function() {
		console.log($scope.ben);
	};

	$scope.getCompanyData = function() {
		$scope.getBalanceSheet();
		$scope.getStockQuote();
		$scope.getRatios();
	};

	$scope.getBalanceSheet = function() {
		var url = 'https://services.last10k.com/v1/company/' + $scope.ben.ticker + '/balancesheet?formType=10-K&filingOrder=0';
		$http.get(url)
			.then(function(data){
				console.log("balance", data);
				$scope.balance = data.data;
				var bal = data.data.Data;
				$scope.balance.longTermDebtCoverageRatio = (bal.AssetsCurrent - bal.LiabilitiesCurrent) / bal.LongTermDebtNoncurrent;
				//console.log(data.data.AssetsCurrent);
			}, function(data){
				alert('error');
			});
	};

	$scope.getStockQuote = function() {
		var url = 'https://services.last10k.com/v1/company/' + $scope.ben.ticker + '/quote'
		$http.get(url)
			.then(function(data){
				console.log("quote", data);
				$scope.quote = data.data;
			}, function(data){
				alert('error');
			});
	};

	$scope.getRatios = function() {
		var url = 'https://services.last10k.com/v1/company/' + $scope.ben.ticker + '/ratios'
		$http.get(url)
			.then(function(data){
				console.log("ratios", data);
				$scope.ratios.currentRatio = data.data.CurrentRatio.Recent["Latest Qtr"];
				$scope.ratios.dividend = data.data.Dividends.Recent.TTM;
				$scope.ratios.quick = data.data.QuickRatio.Recent["Latest Qtr"];
				//console.log(data.data.WorkingCapital.Historical);

				var workingCapital = data.data.WorkingCapital.Historical[Object.keys(data.data.WorkingCapital.Historical)[Object.keys(data.data.WorkingCapital.Historical).length - 1]];
				var longTermDebt = data.data.LongTermDebt.Recent["Latest Qtr"];
				//console.log(workingCapital, longTermDebt);
				//$scope.ratios.longTermToWorking =
			}, function(data){
				alert('error');
			});
	};

});
})();<commit_msg>updates to main app<commit_after>(function(){

var app = angular.module('wsi', ['ngMaterial'])
    .config(function($mdThemingProvider, $httpProvider) {
        $mdThemingProvider.theme('default')
            .primaryPalette('green')
            .accentPalette('blue');

		$httpProvider.defaults.headers.common = {};
		$httpProvider.defaults.headers.post = {};
		$httpProvider.defaults.headers.put = {};
		$httpProvider.defaults.headers.patch = {};
		$httpProvider.defaults.headers.common["Content-Type"] = "text/plain";
 		$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
 		$httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS';
		$httpProvider.defaults.headers.common['Ocp-Apim-Subscription-Key'] = '5053da1874224fb1a0de3c4cd5f51a60';
		$httpProvider.defaults.useXDomain = true;
		delete $httpProvider.defaults.headers.common['X-Requested-With'];

});

app.controller('WsiCtrl', function($scope, $http){

	$scope.ben = {
		marketCap: 1,
		currentAssets: 1,
		currentDebt: 1,
		longTermDebt: 1,
		workingCapital: 1,
		yrsPositiveIncome: '',
		yrsDividend: '',
		yrsGrowth: '',
		pe: 1,
		pb: 1,
		dividend: 1
	};

	$scope.ratios = {};

	$scope.calculate = function() {
		console.log($scope.ben);
	};

	$scope.getCompanyData = function() {
		$scope.getBalanceSheet();
		$scope.getStockQuote();
		$scope.getRatios();
	};

	$scope.getBalanceSheet = function() {
		var url = 'https://services.last10k.com/v1/company/' + $scope.ben.ticker + '/balancesheet?formType=10-K&filingOrder=0';
		$http.get(url)
			.then(function(data){
				console.log("balance", data);
				$scope.balance = data.data;
				var bal = data.data.Data;
				$scope.balance.longTermDebtCoverageRatio = (bal.AssetsCurrent - bal.LiabilitiesCurrent) / bal.LongTermDebtNoncurrent;
				//console.log(data.data.AssetsCurrent);
			}, function(data){
				alert('error');
			});
	};

	$scope.getStockQuote = function() {
		var url = 'https://services.last10k.com/v1/company/' + $scope.ben.ticker + '/quote'
		$http.get(url)
			.then(function(data){
				console.log("quote", data);
				$scope.quote = data.data;
			}, function(data){
				alert('error');
			});
	};

	$scope.getRatios = function() {
		var url = 'https://services.last10k.com/v1/company/' + $scope.ben.ticker + '/ratios'
		$http.get(url)
			.then(function(data){
				console.log("ratios", data);
				$scope.ratios.currentRatio = data.data.CurrentRatio.Recent["Latest Qtr"];
				$scope.ratios.dividend = data.data.Dividends.Recent.TTM;
				$scope.ratios.quick = data.data.QuickRatio.Recent["Latest Qtr"];
				//console.log(data.data.WorkingCapital.Historical);

				var workingCapital = data.data.WorkingCapital.Historical[Object.keys(data.data.WorkingCapital.Historical)[Object.keys(data.data.WorkingCapital.Historical).length - 1]];
				var longTermDebt = data.data.LongTermDebt.Recent["Latest Qtr"];
				//console.log(workingCapital, longTermDebt);
				//$scope.ratios.longTermToWorking =
			}, function(data){
				alert('error');
			});
	};

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