<commit_before>/*
TALLY VOTES IN JAVASCRIPT PAIRING CHALLENGE
WE WORKED ON THIS CHALLENGE: Paul Gouron & Lars Johnson
THIS CHALLENGE TOOK US 3 HOURS

##########################################################################################################
THESE ARE THE VOTES CAST BY EACH STUDENT. DO NOT ALTER THESE OBJECTS
*/

var votes = {
  // Voter  - -  Index 1 --    Index 2 ---     Index 3 --               Index-4
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

// Once the votes have been tallied, assign each officer position the name of the
// student who received the most votes.

var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

var job = Object.getOwnPropertyNames(officers).sort();
// console.log(job)

/*
Set job equal to property names of the officers object: [president, vicePresident, secretary, treasurer]
We use sort to ensure the object's property names wiLl always appear in the same order (as in a loop)

##########################################################################################################
PSEUDOCODE

NOTES: This challenge is about iterating over an object (votes) ccontaining individual voters and their vote
       counts. We must iterate over the value of each property and populate the voteCount object accordingly

       The name of each student receiving a vote for an office should become a property of the respective
       office in voteCount. So for example, after Alex's votes have been tallied voteCount would be:

      var voteCount = {
        president: { Bob: 1 },
        vicePresident: { Devin: 1 },
        secretary: { Gail: 1 },
        treasurer: { Kerry: 1 } }

   INPUT: An object called votes with list of voters and each of their candidates for four different roles
          An object called voteCount with four empty properties (one for each of the four different roles)
          An object called officers with four undefined properties (one for each of the four different roles)

  OUTPUT: We must populate the voteCount object with the number of votes for each candidate in all four roles
          We must populate the officers object with the names of each winner in all four roles

ABOUT TALLYVOTES
  Create a function called tallyVotes to iterate through each voter in votes
    Each voter is voting for 4 people across 4 different jobs
    We created the variable (job) above in order to iterate through every property (job type)
  For each voter in votes...
    TallyVotes iterates through the 4 jobs and their values (candidates) to populate voteCount

ABOUT ELECTIONWINNER
  Create a function called electionWinner to iterate through each property of each the voteCount object
  In other words, iterate through each candidate and the number of votes they received
  Create a variable (record) and store the highest amount of votes for each job
  The winner for each job will be the person with the highest voteCount in that job category

##########################################################################################################
INITIAL SOLUTION

function tallyVotes(){

// Iterate through each voter
for (var voter in votes){

  // iterate through each vote object (with 4 properties - one for each job)
  for (var i=0; i < job.length; i++){

    // create a variable equal to the "index"
    var position = job[i]; // 1st loop is president, 2nd loop is vicePresident, and so on

    // We create a variable query target equal to the finest degree of granularity of the dataset
    // var queryTarget = votes[voter][position]

    // Conditional statement:
    // hasOwnProperty method determines wheater an object has a property with the specified name
    // If the object contains a property we are looking (queryTarget)
    if(voteCount[position].hasOwnProperty(votes[voter][position])){
      // Increment voteCount for this person by one
      voteCount[position][votes[voter][position]] += 1
    }
    // doesnt have the property
    else{
      voteCount[position][votes[voter][position]] = 1;
     }
 // console.log(voteCount)
  }
}
}

tallyVotes();

  // look at each [position] in the votecount object.
  // create var for scores equal to the amount of votes for this persion for one person
  // create var for winner equal to the highest scores value
  // iterate through names in scores and

function electionWinner(){
  // For each kind of office/position/job in voteCount variable
  for (var job in voteCount){
   //   number of votes one person received
  var scores = voteCount[job];
    // Is equal to the maximum value of votes for every job
    var highestValue = 0;
    //(name)
    var winner
    // Iterate through scores and for every name
      for (var name in scores){
      // If the score allocated to this name is > than the actual highestValue
      if(scores[name] > highestValue){
      // highestValue becomes this object (score[name])
      highestValue = scores[name];
      // Then, the winner is allocated the property (name) of this object
      winner = name;
      }
    }
    // We assign the winner name as a value of the property job for every property in the object officers.
    officers[job] = winner;
  }
};

electionWinner();

##########################################################################################################
REFACTORED
*/

// Tallyvotes
function tallyVotes(){
for (var voter in votes){
  for (var i=0; i < job.length; i++){
    var jobs = job[i];
    // We create set variable querytarget equal to the finest degree of granularity of the dataset
    var queryTarget = votes[voter][jobs]
    if(voteCount[jobs].hasOwnProperty(queryTarget)){
      voteCount[jobs][queryTarget] += 1
    }
    else{
      // The first time we encounter a person it counts as one vote (not zero)
      voteCount[jobs][queryTarget] = 1;
     }
  }
}
}
tallyVotes();

// electionWinner
function electionWinner(){
  for (var jobs in voteCount){
  var scores = voteCount[jobs];
    var highestValue = null;
    var winner = null;
      for (var name in scores){
      if(scores[name] > highestValue){
      highestValue = scores[name];
      winner = name;
      }
    }
    officers[jobs] = winner;
  }
};
electionWinner();

/*
##########################################################################################################
REFLECTION

1. What did you learn about iterating over nested objects in JavaScript?

    This reinforced that iterating over nested objects is a matter of knowing the object's structure and
    targeting each property and value with the appropriate notation. We used nested for..in loops to get
    down to the right level in both of the objects (votes and voteCount) that we were targeting.

2. Were you able to find useful methods to help you with this?

    The only new methods that we used for this challenge were the #hasOwnPropertyNames method that we used
    to initially identify the four jobs within the officer object, and the #hasOwnProperty method that we
    used to return a boolean which determined how each vote should be counted.

3. What concepts were solidified in the process of working through this challenge?

    This was a tricky challenge! The concept of using nested for..in loops along with variable counters
    for our tallys, and bracket notation for accessing properties/values were all solidified in this one.

##########################################################################################################
TEST CODE: DO NOT ALTER THE CODE BELOW THIS LINE

// Below you will find driver code. Run the code in this file either
// from the command line using Node.js or by pasting the code of this
// entire file into your browser console.  All tests will log true
// in the console when they pass--false, otherwise.
*/

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

// TEST1:
// if the voteCount encounters a president vote for bob in the vote object, it will create an object
// containing the name of the person (Bob) and add the value to his/her voteCount. In the case of test1,
// the property bob, contained in the object president, contained in the voteCount object, should be now
// pointing to the value 3.

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

// TEST2:
// if the voteCount encounters a vicePresident vote for bob in the vote object, it will create an object
// containing the name of the person (Bob) and add the value to his/her voteCount. In the case of test1,
// the property bob, contained in the object vicePresident, contained in the voteCount object, should be now
// pointing to the value 2.
assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

// TEST3:
// if the voteCount encounters a secretary vote for bob in the vote object, it will create an object
// containing the name of the person (Bob) and add the value to his/her voteCount. In the case of test1,
// the property bob, contained in the object secretary, contained in the voteCount object, should be now
// pointing to the value 3.
assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

// TEST4:
// if the voteCount encounters a treasurer vote for bob in the vote object, it will create an object
// containing the name of the person (Bob) and add the value to his/her voteCount. In the case of test1,
// the property bob, contained in the object treasurer, contained in the voteCount object, should be now
// pointing to the value 4.
assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

// TEST5:
// Function electionWinner should return Louise (name of the person with the highest amount of votes:5) for
// the role of president. In this case, the function electionWinner is querying the voteCount and returns the
// property in relation with the highest value for each office/job/position. Here, Louise should have the
// largest amount of votes and, hence, be elected as president.
assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

// TEST6:
// Here the function electionWinner should return the value of Hermann (name of the person with the highest
// amount of votes) for the role of vice president.
assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

// TEST7:
// Here the function electionWinner should return the value of Fred (name of the person with the highest amount
// of votes) for the role of vice Secretary.
assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

// TEST8:
// Here the function electionWinner should return the value of Ivy (name of the person with the highest amount
// of votes) for the role of treasurer.
assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)

<commit_msg>Update comments on Challenge 8.3<commit_after>/*
TALLY VOTES IN JAVASCRIPT PAIRING CHALLENGE
WE WORKED ON THIS CHALLENGE: Paul Gouron & Lars Johnson
THIS CHALLENGE TOOK US 3 HOURS

##########################################################################################################
THESE ARE THE VOTES CAST BY EACH STUDENT. DO NOT ALTER THESE OBJECTS
*/

var votes = {
  // Voter  - -  Index 1 --    Index 2 ---     Index 3 --               Index-4
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

// Once the votes have been tallied, assign each officer position the name of the
// student who received the most votes.

var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

var job = Object.getOwnPropertyNames(officers).sort();
// console.log(job)

/*
Set job equal to property names of the officers object: [president, vicePresident, secretary, treasurer]
We use sort to ensure the object's property names wiLl always appear in the same order (as in a loop)

##########################################################################################################
PSEUDOCODE

NOTES: This challenge is about iterating over an object (votes) ccontaining individual voters and their vote
       counts. We must iterate over the value of each property and populate the voteCount object accordingly

       The name of each student receiving a vote for an office should become a property of the respective
       office in voteCount. So for example, after Alex's votes have been tallied voteCount would be:

      var voteCount = {
        president: { Bob: 1 },
        vicePresident: { Devin: 1 },
        secretary: { Gail: 1 },
        treasurer: { Kerry: 1 } }

   INPUT: An object called votes with list of voters and each of their candidates for four different roles
          An object called voteCount with four empty properties (one for each of the four different roles)
          An object called officers with four undefined properties (one for each of the four different roles)

  OUTPUT: We must populate the voteCount object with the number of votes for each candidate in all four roles
          We must populate the officers object with the names of each winner in all four roles

ABOUT TALLYVOTES
  Create a function called tallyVotes to iterate through each voter in votes
    Each voter is voting for 4 people across 4 different jobs
    We created the variable (job) above in order to iterate through every property (job type)
  For each voter in votes...
    TallyVotes iterates through the 4 jobs and their values (candidates) to populate voteCount

ABOUT ELECTIONWINNER
  Create a function called electionWinner to iterate through each property of each the voteCount object
  In other words, iterate through each candidate and the number of votes they received
  Create a variable (record) and store the highest amount of votes for each job
  The winner for each job will be the person with the highest voteCount in that job category

##########################################################################################################
INITIAL SOLUTION

function tallyVotes(){

// Iterate through each voter
for (var voter in votes){

  // iterate through each vote object (with 4 properties - one for each job)
  for (var i=0; i < job.length; i++){

    // create a variable equal to the "index"
    var position = job[i]; // 1st loop is president, 2nd loop is vicePresident, and so on

    // We create a variable query target equal to the finest degree of granularity of the dataset
    // var queryTarget = votes[voter][position]

    // Conditional statement:
    // hasOwnProperty method determines wheater an object has a property with the specified name
    // If the object contains a property we are looking (queryTarget)
    if(voteCount[position].hasOwnProperty(votes[voter][position])){
      // Increment voteCount for this person by one
      voteCount[position][votes[voter][position]] += 1
    }
    // doesnt have the property
    else{
      voteCount[position][votes[voter][position]] = 1;
     }
 // console.log(voteCount)
  }
}
}

tallyVotes();

  // look at each [position] in the votecount object.
  // create var for scores equal to the amount of votes for this persion for one person
  // create var for winner equal to the highest scores value
  // iterate through names in scores and

function electionWinner(){
  // For each kind of office/position/job in voteCount variable
  for (var job in voteCount){
   //   number of votes one person received
  var scores = voteCount[job];
    // Is equal to the maximum value of votes for every job
    var highestValue = 0;
    //(name)
    var winner
    // Iterate through scores and for every name
      for (var name in scores){
      // If the score allocated to this name is > than the actual highestValue
      if(scores[name] > highestValue){
      // highestValue becomes this object (score[name])
      highestValue = scores[name];
      // Then, the winner is allocated the property (name) of this object
      winner = name;
      }
    }
    // We assign the winner name as a value of the property job for every property in the object officers.
    officers[job] = winner;
  }
};

electionWinner();

##########################################################################################################
REFACTORED
*/

// TallyVotes
function tallyVotes(){
for (var voter in votes){                 // iterate through each voter in votes object
  for (var i=0; i < job.length; i++){     // iterate through each job being voted for
    var jobs = job[i];                    // the var (job) cycles through president, vp, secretary, treasurer
    var queryTarget = votes[voter][jobs]  // the person being voted for a particular (job) in this iteration
    if(voteCount[jobs].hasOwnProperty(queryTarget)){   // if voteCount(job) already has that person listed
      voteCount[jobs][queryTarget] += 1                // increase the tally for that person in that (job)
    }
    else{
      voteCount[jobs][queryTarget] = 1;  // irst time we encounter a person it counts as one vote (not zero)
     }
  }
}
}
tallyVotes();

// electionWinner
function electionWinner(){
  for (var jobs in voteCount){           // for each (job) in voteCount
  var scores = voteCount[jobs];          // (scores) equals everyone who was voted for in that (job) with # of votes
    var highestValue = null;             // create empty highestValue and winner variables
    var winner = null;
      for (var name in scores){          // iterate over each name in (scores)
      if(scores[name] > highestValue){   // if value of that name is > highest value, set highestValue equal to name
      highestValue = scores[name];
      winner = name;                     // set winner equal to each (name) that achieves highestValue for each (job)
      }
    }
    officers[jobs] = winner;             // set officer[job] to each winner
  }
};
electionWinner();

/*
##########################################################################################################
REFLECTION

1. What did you learn about iterating over nested objects in JavaScript?

    This reinforced that iterating over nested objects is a matter of knowing the object's structure and
    targeting each property and value with the appropriate notation. We used nested for..in loops to get
    down to the right level in both of the objects (votes and voteCount) that we were targeting.

2. Were you able to find useful methods to help you with this?

    The only new methods that we used for this challenge were the #hasOwnPropertyNames method that we used
    to initially identify the four jobs within the officer object, and the #hasOwnProperty method that we
    used to return a boolean which determined how each vote should be counted.

3. What concepts were solidified in the process of working through this challenge?

    This was a tricky challenge! The concept of using nested for..in loops along with variable counters
    for our tallys, and bracket notation for accessing properties/values were all solidified in this one.

##########################################################################################################
TEST CODE: DO NOT ALTER THE CODE BELOW THIS LINE

// Below you will find driver code. Run the code in this file either
// from the command line using Node.js or by pasting the code of this
// entire file into your browser console.  All tests will log true
// in the console when they pass--false, otherwise.
*/

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

// TEST1:
// if the voteCount encounters a president vote for bob in the vote object, it will create an object
// containing the name of the person (Bob) and add the value to his/her voteCount. In the case of test1,
// the property bob, contained in the object president, contained in the voteCount object, should be now
// pointing to the value 3.

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

// TEST2:
// if the voteCount encounters a vicePresident vote for bob in the vote object, it will create an object
// containing the name of the person (Bob) and add the value to his/her voteCount. In the case of test1,
// the property bob, contained in the object vicePresident, contained in the voteCount object, should be now
// pointing to the value 2.
assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

// TEST3:
// if the voteCount encounters a secretary vote for bob in the vote object, it will create an object
// containing the name of the person (Bob) and add the value to his/her voteCount. In the case of test1,
// the property bob, contained in the object secretary, contained in the voteCount object, should be now
// pointing to the value 3.
assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

// TEST4:
// if the voteCount encounters a treasurer vote for bob in the vote object, it will create an object
// containing the name of the person (Bob) and add the value to his/her voteCount. In the case of test1,
// the property bob, contained in the object treasurer, contained in the voteCount object, should be now
// pointing to the value 4.
assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

// TEST5:
// Function electionWinner should return Louise (name of the person with the highest amount of votes:5) for
// the role of president. In this case, the function electionWinner is querying the voteCount and returns the
// property in relation with the highest value for each office/job/position. Here, Louise should have the
// largest amount of votes and, hence, be elected as president.
assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

// TEST6:
// Here the function electionWinner should return the value of Hermann (name of the person with the highest
// amount of votes) for the role of vice president.
assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

// TEST7:
// Here the function electionWinner should return the value of Fred (name of the person with the highest amount
// of votes) for the role of vice Secretary.
assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

// TEST8:
// Here the function electionWinner should return the value of Ivy (name of the person with the highest amount
// of votes) for the role of treasurer.
assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)

<|endoftext|>


<commit_before>var http = require('http'),
    fs = require('fs')
    mime = require('mime');

var server = http.createServer(function(req, res) {
  // send all urls to render index
  var path = 'index.html';

  // make exception for static assets
  if (req.url.match(/^\/media/)) {
    path = req.url;
  }

  var absPath = __dirname + '/' + path;
  var mimeType = mime.lookup(absPath);

  // load file
  fs.readFile(absPath, function(error, content) {
    if (error) {
      res.writeHead(500);
      res.end();
    } else {
      res.setHeader('Content-Type', mimeType);
      res.writeHead(200);
      res.end(content, 'utf-8');
    }
  });
});

server.listen(8000);
console.log('Listening on port: 8008');

<commit_msg>updated server port log<commit_after>var http = require('http'),
    fs = require('fs')
    mime = require('mime');

var server = http.createServer(function(req, res) {
  // send all urls to render index
  var path = 'index.html';

  // make exception for static assets
  if (req.url.match(/^\/media/)) {
    path = req.url;
  }

  var absPath = __dirname + '/' + path;
  var mimeType = mime.lookup(absPath);

  // load file
  fs.readFile(absPath, function(error, content) {
    if (error) {
      res.writeHead(500);
      res.end();
    } else {
      res.setHeader('Content-Type', mimeType);
      res.writeHead(200);
      res.end(content, 'utf-8');
    }
  });
});

server.listen(8000);
console.log('Listening on port: 8000');

<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = {};

        self.routes['/getMyList'] = function(req, res) {
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify({ name: 'getMyList' }, null, 3));
        }

        self.routes['/getTopSearches'] = function(req, res) {
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify({ name: 'getTopSearches' }, null, 3));
        }

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<commit_msg>added descriptions to routes in server.js<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = {};

        self.routes['/miika/getMyList'] = function(req, res) {
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify({
                name: 'getMyList',
                desc: 'Gets own list of movies and TV Shows by id/username'
            }, null, 3));
        };

        self.routes['/getTopSearches'] = function(req, res) {
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify({
                name: 'getTopSearches',
                desc: 'Gets top 10 searches currently'
            }, null, 3));
        };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<|endoftext|>


<commit_before>var express = require('express');
var app = express();

var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static('public'));

app.get('/canoa0', function(req, res){
  res.sendfile('river0.html');
});

app.get('/remo0', function(req, res){
  res.sendfile('remo0.html');
});

app.get('/remo1', function(req, res){
  res.sendfile('remo1.html');
});

io.on('connection', function(socket){
  socket.on('acc0', function(msg){
    io.emit('acc0', msg);
  });
    socket.on('acc1', function(msg){
    io.emit('acc1', msg);
  });
});

http.listen(process.env.PORT || 3000, function(){
  console.log(`Listening on ${ process.env.PORT }`);
});

<commit_msg>Server changed<commit_after>var express = require('express');
var app = express();

var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static('public'));

app.get('/', function(req, res){
  res.sendfile('river0.html');
});

app.get('/remo0', function(req, res){
  res.sendfile('remo0.html');
});

app.get('/remo1', function(req, res){
  res.sendfile('remo1.html');
});

io.on('connection', function(socket){
  socket.on('acc0', function(msg){
    io.emit('acc0', msg);
  });
    socket.on('acc1', function(msg){
    io.emit('acc1', msg);
  });
});

http.listen(process.env.PORT || 3000, function(){
  console.log(`Listening on ${ process.env.PORT }`);
});

<|endoftext|>


<commit_before>"use strict";

let express = require("express");
let app = express();
let config = require("./config");
let authentication = require("./lib/authentication");
let controller = require("./lib/controller");
let encoders = require("./lib/encoders");
let searcher = require("./lib/searcher");
let util = require("util");

let server = app.listen(config.server.port, config.server.address, function() {
  console.log(util.format("Listening at %s:%d", server.address().address, server.address().port));
});

if (config.api.require_authentication) {
  app.use("/v3", authentication.apikey);
}

app.use("/v3", function(req, res, next) {
  req.query.format = req.query.format || "json";
  res.set('Access-Control-Allow-Origin', '*');
  next();
});

app.use("/v3", function(req, res, next) {
  req.query.with = "with" in req.query ? req.query.with.split(",") : [];
  next();
});

app.use("/v3", function(req, res, next) {
  if (!("limit" in req.query)) {
    req.query.limit = config.api.results_per_page;
  }
  next();
});

app.get("/", function(req, res) {
  // Index, documentation
  res.send("API INDEX");
});

app.get("/v3/help", controller.helpIndex);
app.get("/v3/help/:type", controller.helpType);

app.get("/v3/:type", function(req, res, next) {
  let types = searcher.searcher.types;
  if (types.indexOf(req.params.type) >= 0) {
    controller.list.apply(controller, arguments);
  } else {
    next();
  }
});

app.get("/v3/:type/:id", function(req, res, next) {
  let types = searcher.searcher.types;
  if (types.indexOf(req.params.type) >= 0) {
    controller.fetch.apply(controller, arguments);
  } else {
    next();
  }
});

app.get("/v3/library", function(req, res, next) {
  req.params.type = "organisation";
  req.query.type = (req.query.type + "," || "") + "library";
  controller.list.apply(controller, arguments);
});

app.get("/v3/library/:id", function(req, res, next) {
  req.params.type = "organisation";
  controller.fetch.apply(controller, arguments);
});

// app.get("/v3/:type", controller.list);
// app.get("/v3/:type/:id", controller.fetch);

app.get("*", function(req, res, next) {
  if ("result" in res.locals) {
    return next();
  }
  res.status(404).send("404 Not Found");
});

app.use(encoders.selectEncoder);
app.use(encoders.encodeResponse);

/**
 * Final handler for successful requests. Will write the response to the client.
 * If no data is present, will pass to the next middleware which prints and error.
 */
app.use(function(req, res, next) {
  if ("data" in res.locals) {
    res.status(res.locals.status).send(res.locals.data);
  } else {
    next();
  }
});

process.on("uncaughtException", error => {
  console.error("process.exception:", error.stack);
});
<commit_msg>Catch error in handlers<commit_after>"use strict";

let express = require("express");
let app = express();
let config = require("./config");
let authentication = require("./lib/authentication");
let controller = require("./lib/controller");
let encoders = require("./lib/encoders");
let searcher = require("./lib/searcher");
let util = require("util");

let server = app.listen(config.server.port, config.server.address, function() {
  console.log(util.format("Listening at %s:%d", server.address().address, server.address().port));
});

if (config.api.require_authentication) {
  app.use("/v3", authentication.apikey);
}

app.use("/v3", function(req, res, next) {
  req.query.format = req.query.format || "json";
  res.set('Access-Control-Allow-Origin', '*');
  next();
});

app.use("/v3", function(req, res, next) {
  req.query.with = "with" in req.query ? req.query.with.split(",") : [];
  next();
});

app.use("/v3", function(req, res, next) {
  if (!("limit" in req.query)) {
    req.query.limit = config.api.results_per_page;
  }
  next();
});

app.get("/", function(req, res) {
  // Index, documentation
  res.send("API INDEX");
});

app.get("/v3/help", controller.helpIndex);
app.get("/v3/help/:type", controller.helpType);

app.get("/v3/:type", function(req, res, next) {
  try {
    let types = searcher.searcher.types;
    if (types.indexOf(req.params.type) >= 0) {
      controller.list.apply(controller, arguments);
    } else {
      next();
    }
  } catch (error) {
    res.status(500).send(error.toString());
    console.error(error.stack);
  }
});

app.get("/v3/:type/:id", function(req, res, next) {
  try {
    let types = searcher.searcher.types;
    if (types.indexOf(req.params.type) >= 0) {
      controller.fetch.apply(controller, arguments);
    } else {
      next();
    }
  } catch (error) {
    res.status(500).send(error.toString());
    console.error(error.stack);
  }
});

app.get("/v3/library", function(req, res, next) {
  req.params.type = "organisation";
  req.query.type = (req.query.type + "," || "") + "library";
  controller.list.apply(controller, arguments);
});

app.get("/v3/library/:id", function(req, res, next) {
  req.params.type = "organisation";
  controller.fetch.apply(controller, arguments);
});

// app.get("/v3/:type", controller.list);
// app.get("/v3/:type/:id", controller.fetch);

app.get("*", function(req, res, next) {
  if ("result" in res.locals) {
    return next();
  }
  res.status(404).send("404 Not Found");
});

app.use(encoders.selectEncoder);
app.use(encoders.encodeResponse);

/**
 * Final handler for successful requests. Will write the response to the client.
 * If no data is present, will pass to the next middleware which prints and error.
 */
app.use(function(req, res, next) {
  if ("data" in res.locals) {
    res.status(res.locals.status).send(res.locals.data);
  } else {
    next();
  }
});

process.on("uncaughtException", error => {
  console.error("process.exception:", error.stack);
});
<|endoftext|>


<commit_before>"use strict";
var stream      = require('stream');
var async       = require('async');
var util        = require('util');
var co          = require('co');
var _           = require('underscore');
var Q           = require('q');
var parsers     = require('./app/lib/streams/parsers/doc');
var constants   = require('./app/lib/constants');
var fileDAL     = require('./app/lib/dal/fileDAL');
var jsonpckg    = require('./package.json');
var router      = require('./app/lib/streams/router');
var base58      = require('./app/lib/base58');
var crypto      = require('./app/lib/crypto');
var signature   = require('./app/lib/signature');
var directory   = require('./app/lib/directory');
var dos2unix    = require('./app/lib/dos2unix');
var INNER_WRITE = true;

function Server (dbConf, overrideConf) {

  stream.Duplex.call(this, { objectMode: true });

  let home = directory.getHome(dbConf.name, dbConf.home);
  var logger = require('./app/lib/logger')('server');
  var that = this;
  var connectionPromise, servicesPromise;
  that.conf = null;
  that.dal = null;
  that.version = jsonpckg.version;

  var documentsMapping = {};

  // Unused, but made mandatory by Duplex interface
  this._read = () => null;

  this._write = function (obj, enc, writeDone, isInnerWrite) {
    that.submit(obj, isInnerWrite, function (err, res) {
      if (isInnerWrite) {
        writeDone(err, res);
      } else {
        writeDone();
      }
    });
  };

  this.connectDB = function (useDefaultConf) {
    // Connect only once
    return connectionPromise || (connectionPromise = that.connect(useDefaultConf));
  };

  this.initWithServices = function (done) {
    // Init services only once
    return servicesPromise || (servicesPromise = that.connectDB()
        .then(that.initServices)
        .then(function(err) {
          done && done(err);
          return that;
        })
        .catch(done));
  };

  this.submit = function (obj, isInnerWrite, done) {
    return co(function *() {
      if (!obj.documentType) {
        throw 'Document type not given';
      }
      try {
        let action = documentsMapping[obj.documentType];
        let res;
        if (typeof action == 'function') {
          // Handle the incoming object
          res = yield action(obj);
        } else {
          throw 'Unknown document type \'' + obj.documentType + '\'';
        }
        if (res) {
          // Only emit valid documents
          that.emit(obj.documentType, _.clone(res));
          that.push(_.clone(res));
        }
        if (done) {
          isInnerWrite ? done(null, res) : done();
        }
        return res;
      } catch (err) {
        logger.debug(err);
        if (done) {
          isInnerWrite ? done(err, null) : done();
        } else {
          throw err;
        }
      }
    });
  };

  this.submitP = (obj, isInnerWrite) => Q.nbind(this.submit, this)(obj, isInnerWrite);

  this.connect = function (useDefaultConf) {
    // Init connection
    if (that.dal) {
      return Q();
    }
    var dbType = dbConf && dbConf.memory ? fileDAL.memory : fileDAL.file;
    return dbType(home)
      .then(function(dal){
        that.dal = dal;
        return that.dal.init(overrideConf, useDefaultConf);
      })
      .then(function(conf){
        that.conf = conf;
        // Default values
        var defaultValues = {
          remoteipv6:         that.conf.ipv6,
          remoteport:         that.conf.port,
          cpu:                1,
          c:                  constants.CONTRACT.DEFAULT.C,
          dt:                 constants.CONTRACT.DEFAULT.DT,
          ud0:                constants.CONTRACT.DEFAULT.UD0,
          stepMax:            constants.CONTRACT.DEFAULT.STEPMAX,
          sigPeriod:          constants.CONTRACT.DEFAULT.SIGPERIOD,
          sigStock:           constants.CONTRACT.DEFAULT.SIGSTOCK,
          sigWindow:          constants.CONTRACT.DEFAULT.SIGWINDOW,
          sigValidity:        constants.CONTRACT.DEFAULT.SIGVALIDITY,
          msValidity:         constants.CONTRACT.DEFAULT.MSVALIDITY,
          sigQty:             constants.CONTRACT.DEFAULT.SIGQTY,
          xpercent:           constants.CONTRACT.DEFAULT.X_PERCENT,
          percentRot:         constants.CONTRACT.DEFAULT.PERCENTROT,
          blocksRot:          constants.CONTRACT.DEFAULT.BLOCKSROT,
          powDelay:           constants.CONTRACT.DEFAULT.POWDELAY,
          avgGenTime:         constants.CONTRACT.DEFAULT.AVGGENTIME,
          dtDiffEval:         constants.CONTRACT.DEFAULT.DTDIFFEVAL,
          medianTimeBlocks:   constants.CONTRACT.DEFAULT.MEDIANTIMEBLOCKS,
          rootoffset:         0,
          forksize:           constants.BRANCHES.DEFAULT_WINDOW_SIZE
        };
        _.keys(defaultValues).forEach(function(key){
          if (that.conf[key] == undefined) {
            that.conf[key] = defaultValues[key];
          }
        });
      });
  };

  this.start = function () {
    return that.checkConfig()
      .then(function (){
        // Add signing & public key functions to PeeringService
        logger.info('Node version: ' + that.version);
        logger.info('Node pubkey: ' + that.PeeringService.pubkey);
        return Q.nfcall(that.initPeer);
      });
  };

  this.recomputeSelfPeer = function() {
    return Q.nbind(that.PeeringService.generateSelfPeer, that.PeeringService)(that.conf, 0);
  };

  this.initPeer = function (done) {
    async.waterfall([
      function (next){
        that.checkConfig().then(next).catch(next);
      },
      function (next){
        that.PeeringService.regularCrawlPeers(next);
      },
      function (next){
        logger.info('Storing self peer...');
        that.PeeringService.regularPeerSignal(next);
      },
      function(next) {
        that.PeeringService.regularTestPeers(next);
      },
      function (next){
        that.PeeringService.regularSyncBlock(next);
      },
      function (next){
        that.BlockchainService.regularCleanMemory(next);
      }
    ], done);
  };

  let shouldContinue = true;

  this.stopBlockComputation = function() {
    shouldContinue = false;
  };

  this.startBlockComputation = function() {
    return co(function *() {
      while (shouldContinue) {
        try {
          let block = yield that.BlockchainService.startGeneration();
          if (block && shouldContinue) {
            try {
              let obj = parsers.parseBlock.syncWrite(dos2unix(block.getRawSigned()));
              yield that.singleWritePromise(obj);
            } catch (err) {
              logger.warn('Proof-of-work self-submission: %s', err.message || err);
            }
          }
        }
        catch (e) {
          logger.error(e);
          shouldContinue = true;
        }
      }
    });
  };

  this.checkConfig = function () {
    return that.checkPeeringConf(that.conf);
  };

  this.checkPeeringConf = function (conf) {
    return Q()
      .then(function(){
        if (!conf.pair && conf.passwd == null) {
          throw new Error('No key password was given.');
        }
        if (!conf.pair && conf.salt == null) {
          throw new Error('No key salt was given.');
        }
        if (!conf.currency) {
          throw new Error('No currency name was given.');
        }
        if(!conf.ipv4 && !conf.ipv6){
          throw new Error("No interface to listen to.");
        }
        if(!conf.remoteipv4 && !conf.remoteipv6 && !conf.remotehost){
          throw new Error('No interface for remote contact.');
        }
        if (!conf.remoteport) {
          throw new Error('No port for remote contact.');
        }
      });
  };

  this.createSignFunction = function (pair, done) {
    signature.async(pair, function (err, sigFunc) {
      that.sign = sigFunc;
      done(err);
    });
  };

  this.reset = function(done) {
    return that.dal.resetAll(done);
  };

  this.resetData = function(done) {
    return that.dal.resetData(done);
  };

  this.resetStats = function(done) {
    return that.dal.resetStats(done);
  };

  this.resetPeers = function(done) {
    return that.dal.resetPeers(done);
  };

  this.resetTxs = function(done) {
    that.dal.resetTransactions(done);
  };

  this.resetConf = function(done) {
    return that.dal.resetConf(done);
  };

  this.disconnect = function() {
    return that.dal && that.dal.close();
  };

  this.initServices = function() {
    return Q.Promise(function(resolve, reject){
      if (!that.servicesInited) {
        async.waterfall([
          function(next) {
            // Extract key pair
            if (that.conf.pair)
              next(null, {
                publicKey: base58.decode(that.conf.pair.pub),
                secretKey: base58.decode(that.conf.pair.sec)
              });
            else if (that.conf.passwd || that.conf.salt)
              crypto.getKeyPair(that.conf.passwd, that.conf.salt, next);
            else
              next(null, null);
          },
          function (pair, next){
            if (pair) {
              that.pair = pair;
              that.createSignFunction(pair, next);
            }
            else next('This node does not have a keypair. Use `ucoind wizard key` to fix this.');
          },
          function(next) {
            that.servicesInited = true;
            that.MerkleService       = require("./app/service/MerkleService");
            that.ParametersService   = require("./app/service/ParametersService")();
            that.IdentityService     = require('./app/service/IdentityService')(that.conf, that.dal);
            that.MembershipService   = require('./app/service/MembershipService')(that.conf, that.dal);
            that.PeeringService      = require('./app/service/PeeringService')(that, that.pair, that.dal);
            that.BlockchainService   = require('./app/service/BlockchainService')(that.conf, that.dal, that.pair);
            that.TransactionsService = require('./app/service/TransactionsService')(that.conf, that.dal);
            // Create document mapping
            documentsMapping = {
              'identity':    that.IdentityService.submitIdentity,
              'certification': that.IdentityService.submitCertification,
              'revocation':  that.IdentityService.submitRevocation,
              'membership':  that.MembershipService.submitMembership,
              'peer':        that.PeeringService.submitP,
              'transaction': that.TransactionsService.processTx,
              'block':       (obj) => {
                return co(function *() {
                  let block = yield that.BlockchainService.submitBlock(obj, true);
                  that.dal = that.BlockchainService.currentDal;
                  that.IdentityService.setDAL(that.dal);
                  that.MembershipService.setDAL(that.dal);
                  that.PeeringService.setDAL(that.dal);
                  that.TransactionsService.setDAL(that.dal);
                  (theRouter && theRouter.setDAL(that.dal));
                  return block;
                });
              }
            };
            that.BlockchainService.init(next);
          },
          function(next) {
            that.dal = that.BlockchainService.currentDal;
            that.IdentityService.setDAL(that.dal);
            that.MembershipService.setDAL(that.dal);
            that.PeeringService.setDAL(that.dal);
            that.TransactionsService.setDAL(that.dal);
            (theRouter && theRouter.setDAL(that.dal));
            next();
          }
        ], function(err) {
          err ? reject(err) : resolve();
        });
      } else {
        resolve();
      }
    });
  };

  this.makeNextBlock = function(manualValues) {
    return co(function *() {
      yield that.initWithServices();
      let proven = yield that.BlockchainService.makeNextBlock(null, null, null, manualValues);
      return proven;
    });
  };

  this.checkBlock = function(block) {
    return that.initWithServices()
      .then(function(){
        var parsed = parsers.parseBlock.syncWrite(block.getRawSigned());
        return that.BlockchainService.checkBlock(parsed, false);
      });
  };

  this.revert = () => this.BlockchainService.revertCurrentBlock();

  this.revertTo = (number) => co(function *() {
    let current = yield that.BlockchainService.current();
    for (let i = 0, count = current.number - number; i < count; i++) {
      yield that.BlockchainService.revertCurrentBlock();
    }
    if (current.number <= number) {
      logger.warn('Already reached');
    }
    that.BlockchainService.revertCurrentBlock();
  });

  this.singleWritePromise = (obj) => that.submit(obj);

  var theRouter;

  this.router = function() {
    if (!theRouter) {
      theRouter = router(that.PeeringService.pubkey, that.conf, that.dal);
    }
    return theRouter;
  };

}

util.inherits(Server, stream.Duplex);

module.exports = Server;
<commit_msg>Refactoring: _write() method of server can be lighter<commit_after>"use strict";
var stream      = require('stream');
var async       = require('async');
var util        = require('util');
var co          = require('co');
var _           = require('underscore');
var Q           = require('q');
var parsers     = require('./app/lib/streams/parsers/doc');
var constants   = require('./app/lib/constants');
var fileDAL     = require('./app/lib/dal/fileDAL');
var jsonpckg    = require('./package.json');
var router      = require('./app/lib/streams/router');
var base58      = require('./app/lib/base58');
var crypto      = require('./app/lib/crypto');
var signature   = require('./app/lib/signature');
var directory   = require('./app/lib/directory');
var dos2unix    = require('./app/lib/dos2unix');

function Server (dbConf, overrideConf) {

  stream.Duplex.call(this, { objectMode: true });

  let home = directory.getHome(dbConf.name, dbConf.home);
  var logger = require('./app/lib/logger')('server');
  var that = this;
  var connectionPromise, servicesPromise;
  that.conf = null;
  that.dal = null;
  that.version = jsonpckg.version;

  var documentsMapping = {};

  // Unused, but made mandatory by Duplex interface
  this._read = () => null;

  this._write = (obj, enc, writeDone) => that.submit(obj, false, () => writeDone);

  this.connectDB = function (useDefaultConf) {
    // Connect only once
    return connectionPromise || (connectionPromise = that.connect(useDefaultConf));
  };

  this.initWithServices = function (done) {
    // Init services only once
    return servicesPromise || (servicesPromise = that.connectDB()
        .then(that.initServices)
        .then(function(err) {
          done && done(err);
          return that;
        })
        .catch(done));
  };

  this.submit = function (obj, isInnerWrite, done) {
    return co(function *() {
      if (!obj.documentType) {
        throw 'Document type not given';
      }
      try {
        let action = documentsMapping[obj.documentType];
        let res;
        if (typeof action == 'function') {
          // Handle the incoming object
          res = yield action(obj);
        } else {
          throw 'Unknown document type \'' + obj.documentType + '\'';
        }
        if (res) {
          // Only emit valid documents
          that.emit(obj.documentType, _.clone(res));
          that.push(_.clone(res));
        }
        if (done) {
          isInnerWrite ? done(null, res) : done();
        }
        return res;
      } catch (err) {
        logger.debug(err);
        if (done) {
          isInnerWrite ? done(err, null) : done();
        } else {
          throw err;
        }
      }
    });
  };

  this.submitP = (obj, isInnerWrite) => Q.nbind(this.submit, this)(obj, isInnerWrite);

  this.connect = function (useDefaultConf) {
    // Init connection
    if (that.dal) {
      return Q();
    }
    var dbType = dbConf && dbConf.memory ? fileDAL.memory : fileDAL.file;
    return dbType(home)
      .then(function(dal){
        that.dal = dal;
        return that.dal.init(overrideConf, useDefaultConf);
      })
      .then(function(conf){
        that.conf = conf;
        // Default values
        var defaultValues = {
          remoteipv6:         that.conf.ipv6,
          remoteport:         that.conf.port,
          cpu:                1,
          c:                  constants.CONTRACT.DEFAULT.C,
          dt:                 constants.CONTRACT.DEFAULT.DT,
          ud0:                constants.CONTRACT.DEFAULT.UD0,
          stepMax:            constants.CONTRACT.DEFAULT.STEPMAX,
          sigPeriod:          constants.CONTRACT.DEFAULT.SIGPERIOD,
          sigStock:           constants.CONTRACT.DEFAULT.SIGSTOCK,
          sigWindow:          constants.CONTRACT.DEFAULT.SIGWINDOW,
          sigValidity:        constants.CONTRACT.DEFAULT.SIGVALIDITY,
          msValidity:         constants.CONTRACT.DEFAULT.MSVALIDITY,
          sigQty:             constants.CONTRACT.DEFAULT.SIGQTY,
          xpercent:           constants.CONTRACT.DEFAULT.X_PERCENT,
          percentRot:         constants.CONTRACT.DEFAULT.PERCENTROT,
          blocksRot:          constants.CONTRACT.DEFAULT.BLOCKSROT,
          powDelay:           constants.CONTRACT.DEFAULT.POWDELAY,
          avgGenTime:         constants.CONTRACT.DEFAULT.AVGGENTIME,
          dtDiffEval:         constants.CONTRACT.DEFAULT.DTDIFFEVAL,
          medianTimeBlocks:   constants.CONTRACT.DEFAULT.MEDIANTIMEBLOCKS,
          rootoffset:         0,
          forksize:           constants.BRANCHES.DEFAULT_WINDOW_SIZE
        };
        _.keys(defaultValues).forEach(function(key){
          if (that.conf[key] == undefined) {
            that.conf[key] = defaultValues[key];
          }
        });
      });
  };

  this.start = function () {
    return that.checkConfig()
      .then(function (){
        // Add signing & public key functions to PeeringService
        logger.info('Node version: ' + that.version);
        logger.info('Node pubkey: ' + that.PeeringService.pubkey);
        return Q.nfcall(that.initPeer);
      });
  };

  this.recomputeSelfPeer = function() {
    return Q.nbind(that.PeeringService.generateSelfPeer, that.PeeringService)(that.conf, 0);
  };

  this.initPeer = function (done) {
    async.waterfall([
      function (next){
        that.checkConfig().then(next).catch(next);
      },
      function (next){
        that.PeeringService.regularCrawlPeers(next);
      },
      function (next){
        logger.info('Storing self peer...');
        that.PeeringService.regularPeerSignal(next);
      },
      function(next) {
        that.PeeringService.regularTestPeers(next);
      },
      function (next){
        that.PeeringService.regularSyncBlock(next);
      },
      function (next){
        that.BlockchainService.regularCleanMemory(next);
      }
    ], done);
  };

  let shouldContinue = true;

  this.stopBlockComputation = function() {
    shouldContinue = false;
  };

  this.startBlockComputation = function() {
    return co(function *() {
      while (shouldContinue) {
        try {
          let block = yield that.BlockchainService.startGeneration();
          if (block && shouldContinue) {
            try {
              let obj = parsers.parseBlock.syncWrite(dos2unix(block.getRawSigned()));
              yield that.singleWritePromise(obj);
            } catch (err) {
              logger.warn('Proof-of-work self-submission: %s', err.message || err);
            }
          }
        }
        catch (e) {
          logger.error(e);
          shouldContinue = true;
        }
      }
    });
  };

  this.checkConfig = function () {
    return that.checkPeeringConf(that.conf);
  };

  this.checkPeeringConf = function (conf) {
    return Q()
      .then(function(){
        if (!conf.pair && conf.passwd == null) {
          throw new Error('No key password was given.');
        }
        if (!conf.pair && conf.salt == null) {
          throw new Error('No key salt was given.');
        }
        if (!conf.currency) {
          throw new Error('No currency name was given.');
        }
        if(!conf.ipv4 && !conf.ipv6){
          throw new Error("No interface to listen to.");
        }
        if(!conf.remoteipv4 && !conf.remoteipv6 && !conf.remotehost){
          throw new Error('No interface for remote contact.');
        }
        if (!conf.remoteport) {
          throw new Error('No port for remote contact.');
        }
      });
  };

  this.createSignFunction = function (pair, done) {
    signature.async(pair, function (err, sigFunc) {
      that.sign = sigFunc;
      done(err);
    });
  };

  this.reset = function(done) {
    return that.dal.resetAll(done);
  };

  this.resetData = function(done) {
    return that.dal.resetData(done);
  };

  this.resetStats = function(done) {
    return that.dal.resetStats(done);
  };

  this.resetPeers = function(done) {
    return that.dal.resetPeers(done);
  };

  this.resetTxs = function(done) {
    that.dal.resetTransactions(done);
  };

  this.resetConf = function(done) {
    return that.dal.resetConf(done);
  };

  this.disconnect = function() {
    return that.dal && that.dal.close();
  };

  this.initServices = function() {
    return Q.Promise(function(resolve, reject){
      if (!that.servicesInited) {
        async.waterfall([
          function(next) {
            // Extract key pair
            if (that.conf.pair)
              next(null, {
                publicKey: base58.decode(that.conf.pair.pub),
                secretKey: base58.decode(that.conf.pair.sec)
              });
            else if (that.conf.passwd || that.conf.salt)
              crypto.getKeyPair(that.conf.passwd, that.conf.salt, next);
            else
              next(null, null);
          },
          function (pair, next){
            if (pair) {
              that.pair = pair;
              that.createSignFunction(pair, next);
            }
            else next('This node does not have a keypair. Use `ucoind wizard key` to fix this.');
          },
          function(next) {
            that.servicesInited = true;
            that.MerkleService       = require("./app/service/MerkleService");
            that.ParametersService   = require("./app/service/ParametersService")();
            that.IdentityService     = require('./app/service/IdentityService')(that.conf, that.dal);
            that.MembershipService   = require('./app/service/MembershipService')(that.conf, that.dal);
            that.PeeringService      = require('./app/service/PeeringService')(that, that.pair, that.dal);
            that.BlockchainService   = require('./app/service/BlockchainService')(that.conf, that.dal, that.pair);
            that.TransactionsService = require('./app/service/TransactionsService')(that.conf, that.dal);
            // Create document mapping
            documentsMapping = {
              'identity':    that.IdentityService.submitIdentity,
              'certification': that.IdentityService.submitCertification,
              'revocation':  that.IdentityService.submitRevocation,
              'membership':  that.MembershipService.submitMembership,
              'peer':        that.PeeringService.submitP,
              'transaction': that.TransactionsService.processTx,
              'block':       (obj) => {
                return co(function *() {
                  let block = yield that.BlockchainService.submitBlock(obj, true);
                  that.dal = that.BlockchainService.currentDal;
                  that.IdentityService.setDAL(that.dal);
                  that.MembershipService.setDAL(that.dal);
                  that.PeeringService.setDAL(that.dal);
                  that.TransactionsService.setDAL(that.dal);
                  (theRouter && theRouter.setDAL(that.dal));
                  return block;
                });
              }
            };
            that.BlockchainService.init(next);
          },
          function(next) {
            that.dal = that.BlockchainService.currentDal;
            that.IdentityService.setDAL(that.dal);
            that.MembershipService.setDAL(that.dal);
            that.PeeringService.setDAL(that.dal);
            that.TransactionsService.setDAL(that.dal);
            (theRouter && theRouter.setDAL(that.dal));
            next();
          }
        ], function(err) {
          err ? reject(err) : resolve();
        });
      } else {
        resolve();
      }
    });
  };

  this.makeNextBlock = function(manualValues) {
    return co(function *() {
      yield that.initWithServices();
      let proven = yield that.BlockchainService.makeNextBlock(null, null, null, manualValues);
      return proven;
    });
  };

  this.checkBlock = function(block) {
    return that.initWithServices()
      .then(function(){
        var parsed = parsers.parseBlock.syncWrite(block.getRawSigned());
        return that.BlockchainService.checkBlock(parsed, false);
      });
  };

  this.revert = () => this.BlockchainService.revertCurrentBlock();

  this.revertTo = (number) => co(function *() {
    let current = yield that.BlockchainService.current();
    for (let i = 0, count = current.number - number; i < count; i++) {
      yield that.BlockchainService.revertCurrentBlock();
    }
    if (current.number <= number) {
      logger.warn('Already reached');
    }
    that.BlockchainService.revertCurrentBlock();
  });

  this.singleWritePromise = (obj) => that.submit(obj);

  var theRouter;

  this.router = function() {
    if (!theRouter) {
      theRouter = router(that.PeeringService.pubkey, that.conf, that.dal);
    }
    return theRouter;
  };

}

util.inherits(Server, stream.Duplex);

module.exports = Server;
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var stack = require('poe-ui-kit');
var envs = require('envs');
var fs = require('fs');
var read = fs.readFileSync;
var exists = fs.existsSync;
var oauth = require('./server/oauth');

/**
 * Forwarding headers
 */

var headers = {
  port: 'x-orig-port',
  proto: 'x-orig-proto',
  path: 'x-orig-path',
  host: 'x-orig-host'
};

/**
 * Create a poe-ui app
 */

exports = module.exports = function(routesPath, opts) {
  if (!routesPath || typeof routesPath !== 'string') throw new Error('Missing routes path parameter');
  opts = opts || {};

  var app = stack(opts);

  oauth.attach(app, opts.auth);

  // remove the middleware we don't need
  app.remove('methodOverride');
  app.remove('json');
  app.remove('urlencoded');

  var routes = loadRoutes(routesPath);

  mountRoutes(app, routes);

  // setup loaders
  app.builder.module.loaders.push(
    {test: /\.(js)$/, exclude: /node_modules/, loader: 'esnext-loader'},
    {test: /\.(js)$/, include: /node_modules\/[^\/]+\/blocks/, loader: 'esnext-loader'}
  );
  app.builder.resolve.extensions.push('.jade');
  app.builder.addLoader('jade', (process.env.NODE_ENV === 'development' ? 'react-component-loader!' : '') + 'esnext-loader!onus-loader!ast2template-loader!jade2ast-loader');

  app.builder.addLoader(/\.(ess\?(dynamic|raw))$/, 'ess-loader!esnext-loader!ast2template?pass-through=1!ess2ast-loader');
  app.builder.addStyle(/\.(ess)$/, 'css-loader!autoprefixer-loader!ess-loader!esnext-loader!ast2template?pass-through=1!ess2ast-loader');

  app.builder.addLoader('yml', 'json-loader!yaml-loader');

  // files
  app.builder.addLoader('png', 'file-loader');
  app.builder.addLoader('jpg', 'file-loader');
  app.builder.addLoader('gif', 'file-loader');
  app.builder.addLoader('svg', 'file-loader');

  var rootFile = app.builder.sourcedir + '/root.js';
  app.builder.ast2template = {
    root: exists(rootFile) ? rootFile : null
  };

  return app;
};

/**
 * Expose the middleware
 */

exports.middleware = stack.middleware;

function loadRoutes(routesPath) {
  // var routes = read(routesPath, 'utf8');
  // TODO
}

function mountRoutes(app, routes, restricted) {
  var re = /^\/(build).*/;
  app.useAfter('router', function indexPage(req, res, next) {
    if (re.test(req.url)) return next();
    res.render('index.jade');
  });
}
<commit_msg>add dev /api proxy<commit_after>/**
 * Module dependencies
 */

var stack = require('poe-ui-kit');
var envs = require('envs');
var fs = require('fs');
var read = fs.readFileSync;
var exists = fs.existsSync;
var oauth = require('./server/oauth');
var proxy = require('simple-http-proxy');

var NODE_ENV = envs('NODE_ENV', 'production');

/**
 * Forwarding headers
 */

var headers = {
  port: 'x-orig-port',
  proto: 'x-orig-proto',
  path: 'x-orig-path',
  host: 'x-orig-host'
};

/**
 * Create a poe-ui app
 */

exports = module.exports = function(routesPath, opts) {
  if (!routesPath || typeof routesPath !== 'string') throw new Error('Missing routes path parameter');
  opts = opts || {};

  var app = stack(opts);

  if (NODE_ENV === 'development') mountDevProxy(app, envs('API_URL'));

  oauth.attach(app, opts.auth);

  // remove the middleware we don't need
  app.remove('methodOverride');
  app.remove('json');
  app.remove('urlencoded');

  var routes = loadRoutes(routesPath);

  mountRoutes(app, routes);

  // setup loaders
  app.builder.module.loaders.push(
    {test: /\.(js)$/, exclude: /node_modules/, loader: 'esnext-loader'},
    {test: /\.(js)$/, include: /node_modules\/[^\/]+\/blocks/, loader: 'esnext-loader'}
  );
  app.builder.resolve.extensions.push('.jade');
  app.builder.addLoader('jade', (process.env.NODE_ENV === 'development' ? 'react-component-loader!' : '') + 'esnext-loader!onus-loader!ast2template-loader!jade2ast-loader');

  app.builder.addLoader(/\.(ess\?(dynamic|raw))$/, 'ess-loader!esnext-loader!ast2template?pass-through=1!ess2ast-loader');
  app.builder.addStyle(/\.(ess)$/, 'css-loader!autoprefixer-loader!ess-loader!esnext-loader!ast2template?pass-through=1!ess2ast-loader');

  app.builder.addLoader('yml', 'json-loader!yaml-loader');

  // files
  app.builder.addLoader('png', 'file-loader');
  app.builder.addLoader('jpg', 'file-loader');
  app.builder.addLoader('gif', 'file-loader');
  app.builder.addLoader('svg', 'file-loader');

  var rootFile = app.builder.sourcedir + '/root.js';
  app.builder.ast2template = {
    root: exists(rootFile) ? rootFile : null
  };

  return app;
};

/**
 * Expose the middleware
 */

exports.middleware = stack.middleware;

function loadRoutes(routesPath) {
  // var routes = read(routesPath, 'utf8');
  // TODO
}

function mountRoutes(app, routes, restricted) {
  var re = /^\/(build).*/;
  app.useAfter('router', function indexPage(req, res, next) {
    if (re.test(req.url)) return next();
    res.render('index.jade');
  });
}

function mountDevProxy(app, API_URL) {
  if (!API_URL) return;

  app.useAfter('cookieParser', '/api', 'api-proxy', proxy(API_URL.replace(/^ws/, 'http'), {xforward: headers, onrequest: function(opts, req) {
    delete opts.headers['if-none-match'];
    delete opts.headers.connection;
    if (!opts.headers.authorization && req.cookies && req.cookies._access_token) opts.headers.authorization = 'Bearer ' + req.cookies._access_token;
  }}));
}<|endoftext|>


<commit_before><commit_msg>Minimum server<commit_after>import http from 'http';
import colors from 'colors';

let app = http.createServer(function (req, res) {});

app.listen(3000, () => {
  console.log('Server running at localhost:3000/'.underline);
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var port = process.env.PORT;
var favicon = require('serve-favicon');
app.use(express.static('public'));

app.use(favicon(__dirname + '/public/img/favicon.ico'));
//app.listen(port);
app.listen(3000, function(){
  console.log('Listening on port 3000..');
});
<commit_msg>modified port to fix the heroku errors<commit_after>var express = require('express');
var app = express();
var favicon = require('serve-favicon');
app.use(express.static('public'));

app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.listen(process.env.PORT || 3000, function () {
  console.log("Listening on port 3000...");
});
<|endoftext|>