<commit_before>'use strict'
var fs = require('fs');
var _  = require('lodash');

//bullPen format is =[{c1},{c2},{c3}]
var numberOfRounds = null;

// var demographicInformation = [144,306,551,642,198];
var demographicInformation = [5,5,5,5,5];
var demographicInformationLength = 5;
var jiujitsuBelts = ['black','brown','purple','blue','white'];

var bullPen             = [];
var bullPenLength       = null;
var theCompetitionMats  = [];
var aboutToCompeteArray = [];
var aboutToCompeteArrayLength = null;
var winnersBracket      = [];
var losersBracket       = [];
var nSquared            = null;
var finishedCompeting   = [];
var firstCompetitorsProbabilityOfVictory  = 0;
var secondCompetitorsProbabilityOfVictory = 0;

var firstCompetitor       = null;
var firstCompetitorLosses = 0;
var firstCompetitorName   = null;
var firstCompetitorRating = null;
var firstCompetitorRecord = null;
var firstCompetitorWins   = 0;
var firstCompetitorBelt   = null;
var firstCompetitorBeltRank = null;

var secondCompetitor       = null;
var secondCompetitorName   = null;
var secondCompetitorWins   = 0;
var secondCompetitorLosses = 0;
var secondCompetitorRating = null;
var secondCompetitorRecord = null;
var secondCompetitorBelt   = null;
var secondCompetitorBeltRank = null;

var ifFirstCompetitorWins   = null;
var ifFirstCompetitorLoses  = null;
var ifSecondCompetitorWins  = null;
var ifSecondCompetitorLoses = null;

/**
 * @name - bullPenGenerator
 * @description - outputs bullPen populated with integer^2 number of competitors
 * @example - bullPen = [{c1},{c2},{c3},...,{c(integer^2)}]
 *            bullPen.length = integer^2
 * @param - integer
 **/

var bullPenGenerator = function(demographicInformation) {
  let counter = 1;
  var competitorAssemblerAndBullPenPopulator = function(demographicInformation){
    //go across each item in demographicInformation array
    for ( let j = 0; j < demographicInformation.length; j++ ) {
      //for as many as are in each of demographicInformation's elements
      for ( let i = 1; i <= demographicInformation[j]; i++ ) {
        let competitorNameBlueprint = counter.toString();
        let competitorBlueprint = '{"c' + competitorNameBlueprint
              + '":{"rating":1600,"wins":0,"losses":0,"record":"","beltRank":'
              + j  + ',"belt":"' + jiujitsuBelts[j] + '","matches":""}}';
        counter++;

        bullPen.push(JSON.parse(competitorBlueprint));
      }
    }
  };
  competitorAssemblerAndBullPenPopulator(demographicInformation);
};

var separateBelts = function(demographicInformation,bullPen){

  console.log("separateBelts invoked!");
  console.log("demographicInformation",demographicInformation);
  console.log("bullPen:",bullPen);

  // let leadingBelt      = Object.keys(bullPen[0]);
  // let leadingBeltColor = bullPen[0][leadingBelt]['belt']
  // let numberOfBelts = demographicInformation.shift();

  // for ( let i = 0; i < numberOfBelts; i++ ) {
  //   aboutToCompeteArray.push(bullPen.shift());
  // }

  // bullPenLength = bullPen.length;
  // aboutToCompeteArrayLength = aboutToCompeteArray.length;
  // console.log("inside separateBelts --> bullPen.length:",bullPen.length);
  // console.log("separateBelts invoked!");
  // console.log("leadingBelt:",leadingBelt);
  // console.log("leadingBeltColor:",leadingBeltColor);
}

/**
 * @name - competitionMatPopulator
 * @description - Takes as input bullPen array
 *                Removes first and second competitors from bullPen
 *                And places them inside theCompetitionMats
 * @param - bullPen
 *
 **/
var competitionMatPopulator = function(aboutToCompeteArray, bullPen){
  theCompetitionMats.push(aboutToCompeteArray.shift())
  theCompetitionMats.push(bullPen.pop())
};

/**
 * @name - variableAssigner
 * @description - Assigns to variables all statistics relevant to calculations for
 *                the two competitors on theCompetitionMats.
 * @param - theCompetitionMats
 **/
var scribe = function(theCompetitionMats){
  firstCompetitor       = theCompetitionMats[0];
  firstCompetitorName   = Object.keys(firstCompetitor)[0];
  firstCompetitorRating = firstCompetitor[firstCompetitorName]['rating'];
  firstCompetitorWins   = firstCompetitor[firstCompetitorName]['wins'];
  firstCompetitorLosses = firstCompetitor[firstCompetitorName]['losses'];
  firstCompetitorRecord = firstCompetitor[firstCompetitorName]['record'];
  firstCompetitorBelt   = firstCompetitor[firstCompetitorName]['belt'];
  firstCompetitorBeltRank = firstCompetitor[firstCompetitorName]['beltRank'];

  secondCompetitor       = theCompetitionMats[1];
  secondCompetitorName   = Object.keys(secondCompetitor)[0];
  secondCompetitorRating = secondCompetitor[secondCompetitorName]['rating'];
  secondCompetitorWins   = secondCompetitor[secondCompetitorName]['wins'];
  secondCompetitorLosses = secondCompetitor[secondCompetitorName]['losses'];
  secondCompetitorRecord = secondCompetitor[secondCompetitorName]['record'];
  secondCompetitorBelt   = secondCompetitor[secondCompetitorName]['belt'];
  secondCompetitorBeltRank = secondCompetitor[secondCompetitorName]['beltRank'];

  //important to save this step for last
  //otherwise secondCompetitorsRating may not be defined
  //at assignment-time for firstCompetitorsProbabilityOfVictory
  firstCompetitorsProbabilityOfVictory  = 1 / (1 + Math.pow(10, ((secondCompetitorRating - firstCompetitorRating) / 400)));
  secondCompetitorsProbabilityOfVictory = 1 / (1 + Math.pow(10, ((firstCompetitorRating - secondCompetitorRating) / 400)));
};

//should compare against numerical representation of belt
var referee = function(firstCompetitorBeltRank,secondCompetitorBeltRank){
  matchRecorder();

  if ( firstCompetitorBeltRank < secondCompetitorBeltRank ) {
    firstCompetitor[firstCompetitorName]['wins']++;
    firstCompetitor[firstCompetitorName]['record'] = firstCompetitorRecord + "w";

    secondCompetitor[secondCompetitorName]['losses']++;
    secondCompetitor[secondCompetitorName]['record'] = secondCompetitorRecord + "l";
  } else {
    firstCompetitor[firstCompetitorName]['losses']++;
    firstCompetitor[firstCompetitorName]['record'] = firstCompetitorRecord + "l";

    secondCompetitor[secondCompetitorName]['wins']++;
    secondCompetitor[secondCompetitorName]['record'] = secondCompetitorRecord + "w";
  }
};

/**
 * @name - ratingsAdjuster
 * @description - Determines the result of firstCompetitor's match
 *                ** ratingsAtStakeCalculator(k) -- calculates the ratings at stake for each player
 *                                                  depending on whether they win or lose
 *                Adds additional ratings points to winner
 *                Subtracts rating points from loser
 * @param - theCompetitionMats
 * @param - k-factor
 **/
var ratingsAdjuster = function(theCompetitionMats,k) {
  let firstCompetitorLastMatchResult = theCompetitionMats[0][firstCompetitorName]['record'].slice(theCompetitionMats[0][firstCompetitorName]['record'].length-1);
  ratingsAtStakeCalculator(k);

  if ( firstCompetitorLastMatchResult === 'w' ) {
    firstCompetitor[firstCompetitorName]['rating']   = Math.round(firstCompetitorRating + ifFirstCompetitorWins);
    secondCompetitor[secondCompetitorName]['rating'] = Math.round(secondCompetitorRating + ifSecondCompetitorLoses);
  } else {
    firstCompetitor[firstCompetitorName]['rating']   = Math.round(firstCompetitorRating + ifFirstCompetitorLoses);
    secondCompetitor[secondCompetitorName]['rating'] = Math.round(secondCompetitorRating + ifSecondCompetitorWins);
  }
  firstCompetitorRecord  = firstCompetitor[firstCompetitorName]['record'];
  secondCompetitorRecord = secondCompetitor[secondCompetitorName]['record'];
};

/**
 * @name - ratingsAtStakeCalculator
 * @description - Calculates how much each competitorObject in theCompetitionMats
 *                stands to win or lose based on the result of the match.
 * @param - k-factor
 **/
var ratingsAtStakeCalculator = function(k){
  ifFirstCompetitorWins   = k*(1-firstCompetitorsProbabilityOfVictory);
  ifFirstCompetitorLoses  = k*(-firstCompetitorsProbabilityOfVictory);
  ifSecondCompetitorWins  = k*(1-secondCompetitorsProbabilityOfVictory);
  ifSecondCompetitorLoses = k*(-secondCompetitorsProbabilityOfVictory);
};

/**
 * @name - matchRecorder
 * @description - To 'matches' key in competitorObject, assigns value -->
 *                stringified record of match just finished in theCompetitionMats.
 *                Each match is delimited by '***'
 * @example - 'matches': {'1600-c733-1600***1588-c503-1613'}
 *             where at time of match: '1600' is competitorObject's rating
 *                                     'c733' is competitorObject's opponent
 *                                     '1600' is competitorObject's opponent's rating
 *             '***' delimiter
 *             Second match:           '1588' is competitorObject's rating
 *                                     'c503' is competitorObject's opponent
 *                                     '1613' is competitorObject's opponent's rating
 * @param - none
 **/

//should record belt of opponent too
//should also record the match number in the field
//would help keep everything in place
var matchRecorder = function(){
  firstCompetitor[firstCompetitorName]['matches'] = firstCompetitor[firstCompetitorName]['matches']
                                                  + firstCompetitorRating.toString()
                                                  + "-" + secondCompetitorName
                                                  + "-" + secondCompetitorRating.toString() + "***";

  secondCompetitor[secondCompetitorName]['matches'] = secondCompetitor[secondCompetitorName]['matches']
                                                    + secondCompetitorRating.toString()
                                                    + "-" + firstCompetitorName
                                                    + "-" + firstCompetitorRating.toString() + "***";
};

// var callNextCompetitor = function(bullPen){
//   theCompetitionMats.push(bullPen.pop());
// }

// var fightAllOtherBelts = function(theCompetitionMats,bullPen,k){
//   for ( let i = 0; i < bullPen.length/144; i++ ) {
//     // scribe(theCompetitionMats);
//     // referee(firstCompetitorBeltRank,secondCompetitorBeltRank);
//     // ratingsAdjuster(theCompetitionMats,k)
//     // competitionMatDepopulator(firstCompetitorRecord,theCompetitionMats);
//     theCompetitionMats.push(bullPen.pop())
//   }
// }

/**
 * @name - competitionMatDepopulator
 * @description - Checks last entry of firstCompetitorRecord
 *                Then places winner of match into innersBracket
 *                And loser of match into losersBracket
 * @param - firstCompetitorRecord
 * @param - theCompetitionMats
 **/
var competitionMatDepopulator = function(firstCompetitorRecord,theCompetitionMats){
  if ( firstCompetitorRecord.charAt(firstCompetitorRecord.length-1) === 'w' ) {
    losersBracket.push(theCompetitionMats.pop());
  }
};

/**
 * @name - mundialTournament
 * @description - Makes all competitorObjects in bullPen compete once
 *                **bullPenGenerator -- builds competitors; populates bullPen
 *                **roundsCalculator -- calculates the number of rounds 1st and 2nd will fight!
 *                Invokes runAllMatchesForOneRound() for numberOfRounds
 * @param - integer
 * @param - k-factor
 **/
var mundialTournament = function(demographicInformation,k){
  bullPenGenerator(demographicInformation);
  separateBelts(demographicInformation,bullPen);
  // console.log("BEFORE ASSIGNMENT --> bullPen had",bullPen.length,"number of competitors!");
  // console.log("demographicInformation.length:",demographicInformation.length);

  // for ( let i = 0; i < demographicInformation.length; i++ ) {
  //   separateBelts(demographicInformation,bullPen);
  //   for ( let i = 0; i < aboutToCompeteArrayLength; i++ ) {
  //     theCompetitionMats.push(aboutToCompeteArray.shift());
  //     theCompetitionMats.push(bullPen.pop());
  //     for ( let i = 0; i < bullPenLength; i++ ) {
  //       scribe(theCompetitionMats);
  //       referee(firstCompetitorBeltRank,secondCompetitorBeltRank);
  //       ratingsAdjuster(theCompetitionMats,k)
  //       competitionMatDepopulator(firstCompetitorRecord,theCompetitionMats);
  //       if ( bullPen.length !== 0 ) {
  //         theCompetitionMats.push(bullPen.pop())
  //       }
  //     }
  //     bullPen = losersBracket;
  //     losersBracket = [];
  //     finishedCompeting.push(theCompetitionMats.pop());
  //   }
  // }

  console.log("aboutToCompeteArray:",aboutToCompeteArray);
  console.log("bullPen:",bullPen);
  console.log("theCompetitionMats:",theCompetitionMats);
  console.log("theCompetitionMats.length:",theCompetitionMats.length);
  console.log("bullPen had",bullPen.length,"number of competitors!");
  console.log("finishedCompeting:",finishedCompeting);
  // console.log("losersBracket:",losersBracket);
  // console.log("TOURNAMENT'S WINNER!",bullPen[0]);

  // console.log("winnersBracket.length:",winnersBracket.length);
  // console.log("losersBracket.length:",losersBracket.length);
};

// Will generate competitors equal to sum of demographicInformation which will
// Compete each belt vs each other belt
// Until a winner is declared.
// k is the maximal number of points a player can win/lose in a given match
mundialTournament(demographicInformation,25);<commit_msg>Second trial still not working<commit_after>'use strict'
var fs = require('fs');
var _  = require('lodash');

//bullPen format is =[{c1},{c2},{c3}]
var numberOfRounds = null;

// var demographicInformation = [144,306,551,642,198];
var demographicInformation = [2,2,2,2,2];
var demographicInformationLength = demographicInformation.length;
var jiujitsuBelts = ['black','brown','purple','blue','white'];

var bullPen             = [];
var bullPenLength       = null;
var theCompetitionMats  = [];
var aboutToCompeteArray = [];
var aboutToCompeteArrayLength = null;
var winnersBracket      = [];
var losersBracket       = [];
var nSquared            = null;
var finishedCompeting   = [];
var firstCompetitorsProbabilityOfVictory  = 0;
var secondCompetitorsProbabilityOfVictory = 0;

var firstCompetitor       = null;
var firstCompetitorLosses = 0;
var firstCompetitorName   = null;
var firstCompetitorRating = null;
var firstCompetitorRecord = null;
var firstCompetitorWins   = 0;
var firstCompetitorBelt   = null;
var firstCompetitorBeltRank = null;

var secondCompetitor       = null;
var secondCompetitorName   = null;
var secondCompetitorWins   = 0;
var secondCompetitorLosses = 0;
var secondCompetitorRating = null;
var secondCompetitorRecord = null;
var secondCompetitorBelt   = null;
var secondCompetitorBeltRank = null;

var ifFirstCompetitorWins   = null;
var ifFirstCompetitorLoses  = null;
var ifSecondCompetitorWins  = null;
var ifSecondCompetitorLoses = null;

/**
 * @name - bullPenGenerator
 * @description - outputs bullPen populated with integer^2 number of competitors
 * @example - bullPen = [{c1},{c2},{c3},...,{c(integer^2)}]
 *            bullPen.length = integer^2
 * @param - integer
 **/

var bullPenGenerator = function(demographicInformation) {
  let counter = 1;
  var competitorAssemblerAndBullPenPopulator = function(demographicInformation){
    //go across each item in demographicInformation array
    for ( let j = 0; j < demographicInformation.length; j++ ) {
      //for as many as are in each of demographicInformation's elements
      for ( let i = 1; i <= demographicInformation[j]; i++ ) {
        let competitorNameBlueprint = counter.toString();
        let competitorBlueprint = '{"c' + competitorNameBlueprint
              + '":{"rating":1600,"wins":0,"losses":0,"record":"","beltRank":'
              + j  + ',"belt":"' + jiujitsuBelts[j] + '","matches":""}}';
        counter++;

        bullPen.push(JSON.parse(competitorBlueprint));
      }
    }
  };
  competitorAssemblerAndBullPenPopulator(demographicInformation);
};

var separateBelts = function(demographicInformation,bullPen){
  console.log("demographicInformation:",demographicInformation);
  console.log("separateBelt's bullPen:",bullPen);
  let numberOfBelts = demographicInformation.shift();
  for ( let i = 0; i < numberOfBelts; i++ ) {
    aboutToCompeteArray.push(bullPen.shift());
  }

  bullPenLength = bullPen.length;
  aboutToCompeteArrayLength = aboutToCompeteArray.length;
};

/**
 * @name - competitionMatPopulator
 * @description - Takes as input bullPen array
 *                Removes first and second competitors from bullPen
 *                And places them inside theCompetitionMats
 * @param - bullPen
 *
 **/
var competitionMatPopulator = function(aboutToCompeteArray, bullPen){
  theCompetitionMats.push(aboutToCompeteArray.shift())
  theCompetitionMats.push(bullPen.pop())
};

/**
 * @name - variableAssigner
 * @description - Assigns to variables all statistics relevant to calculations for
 *                the two competitors on theCompetitionMats.
 * @param - theCompetitionMats
 **/
var scribe = function(theCompetitionMats){
  firstCompetitor       = theCompetitionMats[0];
  firstCompetitorName   = Object.keys(firstCompetitor)[0];
  firstCompetitorRating = firstCompetitor[firstCompetitorName]['rating'];
  firstCompetitorWins   = firstCompetitor[firstCompetitorName]['wins'];
  firstCompetitorLosses = firstCompetitor[firstCompetitorName]['losses'];
  firstCompetitorRecord = firstCompetitor[firstCompetitorName]['record'];
  firstCompetitorBelt   = firstCompetitor[firstCompetitorName]['belt'];
  firstCompetitorBeltRank = firstCompetitor[firstCompetitorName]['beltRank'];

  secondCompetitor       = theCompetitionMats[1];
  secondCompetitorName   = Object.keys(secondCompetitor)[0];
  secondCompetitorRating = secondCompetitor[secondCompetitorName]['rating'];
  secondCompetitorWins   = secondCompetitor[secondCompetitorName]['wins'];
  secondCompetitorLosses = secondCompetitor[secondCompetitorName]['losses'];
  secondCompetitorRecord = secondCompetitor[secondCompetitorName]['record'];
  secondCompetitorBelt   = secondCompetitor[secondCompetitorName]['belt'];
  secondCompetitorBeltRank = secondCompetitor[secondCompetitorName]['beltRank'];

  //important to save this step for last
  //otherwise secondCompetitorsRating may not be defined
  //at assignment-time for firstCompetitorsProbabilityOfVictory
  firstCompetitorsProbabilityOfVictory  = 1 / (1 + Math.pow(10, ((secondCompetitorRating - firstCompetitorRating) / 400)));
  secondCompetitorsProbabilityOfVictory = 1 / (1 + Math.pow(10, ((firstCompetitorRating - secondCompetitorRating) / 400)));
};

//should compare against numerical representation of belt
var biasedReferee = function(firstCompetitorBeltRank,secondCompetitorBeltRank){

  //records all their relevant information
  matchRecorder();

  //calculates winner -- highest belt always wins
  if ( firstCompetitorBeltRank < secondCompetitorBeltRank ) {
    firstCompetitor[firstCompetitorName]['wins']++;
    firstCompetitor[firstCompetitorName]['record'] = firstCompetitorRecord + "w";

    secondCompetitor[secondCompetitorName]['losses']++;
    secondCompetitor[secondCompetitorName]['record'] = secondCompetitorRecord + "l";
  } else {
    firstCompetitor[firstCompetitorName]['losses']++;
    firstCompetitor[firstCompetitorName]['record'] = firstCompetitorRecord + "l";

    secondCompetitor[secondCompetitorName]['wins']++;
    secondCompetitor[secondCompetitorName]['record'] = secondCompetitorRecord + "w";
  }
};

/**
 * @name - ratingsAdjuster
 * @description - Determines the result of firstCompetitor's match
 *                ** ratingsAtStakeCalculator(k) -- calculates the ratings at stake for each player
 *                                                  depending on whether they win or lose
 *                Adds additional ratings points to winner
 *                Subtracts rating points from loser
 * @param - theCompetitionMats
 * @param - k-factor
 **/
var ratingsAdjuster = function(theCompetitionMats,k) {
  let firstCompetitorLastMatchResult = theCompetitionMats[0][firstCompetitorName]['record'].slice(theCompetitionMats[0][firstCompetitorName]['record'].length-1);
  ratingsAtStakeCalculator(k);

  if ( firstCompetitorLastMatchResult === 'w' ) {
    firstCompetitor[firstCompetitorName]['rating']   = Math.round(firstCompetitorRating + ifFirstCompetitorWins);
    secondCompetitor[secondCompetitorName]['rating'] = Math.round(secondCompetitorRating + ifSecondCompetitorLoses);
  } else {
    firstCompetitor[firstCompetitorName]['rating']   = Math.round(firstCompetitorRating + ifFirstCompetitorLoses);
    secondCompetitor[secondCompetitorName]['rating'] = Math.round(secondCompetitorRating + ifSecondCompetitorWins);
  }
  firstCompetitorRecord  = firstCompetitor[firstCompetitorName]['record'];
  secondCompetitorRecord = secondCompetitor[secondCompetitorName]['record'];
};

/**
 * @name - ratingsAtStakeCalculator
 * @description - Calculates how much each competitorObject in theCompetitionMats
 *                stands to win or lose based on the result of the match.
 * @param - k-factor
 **/
var ratingsAtStakeCalculator = function(k){
  ifFirstCompetitorWins   = k*(1-firstCompetitorsProbabilityOfVictory);
  ifFirstCompetitorLoses  = k*(-firstCompetitorsProbabilityOfVictory);
  ifSecondCompetitorWins  = k*(1-secondCompetitorsProbabilityOfVictory);
  ifSecondCompetitorLoses = k*(-secondCompetitorsProbabilityOfVictory);
};

/**
 * @name - matchRecorder
 * @description - To 'matches' key in competitorObject, assigns value -->
 *                stringified record of match just finished in theCompetitionMats.
 *                Each match is delimited by '***'
 * @example - 'matches': {'1600-c733-1600***1588-c503-1613'}
 *             where at time of match: '1600' is competitorObject's rating
 *                                     'c733' is competitorObject's opponent
 *                                     '1600' is competitorObject's opponent's rating
 *             '***' delimiter
 *             Second match:           '1588' is competitorObject's rating
 *                                     'c503' is competitorObject's opponent
 *                                     '1613' is competitorObject's opponent's rating
 * @param - none
 **/

//should record belt of opponent too
//should also record the match number in the field
//would help keep everything in place
var matchRecorder = function(){
  firstCompetitor[firstCompetitorName]['matches'] = firstCompetitor[firstCompetitorName]['matches']
                                                  + firstCompetitorRating.toString()
                                                  + "-" + secondCompetitorName
                                                  + "-" + secondCompetitorRating.toString() + "***";

  secondCompetitor[secondCompetitorName]['matches'] = secondCompetitor[secondCompetitorName]['matches']
                                                    + secondCompetitorRating.toString()
                                                    + "-" + firstCompetitorName
                                                    + "-" + firstCompetitorRating.toString() + "***";
};

/**
 * @name - competitionMatDepopulator
 * @description - Checks last entry of firstCompetitorRecord
 *                Then places winner of match into innersBracket
 *                And loser of match into losersBracket
 * @param - firstCompetitorRecord
 * @param - theCompetitionMats
 **/
var competitionMatDepopulator = function(firstCompetitorRecord,theCompetitionMats){
  if ( firstCompetitorRecord.charAt(firstCompetitorRecord.length-1) === 'w' ) {
    losersBracket.push(theCompetitionMats.pop());
  }
};

var runMatchesAgainstDifferentBelts = function(theCompetitionMats,bullPen,k){
  // console.log("at the beginning of runMatchesAgainstDifferentBelts --> demographicInformation:",demographicInformation);
  // console.log("at the beginning of runMatchesAgainstDifferentBelts --> bullPen:",bullPen);

  //black belt beats every single non-black belt in the tournament
  for ( let i = 0; i < bullPenLength; i++ ) {
    //puts last white belt on stage
    theCompetitionMats.push(bullPen.pop());

    //ringside assistants record their information
    scribe(theCompetitionMats);

    //assigns victory to competitor with highest belt
    biasedReferee(firstCompetitorBeltRank,secondCompetitorBeltRank);

    //calculates ratings at stake
    //and adjusts competitors's ratings based on their result
    ratingsAdjuster(theCompetitionMats,k);

    //loser is pushed to losersBracket
    losersBracket.push(theCompetitionMats.pop());
  }

  // console.log("at the end of runMatchesAgainstDifferentBelts --> demographicInformation:",demographicInformation);
  // console.log("at the end of runMatchesAgainstDifferentBelts --> bullPen:",bullPen);
};

var makeAWholeBeltDivisionCompete = function(demographicInformation,bullPen,k) {
  console.log("makeAWholeBeltDivisionCompete's --> demographicInformation:",demographicInformation);
  console.log("makeAWholeBeltDivisionCompete's --> bullPen:",bullPen);

  //makes each black belt compete
  for ( let i = 0; i < aboutToCompeteArrayLength; i++ ) {

    //puts first black belt on stage
    theCompetitionMats.push(aboutToCompeteArray.shift());

    //makes black belt on stage have a match with every non-black belt competitor
    //the error is here!

    //unsure exactly what is wrong.
    //for some reason -- while i = 1,
    //bullPen is empty
    //losersBracket is also empty
    //But the logic does not fail when i = 0
    //the logic works perfectly
    //cant figure out exactly why

    runMatchesAgainstDifferentBelts(theCompetitionMats,bullPen,k);
    console.log("i:",i);
    console.log("inside makeAWholeBeltDivisionCompete's -- after runMatchesAgainstDifferentBelts --> bullPen:",bullPen);
    console.log("losersBracket:",losersBracket);
    console.log("bullPen immediately after runMatchesAgainstDifferentBelts:",bullPen);
    //take finished black belt off stage
    finishedCompeting.push(theCompetitionMats.pop());

    debugger;
    //put losers (who all lost to an individual higher belt) back into bullPen
    bullPen = losersBracket.reverse();

    //empty losersBracket
    losersBracket = [];
  };
  console.log("after a for-loop makeAWholeBeltDivisionCompete's --> demographicInformation:",demographicInformation);
  console.log("after a for-loop makeAWholeBeltDivisionCompete's --> bullPen:",bullPen);

  // console.log("right after makeAWholeBeltDivisionCompete finished --> bullPen:",bullPen)
};

/**
 * @name - mundialTournament
 * @description - Makes all competitorObjects in bullPen compete once
 *                **bullPenGenerator -- builds competitors; populates bullPen
 *                **roundsCalculator -- calculates the number of rounds 1st and 2nd will fight!
 *                Invokes runAllMatchesForOneRound() for numberOfRounds
 * @param - integer
 * @param - k-factor
 **/
var mundialTournament = function(demographicInformation,k){

  //sets up the tournament
  bullPenGenerator(demographicInformation);

  for ( let i = 0; i < 2; i++ ) {
    // console.log("right before makeAWholeBeltDivisionCompete bullPen:",bullPen)

    //gets leftmost belts ready to compete
    separateBelts(demographicInformation,bullPen);

    // console.log("after separateBelts bullPen:",bullPen);
    // console.log("after separateBelts losersBracket:",losersBracket);
    // console.log("after separateBelts aboutToCompeteArray:",aboutToCompeteArray);
    // console.log("after separateBelts theCompetitionMats:",theCompetitionMats);
    // console.log("after separateBelts theCompetitionMats.length:",theCompetitionMats.length);
    // console.log("after separateBelts bullPen had",bullPen.length,"number of competitors!");
    // console.log("after separateBelts finishedCompeting:",finishedCompeting);

    //separates leftmost belts in original bullPen array
    makeAWholeBeltDivisionCompete(demographicInformation,bullPen,k);

    // console.log("after makeAWholeBeltDivisionCompete --> bullPen:",bullPen);
    // console.log("after makeAWholeBeltDivisionCompete --> losersBracket:",losersBracket);
    // console.log("after makeAWholeBeltDivisionCompete --> aboutToCompeteArray:",aboutToCompeteArray);
    // console.log("after makeAWholeBeltDivisionCompete --> theCompetitionMats:",theCompetitionMats);
    // console.log("after makeAWholeBeltDivisionCompete --> theCompetitionMats.length:",theCompetitionMats.length);
    // console.log("after makeAWholeBeltDivisionCompete --> bullPen had",bullPen.length,"number of competitors!");
    // console.log("after makeAWholeBeltDivisionCompete --> finishedCompeting:",finishedCompeting);

    //put losers who lost to all belts higher back into bullPen
    // bullPen = losersBracket;
  }

  // for ( let i = 0; i < demographicInformation.length; i++ ) {
  //   separateBelts(demographicInformation,bullPen);
  //   for ( let i = 0; i < aboutToCompeteArrayLength; i++ ) {
  //     theCompetitionMats.push(aboutToCompeteArray.shift());
  //     theCompetitionMats.push(bullPen.pop());
  //     for ( let i = 0; i < bullPenLength; i++ ) {
  //       scribe(theCompetitionMats);
  //       biasedReferee(firstCompetitorBeltRank,secondCompetitorBeltRank);
  //       ratingsAdjuster(theCompetitionMats,k)
  //       competitionMatDepopulator(firstCompetitorRecord,theCompetitionMats);
  //       if ( bullPen.length !== 0 ) {
  //         theCompetitionMats.push(bullPen.pop())
  //       }
  //     }
  //     bullPen = losersBracket;
  //     losersBracket = [];
  //     finishedCompeting.push(theCompetitionMats.pop());
  //   }
  // }
};

// Will generate competitors equal to sum of demographicInformation which will
// Compete each belt vs each other belt
// Until a winner is declared.
// k is the maximal number of points a player can win/lose in a given match
mundialTournament(demographicInformation,25);<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var DataModel = require("../dataModel");
var when = require("promised-io/promise").when;
var errors = require("dactic/errors");
var UserModel = DataModel.get("user");
var generateToken = require("../generateToken");
var validateToken = require("../validateToken");
var bcrypt = require("bcrypt");

/* Basic Password auth */
router.post('/', [
	bodyParser.urlencoded({extended:true}),
	function(req, res, next) {

		if (!req.body.username || !req.body.password){
			return next(new errors.Unauthorized("Missing Username or Password"));
		}

		when(UserModel.validatePassword(req.body.username,req.body.password), function(ruser){
			var user = ruser.getData();
			if (user) {
				var token = generateToken(user,"user")
				res.status(200);
				res.send(token);
				res.end();
				return;
			}else{
				next(errors.Unauthorized("Invalid username, email, o r password"));
			}
		}, function(err){
			next(errors.Unauthorized("Invalid username, email, or password"));
		});
	}
]);

/* Superuser Login */
router.post('/sulogin', [
	bodyParser.urlencoded({extended:true}),
	function(req, res, next) {
		console.log("Authenticate User Token: ", req.body);

		if (!req.body.username || !req.body.password || !req.body.targetUser){
			return next(new errors.Unauthorized("Missing Username, Password, or Target User"));
		}

		console.log("Get User: ", req.body.username);
		when(UserModel.get(req.body.username), function(ruser){
			var user = ruser.getData();
			console.log("Got Login User: ", user);
			if (!user || !user.roles || (user.roles.length<1) || (user.roles.indexOf("admin")<0)){
				return next(errors.Unauthorized());
			}

			bcrypt.compare(req.body.password,user.password, function(err,response){
				console.log("Authenticated");
				if (err) { console.log("Invalid Password"); next(errors.Unauthorized(err)); }
				when(UserModel.get(req.body.targetUser), function(tres){
					if (!tres){
						return next(errors.NotAcceptable("Invalid Target User"));
					}
					var tuser = tres.getData();

					console.log("Target User: ", tuser);
					var token = generateToken(tuser,"user")
					res.status(200);
					res.send(token);
					res.end();
					return;
				}, function(){
					next(errors.NotAcceptable("Invalid Target User"));
				});
			})
		});
	}
]);

/* Refresh a valid token */
router.get('/refresh',
	function(req, res, next) {
		if (!req.user){
			return next(new errors.Unauthorized("Invalid Token"));
		}

		console.log("Refresh Token: ", req.user);
		when(UserModel.get(req.user.id), function(ruser){
			var user = ruser.getData()
			var u = {
				id: user.id,
				roles: user.roles || []
			}
			var token = generateToken(user,"user")
			res.status(200);
			res.send(token);
			res.end();
		});
	}
);

/* get a 'service' token with a valid user and application token */
router.post('/service', [
	bodyParser.urlencoded({extended:true}),
	function(req, res, next) {
		console.log("Authenticate Service Token: ", req.user);
		if (!req.user || !req.user.id){
			return next(new errors.Unauthorized("Invalid Application Token"));
		}

		if (!req.user.scope || (req.user.scope != "application")) {
			return next(new errors.Unauthorized("Application Scoped Token Required"));
		}

		if (!req.body.token){
			return next(new errors.Unauthorized("Missing User Token"));
		}

		// TODO validate body.token
		when(validateToken(req.body.token), function(tuser){
			console.log("Body Token Data: ", tuser);
			when(UserModel.get(tuser.id), function(ruser){
				var user = ruser.getData();
				if (user) {
					var token = generateToken(user,"service")
					res.status(200);
					res.send(token);
					res.end();
					return;
				}
			}, function(err){
				return next(new errors.NotAcceptable(err));
			});
		})
	}
]);

module.exports = router;
<commit_msg>fix typo<commit_after>var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var DataModel = require("../dataModel");
var when = require("promised-io/promise").when;
var errors = require("dactic/errors");
var UserModel = DataModel.get("user");
var generateToken = require("../generateToken");
var validateToken = require("../validateToken");
var bcrypt = require("bcrypt");

/* Basic Password auth */
router.post('/', [
	bodyParser.urlencoded({extended:true}),
	function(req, res, next) {

		if (!req.body.username || !req.body.password){
			return next(new errors.Unauthorized("Missing Username or Password"));
		}

		when(UserModel.validatePassword(req.body.username,req.body.password), function(ruser){
			var user = ruser.getData();
			if (user) {
				var token = generateToken(user,"user")
				res.status(200);
				res.send(token);
				res.end();
				return;
			}else{
				next(errors.Unauthorized("Invalid username, email, or password"));
			}
		}, function(err){
			next(errors.Unauthorized("Invalid username, email, or password"));
		});
	}
]);

/* Superuser Login */
router.post('/sulogin', [
	bodyParser.urlencoded({extended:true}),
	function(req, res, next) {
		console.log("Authenticate User Token: ", req.body);

		if (!req.body.username || !req.body.password || !req.body.targetUser){
			return next(new errors.Unauthorized("Missing Username, Password, or Target User"));
		}

		console.log("Get User: ", req.body.username);
		when(UserModel.get(req.body.username), function(ruser){
			var user = ruser.getData();
			console.log("Got Login User: ", user);
			if (!user || !user.roles || (user.roles.length<1) || (user.roles.indexOf("admin")<0)){
				return next(errors.Unauthorized());
			}

			bcrypt.compare(req.body.password,user.password, function(err,response){
				console.log("Authenticated");
				if (err) { console.log("Invalid Password"); next(errors.Unauthorized(err)); }
				when(UserModel.get(req.body.targetUser), function(tres){
					if (!tres){
						return next(errors.NotAcceptable("Invalid Target User"));
					}
					var tuser = tres.getData();

					console.log("Target User: ", tuser);
					var token = generateToken(tuser,"user")
					res.status(200);
					res.send(token);
					res.end();
					return;
				}, function(){
					next(errors.NotAcceptable("Invalid Target User"));
				});
			})
		});
	}
]);

/* Refresh a valid token */
router.get('/refresh',
	function(req, res, next) {
		if (!req.user){
			return next(new errors.Unauthorized("Invalid Token"));
		}

		console.log("Refresh Token: ", req.user);
		when(UserModel.get(req.user.id), function(ruser){
			var user = ruser.getData()
			var u = {
				id: user.id,
				roles: user.roles || []
			}
			var token = generateToken(user,"user")
			res.status(200);
			res.send(token);
			res.end();
		});
	}
);

/* get a 'service' token with a valid user and application token */
router.post('/service', [
	bodyParser.urlencoded({extended:true}),
	function(req, res, next) {
		console.log("Authenticate Service Token: ", req.user);
		if (!req.user || !req.user.id){
			return next(new errors.Unauthorized("Invalid Application Token"));
		}

		if (!req.user.scope || (req.user.scope != "application")) {
			return next(new errors.Unauthorized("Application Scoped Token Required"));
		}

		if (!req.body.token){
			return next(new errors.Unauthorized("Missing User Token"));
		}

		// TODO validate body.token
		when(validateToken(req.body.token), function(tuser){
			console.log("Body Token Data: ", tuser);
			when(UserModel.get(tuser.id), function(ruser){
				var user = ruser.getData();
				if (user) {
					var token = generateToken(user,"service")
					res.status(200);
					res.send(token);
					res.end();
					return;
				}
			}, function(err){
				return next(new errors.NotAcceptable(err));
			});
		})
	}
]);

module.exports = router;
<|endoftext|>


<commit_before>var _ = require("underscore");
var github = require('octonode');
var moment = require('moment');
var request = require('request');
var Q = require('q');

module.exports = function (mongoRepository, qdService) {
    var getGithubPushEventsPerPage = function (page, userInfo) {
        var githubUsername = userInfo.githubUsername;
        var user_api_url = "/users/" + githubUsername;
        var client = github.client(userInfo.accessToken);
        client.get(user_api_url, {}, function (err, status, body, headers) {
        });
        var githubUser = client.user(githubUsername);

        var deferred = Q.defer();
        githubUser.events(page, ['PushEvent'], function (err, pushEvents) {
            if (err) {
                console.log("err " + err);
                deferred.reject(err);
            } else {
                deferred.resolve(pushEvents);
            }
        });
        return deferred.promise;
    };
    var fetchGithubPushEvents = function (userInfo, streamInfo) {
        var deferred = Q.defer();
        var pages = _.range(1, 11);
        var promiseArray = _.map(pages, function (page) {
            return getGithubPushEventsPerPage(page, userInfo);
        });
        Q.all(promiseArray)
            .then(_.flatten)
            .then(function (events) {
                deferred.resolve(events);
            });
        return deferred.promise;
    };
    var filterEventsToBeSent = function (events, lastSyncDate) {
        var eventsToBeSent = function (event) {
            return moment(event.created_at).isAfter(lastSyncDate);
        };
        return _.filter(events, eventsToBeSent);
    };

    var convertEventsTo1SelfFormat = function (filteredEvents) {
        var convertEventTo1SelfFormat = function (event) {
            var clone = function (obj) {
                return JSON.parse(JSON.stringify(obj));
            };
            if (event.type == "PushEvent") {
                var singleEventTemplate = {
                    "actionTags": [
                        "Github",
                        "Push"
                    ],
                    "source": "GitHub",
                    "objectTags": [
                        "Computer",
                        "Software",
                        "Source Control"
                    ],
                    "dateTime": moment(event.created_at).toISOString(),
                    "latestSyncField": {
                        "$date": moment(event.created_at).toISOString()
                    },
                    "properties": {
                        "pushId": event.payload["push_id"],
                        "commitIds": _.map(event.payload.commits, function (c) {
                            return c['sha']
                        })
                    }
                };
            } else if (event.commit != undefined) {
                var singleEventTemplate = {
                    "actionTags": [
                        "commit"
                    ],
                    "source": "GitHub",
                    "objectTags": [
                        "git",
                        "github",
                        "computer",
                        "software",
                        "source control"
                    ],
                    "dateTime": moment(event.created_at).toISOString(),
                    "latestSyncField": {
                        "$date": moment(event.created_at).toISOString()
                    },
                    "properties": {
                        "pushId": event.pushId,
                        "sha": event.sha,
                        "author-name": event.commit.author.name,
                        "author-email": event.commit.author.email,
                        "author-date": event.commit.author.date,
                        "message": event.commit.message,
                        "url": event.commit.url,
                        "line-changes": event.stats.total,
                        "line-additions": event.stats.additions,
                        "line-deletions": event.stats.deletions
                        //"file-changes": event.files.changes,
                        //"file-additions": event.files.additions,
                        //"file-deletions": event.files.deletions
                    }
                };
            } else {
                console.log("ERROR commit ---->", JSON.stringify(event))
            }
            return clone(singleEventTemplate);
        };
        return _.map(filteredEvents, convertEventTo1SelfFormat);
    };

    var sendEventsToQD = function (events, streamInfo) {
        var deferred = Q.defer();
        if (_.isEmpty(events)) {
            deferred.resolve();
        }
        qdService.sendBatchEvents(events, streamInfo)
            .then(function () {
                console.log("Events sent to 1self!!!");
                deferred.resolve();
            }, function (error) {
                deferred.reject(error);
            });
        return deferred.promise;
    };
    var createSyncStartEvent = function () {
        return {
            "dateTime": moment().toISOString(),
            "objectTags": ["sync"],
            "actionTags": ["start"],
            "properties": {
                "source": "GitHub"
            }
        };
    };
    var createSyncCompleteEvent = function () {
        return {
            "dateTime": moment().toISOString(),
            "objectTags": ["sync"],
            "actionTags": ["complete"],
            "properties": {
                "source": "GitHub"
            }
        };
    };

    var getGithubCommitEvents = function (filteredEvents) {
        var deferred = Q.defer();

        var commitObjects = [];
        _.each(filteredEvents, function (event) {
            _.each(event.payload.commits, function (commit) {
                commitObjects.push({url: commit['url'], pushId: event.payload["push_id"]})
            })
        });

        var getCommitPromise = function (commitObject) {
            var deferred = Q.defer();
            console.log("Hitting request")

            var options = {
                url: commitObject.url,
                headers: {
                    "User-Agent": "1self"
                }
            };
            request(options, function (err, res, body) {
                if (!err) {
                    var commit = JSON.parse(body);
                    commit.pushId = commitObject.pushId
                    deferred.resolve(commit);
                }
                else {
                    deferred.reject(err);
                }
            });
            return deferred.promise;
        };

        var promiseArray = [];

        //commitObjects = commitObjects.slice(0, 3);

        _.map(commitObjects, function (commitObject) {
            promiseArray.push(getCommitPromise(commitObject))
        });

        Q.all(promiseArray).then(function (commitEvents) {
            var events = filteredEvents.concat(commitEvents)
            deferred.resolve(events);
        }).catch(function (error) {
            console.log("Error occurred", error);
        });

        return deferred.promise;
    };

    this.sendGithubEvents = function (userInfo, streamInfo) {
        var syncStartEvent = createSyncStartEvent();

        qdService.sendEvent(syncStartEvent, streamInfo)
            .then(function () {
                return fetchGithubPushEvents(userInfo, streamInfo)
            })
            .then(function (events) {
                return filterEventsToBeSent(events, streamInfo.lastSyncDate);
            })
            .then(getGithubCommitEvents)
            .then(convertEventsTo1SelfFormat)
            .then(function (eventsToBeSent) {
                return sendEventsToQD(eventsToBeSent, streamInfo);
            })
            .then(function () {
                var syncCompleteEvent = createSyncCompleteEvent();
                return qdService.sendEvent(syncCompleteEvent, streamInfo);
            }).catch(function (error) {
                console.error("Error occurred", error)
            });
    };
}
;
<commit_msg>Log error<commit_after>var _ = require("underscore");
var github = require('octonode');
var moment = require('moment');
var request = require('request');
var Q = require('q');

module.exports = function (mongoRepository, qdService) {
    var getGithubPushEventsPerPage = function (page, userInfo) {
        var githubUsername = userInfo.githubUsername;
        var user_api_url = "/users/" + githubUsername;
        var client = github.client(userInfo.accessToken);
        client.get(user_api_url, {}, function (err, status, body, headers) {
        });
        var githubUser = client.user(githubUsername);

        var deferred = Q.defer();
        githubUser.events(page, ['PushEvent'], function (err, pushEvents) {
            if (err) {
                console.log("err " + err);
                deferred.reject(err);
            } else {
                deferred.resolve(pushEvents);
            }
        });
        return deferred.promise;
    };
    var fetchGithubPushEvents = function (userInfo, streamInfo) {
        var deferred = Q.defer();
        var pages = _.range(1, 11);
        var promiseArray = _.map(pages, function (page) {
            return getGithubPushEventsPerPage(page, userInfo);
        });
        Q.all(promiseArray)
            .then(_.flatten)
            .then(function (events) {
                deferred.resolve(events);
            });
        return deferred.promise;
    };
    var filterEventsToBeSent = function (events, lastSyncDate) {
        var eventsToBeSent = function (event) {
            return moment(event.created_at).isAfter(lastSyncDate);
        };
        return _.filter(events, eventsToBeSent);
    };

    var convertEventsTo1SelfFormat = function (filteredEvents) {
        var convertEventTo1SelfFormat = function (event) {
            var clone = function (obj) {
                return JSON.parse(JSON.stringify(obj));
            };
            if (event.type == "PushEvent") {
                var singleEventTemplate = {
                    "actionTags": [
                        "Github",
                        "Push"
                    ],
                    "source": "GitHub",
                    "objectTags": [
                        "Computer",
                        "Software",
                        "Source Control"
                    ],
                    "dateTime": moment(event.created_at).toISOString(),
                    "latestSyncField": {
                        "$date": moment(event.created_at).toISOString()
                    },
                    "properties": {
                        "pushId": event.payload["push_id"],
                        "commitIds": _.map(event.payload.commits, function (c) {
                            return c['sha']
                        })
                    }
                };
            } else if (event.commit != undefined) {
                var singleEventTemplate = {
                    "actionTags": [
                        "commit"
                    ],
                    "source": "GitHub",
                    "objectTags": [
                        "git",
                        "github",
                        "computer",
                        "software",
                        "source control"
                    ],
                    "dateTime": moment(event.created_at).toISOString(),
                    "latestSyncField": {
                        "$date": moment(event.created_at).toISOString()
                    },
                    "properties": {
                        "pushId": event.pushId,
                        "sha": event.sha,
                        "author-name": event.commit.author.name,
                        "author-email": event.commit.author.email,
                        "author-date": event.commit.author.date,
                        "message": event.commit.message,
                        "url": event.commit.url,
                        "line-changes": event.stats.total,
                        "line-additions": event.stats.additions,
                        "line-deletions": event.stats.deletions
                        //"file-changes": event.files.changes,
                        //"file-additions": event.files.additions,
                        //"file-deletions": event.files.deletions
                    }
                };
            } else {
                console.log("ERROR commit ---->", JSON.stringify(event))
            }
            return clone(singleEventTemplate);
        };
        return _.map(filteredEvents, convertEventTo1SelfFormat);
    };

    var sendEventsToQD = function (events, streamInfo) {
        var deferred = Q.defer();
        if (_.isEmpty(events)) {
            deferred.resolve();
        }
        qdService.sendBatchEvents(events, streamInfo)
            .then(function () {
                console.log("Events sent to 1self!!!");
                deferred.resolve();
            }, function (error) {
                deferred.reject(error);
            });
        return deferred.promise;
    };
    var createSyncStartEvent = function () {
        return {
            "dateTime": moment().toISOString(),
            "objectTags": ["sync"],
            "actionTags": ["start"],
            "properties": {
                "source": "GitHub"
            }
        };
    };
    var createSyncCompleteEvent = function () {
        return {
            "dateTime": moment().toISOString(),
            "objectTags": ["sync"],
            "actionTags": ["complete"],
            "properties": {
                "source": "GitHub"
            }
        };
    };

    var getGithubCommitEvents = function (filteredEvents) {
        var deferred = Q.defer();

        var commitObjects = [];
        _.each(filteredEvents, function (event) {
            _.each(event.payload.commits, function (commit) {
                commitObjects.push({url: commit['url'], pushId: event.payload["push_id"]})
            })
        });

        var getCommitPromise = function (commitObject) {
            var deferred = Q.defer();
            console.log("Hitting request")

            var options = {
                url: commitObject.url,
                headers: {
                    "User-Agent": "1self"
                }
            };
            request(options, function (err, res, body) {
                if (!err) {
                    var commit = JSON.parse(body);
                    commit.pushId = commitObject.pushId
                    deferred.resolve(commit);
                }
                else {
                    console.log("Error occurred :: getCommitPromise", err);
                    deferred.reject(err);
                }
            });
            return deferred.promise;
        };

        var promiseArray = [];

        //commitObjects = commitObjects.slice(0, 3);

        _.map(commitObjects, function (commitObject) {
            promiseArray.push(getCommitPromise(commitObject))
        });

        Q.all(promiseArray).then(function (commitEvents) {
            var events = filteredEvents.concat(commitEvents)
            deferred.resolve(events);
        }).catch(function (error) {
            console.log("Error occurred", error);
        });

        return deferred.promise;
    };

    this.sendGithubEvents = function (userInfo, streamInfo) {
        var syncStartEvent = createSyncStartEvent();

        qdService.sendEvent(syncStartEvent, streamInfo)
            .then(function () {
                return fetchGithubPushEvents(userInfo, streamInfo)
            })
            .then(function (events) {
                return filterEventsToBeSent(events, streamInfo.lastSyncDate);
            })
            .then(getGithubCommitEvents)
            .then(convertEventsTo1SelfFormat)
            .then(function (eventsToBeSent) {
                return sendEventsToQD(eventsToBeSent, streamInfo);
            })
            .then(function () {
                var syncCompleteEvent = createSyncCompleteEvent();
                return qdService.sendEvent(syncCompleteEvent, streamInfo);
            }).catch(function (error) {
                console.error("Error occurred", error)
            });
    };
}
;
<|endoftext|>


<commit_before>var express = require('express'),
	router = express.Router();
var cartodbClient = require('../cartodbClient');
var secret = require('../secret');
var request = require('request');

//All routes derive from /parcels
router
.all(function(req,res,next){
	next();
})
.get('/',function(req,res){
	console.log('Query entire parcel collection');

	cartodbClient.query(
		"SELECT * FROM {table}",
		{
			table:"tdi_parcels"
		},
		function(err,data){
			//Assumes data is in GeoJSON

			if(err){ res.status(400).send(error); }

			console.log('successful GET to /parcel');

			data.features.forEach(function(feature){
				for(var key in feature.properties){
					feature[key] = feature.properties[key];
				}

				delete feature.properties;
			});
			res.json(data.features);
		}
	);

})
.get('/:id',function(req,res){

	cartodbClient.query(
		"SELECT * FROM {table} WHERE cartodb_id=" + req.params.id,
		{ table:"tdi_parcels" },
		function(err,data){
			if(err){ res.send(err); }
			else{

			console.log('successful GET to /parcel/' + req.params.id);

			//data returns a feature collection
				var feature = data.features[0];
				for(var key in feature.properties){
					feature[key] = feature.properties[key];
				}
				delete feature.properties;

				res.json(feature);
			}
		}
	);

})
.put('/:id',function(req,res){
	//HTTP PUT request assumes req.body contains the entire resource representation

	//Construct query string
	var query = "UPDATE tdi_parcels SET comment='"
		+ req.body.comment +
		"', modified="
		+ req.body.modified +
		", marked="
		+ req.body.marked +
		", city_owned="
		+ req.body.city_owned +
		", partner_owned="
		+ req.body.partner_owned +
		", vacancy="
		+ req.body.vacancy +
		", tdi_for_sale="
		+ req.body.tdi_for_sale +
		", tdi_for_lease="
		+ req.body.tdi_for_lease +
		", year_built="
		+ req.body.year_built +
		", zoning='"
		+ req.body.zoning + "'" +
		", owner1='"
		+ req.body.owner1 + "'" +
		" WHERE cartodb_id=" + req.params.id;

	console.log(query);

	//TODO: there is a bug here where, if UPDATE or INSERT query is made to the Cartodb API with format=GeoJSON,
	//it returns a syntax error

	/*cartodbClient.query(
		query,
		{table:"tdi_parcels"},
		function(err,data){
			if(err){
				console.log(err);
				res.status(400).send(err);
			}
			else{
				console.log("successful UPDATE to parcel "+req.params.id);
				res.json(req.body)
			};
		}
	)*/

	//TODO: this is a shim; manually make request to cartodb api without specifying GeoJSON format
	request("https://"+secret.USER+".cartodb.com/api/v2/sql?q=" + query + "&api_key=" + secret.API_KEY,
		function(err,response,body){
			if(err || response.statusCode != 200){
				console.error(err);
				res.status(400).send(err);
			}else{
				console.log("successful UPDATE to parcel "+req.params.id);
				res.json(req.body)
			}
		});

});

module.exports = router;
<commit_msg>Resolves #22<commit_after>var express = require('express'),
	router = express.Router();
var cartodbClient = require('../cartodbClient');
var secret = require('../secret');
var request = require('request');

//All routes derive from /parcels
router
.all(function(req,res,next){
	next();
})
.get('/',function(req,res){
	console.log('Query entire parcel collection');

	cartodbClient.query(
		"SELECT * FROM {table} WHERE use_code NOT LIKE '102%'",
		{
			table:"tdi_parcels"
		},
		function(err,data){
			//Assumes data is in GeoJSON

			if(err){ res.status(400).send(error); }

			console.log('successful GET to /parcel');

			data.features.forEach(function(feature){
				for(var key in feature.properties){
					feature[key] = feature.properties[key];
				}

				delete feature.properties;
			});
			res.json(data.features);
		}
	);

})
.get('/:id',function(req,res){

	cartodbClient.query(
		"SELECT * FROM {table} WHERE WHERE use_code NOT LIKE '102%' AND cartodb_id=" + req.params.id,
		{ table:"tdi_parcels" },
		function(err,data){
			if(err){ res.send(err); }
			else{

			console.log('successful GET to /parcel/' + req.params.id);

			//data returns a feature collection
				var feature = data.features[0];
				for(var key in feature.properties){
					feature[key] = feature.properties[key];
				}
				delete feature.properties;

				res.json(feature);
			}
		}
	);

})
.put('/:id',function(req,res){
	//HTTP PUT request assumes req.body contains the entire resource representation

	//Construct query string
	var query = "UPDATE tdi_parcels SET comment='"
		+ req.body.comment +
		"', modified="
		+ req.body.modified +
		", marked="
		+ req.body.marked +
		", city_owned="
		+ req.body.city_owned +
		", partner_owned="
		+ req.body.partner_owned +
		", vacancy="
		+ req.body.vacancy +
		", tdi_for_sale="
		+ req.body.tdi_for_sale +
		", tdi_for_lease="
		+ req.body.tdi_for_lease +
		", year_built="
		+ req.body.year_built +
		", zoning='"
		+ req.body.zoning + "'" +
		", owner1='"
		+ req.body.owner1 + "'" +
		" WHERE cartodb_id=" + req.params.id;

	console.log(query);

	//TODO: there is a bug here where, if UPDATE or INSERT query is made to the Cartodb API with format=GeoJSON,
	//it returns a syntax error

	/*cartodbClient.query(
		query,
		{table:"tdi_parcels"},
		function(err,data){
			if(err){
				console.log(err);
				res.status(400).send(err);
			}
			else{
				console.log("successful UPDATE to parcel "+req.params.id);
				res.json(req.body)
			};
		}
	)*/

	//TODO: this is a shim; manually make request to cartodb api without specifying GeoJSON format
	request("https://"+secret.USER+".cartodb.com/api/v2/sql?q=" + query + "&api_key=" + secret.API_KEY,
		function(err,response,body){
			if(err || response.statusCode != 200){
				console.error(err);
				res.status(400).send(err);
			}else{
				console.log("successful UPDATE to parcel "+req.params.id);
				res.json(req.body)
			}
		});

});

module.exports = router;
<|endoftext|>


<commit_before>/**
 * Created by bacchus on 6/11/14.
 */

function init() {

    $('.barcode_input').unbind("keyup", car_ret_add_bc);
    $('.barcode_input').keyup(car_ret_add_bc);

}

function car_ret_add_bc(e) {
    var evt = e || window.event
    // Check if next sibling has a value of "" in its textfield.  If so, set focus to that instead of adding another field.
    if(evt.keyCode === 17 || evt.keyCode === 13) {
        addBarcodeInput();
    }
}

function addBarcodeInput() {

    /*

            <input type="text" value="TEST1">

            <input type="checkbox" value="0">

     */

    var barcodes_tbl = document.getElementById('barcodes_table');

    var new_table_row = document.createElement('tr');

    var new_table_textbox_cell = document.createElement('td');
    var new_table_textbox_cell_input = document.createElement('input');

    var new_table_checkbox_cell = document.createElement('td');
    var new_table_checkbox_cell_checkbox = document.createElement('input');

    /* This hidden input value is neccesary to carry the value of an unchecked checkbox upon submission */
    var new_table_hidden_cb_value_input = document.createElement('input');

    new_table_textbox_cell_input.type = "text";
    new_table_textbox_cell_input.value = "";
    new_table_textbox_cell_input.name = "barcodes[]";
    new_table_textbox_cell_input.setAttribute("class", "barcode_input");

    new_table_checkbox_cell_checkbox.type = "checkbox";
    new_table_checkbox_cell_checkbox.name = "print_pocket_label_cb";
    new_table_checkbox_cell_checkbox.value = "no";
    new_table_checkbox_cell_checkbox.onclick = setCheckboxValue;

    new_table_hidden_cb_value_input.type = "hidden";
    new_table_hidden_cb_value_input.value = 0;
    new_table_hidden_cb_value_input.name = "print_pocket_label[]";

    new_table_textbox_cell.appendChild(new_table_textbox_cell_input);
    new_table_checkbox_cell.appendChild(new_table_checkbox_cell_checkbox);
    new_table_checkbox_cell.appendChild(new_table_hidden_cb_value_input);

    new_table_row.appendChild(new_table_textbox_cell);
    new_table_row.appendChild(new_table_checkbox_cell);

    barcodes_tbl.appendChild(new_table_row);

    altRows('barcodes_table');

    new_table_textbox_cell_input.focus();

    init();

}

function setCheckboxValue() {

    hidden_sibling = this.nextSibling;

    if (hidden_sibling.value == 0 || hidden_sibling.value == "") {
        this.value = "yes";
        hidden_sibling.value = 1;
    }
    else {
        this.value = "no";
        hidden_sibling.value = 0;
    }
}

function altRows(id){
    if(document.getElementsByTagName){

        var table = document.getElementById(id);
        var rows = table.getElementsByTagName("tr");

        for(i = 0; i < rows.length; i++){
            if(i % 2 == 0){
                rows[i].className = "evenrowcolor";
            }else{
                rows[i].className = "oddrowcolor";
            }
        }
    }
}<commit_msg>fixed car_ret_add_bc.  Now it checks to see if there are any empty barcode inputs below its position before adding another input field.  If there are, it just sets the focus to them.<commit_after>/**
 * Created by bacchus on 6/11/14.
 */

function init() {

    $('.barcode_input').unbind("keyup", car_ret_add_bc);
    $('.barcode_input').keyup(car_ret_add_bc);

}

function car_ret_add_bc(e) {
    var evt = e || window.event
    // Check if next sibling has a value of "" in its textfield.  If so, set focus to that instead of adding another field.

    var row = $(this).parent().parent();

    // If return carriage is present in input (scanner done with input)...
    if(evt.keyCode == 17 || evt.keyCode == 13) {
        // Then ... if there are no empty inputs below us, add a new one
        if (row.index() == row.siblings().length) {
            addBarcodeInput();
        }
        // If there are empty inputs below us, go to the next one and set focus.
        else {
            var sib = row.next().find('.barcode_input');
            sib.focus();
        }
    }
}

function addBarcodeInput() {

    /*

            <input type="text" value="TEST1">

            <input type="checkbox" value="0">

     */

    var barcodes_tbl = document.getElementById('barcodes_table');

    var new_table_row = document.createElement('tr');

    var new_table_textbox_cell = document.createElement('td');
    var new_table_textbox_cell_input = document.createElement('input');

    var new_table_checkbox_cell = document.createElement('td');
    var new_table_checkbox_cell_checkbox = document.createElement('input');

    /* This hidden input value is neccesary to carry the value of an unchecked checkbox upon submission */
    var new_table_hidden_cb_value_input = document.createElement('input');

    new_table_textbox_cell_input.type = "text";
    new_table_textbox_cell_input.value = "";
    new_table_textbox_cell_input.name = "barcodes[]";
    new_table_textbox_cell_input.setAttribute("class", "barcode_input");

    new_table_checkbox_cell_checkbox.type = "checkbox";
    new_table_checkbox_cell_checkbox.name = "print_pocket_label_cb";
    new_table_checkbox_cell_checkbox.value = "no";
    new_table_checkbox_cell_checkbox.onclick = setCheckboxValue;

    new_table_hidden_cb_value_input.type = "hidden";
    new_table_hidden_cb_value_input.value = 0;
    new_table_hidden_cb_value_input.name = "print_pocket_label[]";

    new_table_textbox_cell.appendChild(new_table_textbox_cell_input);
    new_table_checkbox_cell.appendChild(new_table_checkbox_cell_checkbox);
    new_table_checkbox_cell.appendChild(new_table_hidden_cb_value_input);

    new_table_row.appendChild(new_table_textbox_cell);
    new_table_row.appendChild(new_table_checkbox_cell);

    barcodes_tbl.appendChild(new_table_row);

    altRows('barcodes_table');

    new_table_textbox_cell_input.focus();

    init();

}

function setCheckboxValue() {

    hidden_sibling = this.nextSibling;

    if (hidden_sibling.value == 0 || hidden_sibling.value == "") {
        this.value = "yes";
        hidden_sibling.value = 1;
    }
    else {
        this.value = "no";
        hidden_sibling.value = 0;
    }
}

function altRows(id){
    if(document.getElementsByTagName){

        var table = document.getElementById(id);
        var rows = table.getElementsByTagName("tr");

        for(i = 0; i < rows.length; i++){
            if(i % 2 == 0){
                rows[i].className = "evenrowcolor";
            }else{
                rows[i].className = "oddrowcolor";
            }
        }
    }
}<|endoftext|>


<commit_before>define(function (require, exports, module) {
  'use strict';

  var Repository = app.getModule('core/Repository');
  var ProjectManager = app.getModule('engine/ProjectManager');
  var Engine = app.getModule('engine/Engine');
  var FileSystem = app.getModule('filesystem/FileSystem');
  var FileUtils = app.getModule('file/FileUtils');
  var Async = app.getModule('utils/Async');
  var UML = app.getModule('uml/UML');

  var CodeGenUtils = require('code-generator-utils');

  function RubyCodeGenerator(baseModel, basePath) {
    this.baseModel = baseModel;
    this.basePath = basePath;
  }

  RubyCodeGenerator.prototype.getIndentString = function (options) {
    if (options.useTab) {
      return '\t';
    } else {
      var indent = [];
      var length = options.indentSpaces;
      for (var i = 0; i < length; i++) {
        indent.push(' ');
      }

      return indent.join('');
    }
  };

  RubyCodeGenerator.prototype.generate = function (element, path, options) {
    var result = new $.Deferred();
    var _this = this;
    var fullPath;
    var directory;
    var codeWriter;
    var file;

    if (element instanceof type.UMLPackage) {
      fullPath = path + '/' + element.name;
      directory = FileSystem.getDirectoryForPath(fullPath);
      directory.create(function (error, stat) {
        if (!error) {
          Async.doSequentially(element.ownedElements, function (child) {
            return _this.generate(child, fullPath, options);
          }, false).then(result.resolve, result.reject);
        } else {
          result.reject(error);
        }
      });
    } else if (element instanceof type.UMLClass) {
      if (element.stereotype !== 'annotationType') {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        var moduleName = this.writePackage(codeWriter, element);
        if (moduleName) {
          codeWriter.writeLine('module ' + moduleName);
          codeWriter.indent();
        }

        this.writeClass(codeWriter, element, options);
        if (moduleName) {
          codeWriter.outdent();
          codeWriter.writeLine('end');
        }

        fullPath = path + '/' + codeWriter.fileName(element.name) + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      }
    } else {
      result.resolve();
    }

    return result.promise();
  };

  RubyCodeGenerator.prototype.getVisibility = function (element) {
    switch (element.visibility) {
      case UML.VK_PUBLIC:
        return 'public';
      case UML.VK_PROTECTED:
        return 'protected';
      case UML.VK_PRIVATE:
        return 'private';
    }

    return null;
  };

  RubyCodeGenerator.prototype.writePackage = function (codeWriter, element) {
    var path = null;

    if (element._parent) {
      path = _.map(element._parent.getPath(this.baseModel), function (e) {
        return e.name
      }).join('.');
    }

    return path;
  };

  RubyCodeGenerator.prototype.getSuperClasses = function (element) {
    var inheritances = Repository.getRelationshipsOf(element, function (relationship) {
      return (relationship instanceof type.UMLGeneralization && relationship.source === element);
    });
    return _.map(inheritances, function (inherit) {
      return inherit.target;
    });
  };

  RubyCodeGenerator.prototype.writeConstructor = function (codeWriter, element, options) {
    if (element.name.length) {
      var terms = [];
      var len = element.attributes.length;

      terms.push('def initialize(');
      for (var i = 0; i < len; i++) {
        terms.push(element.attributes[i].name);
        if (i !== len - 1) {
          terms.push(', ');
        }
      }

      codeWriter.writeLine(terms.join('') + ')');
      codeWriter.indent();
      for (var j = 0; j < len; j++) {
        codeWriter.writeLine('@' + element.attributes[j].name + ' = ' + element.attributes[j].name);
      }

      codeWriter.outdent();
      codeWriter.writeLine('end');
    }
  };

  RubyCodeGenerator.prototype.writeAttributeAccessor = function (type, visibility, codeWriter, element) {
    var terms = [];
    var len = element.attributes.length;
    var attributeVisibility;
    var publicAttributeLastIndex;
    var protectedAttributeLastIndex;
    var privateAttributeLastIndex;

    for (var i = 0; i < len; i++) {
      attributeVisibility = this.getVisibility(element.attributes[i]);

      if (attributeVisibility === 'public') {
        publicAttributeLastIndex = i;
      } else if (attributeVisibility === 'protected') {
        protectedAttributeLastIndex = i;
      } else if (attributeVisibility === 'private') {
        privateAttributeLastIndex = i;
      }
    }

    if (type === 'short' && visibility === 'public') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public') {
          terms.push(':' + element.attributes[i].name);
          if (i !== publicAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'protected') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          terms.push(':' + element.attributes[i].name);
          if (i !== protectedAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'private') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private') {
          terms.push(':' + element.attributes[i].name);
          if (i !== privateAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'long' && visibility === 'public') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== publicAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'protected') {
      codeWriter.writeLine();
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== protectedAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'private') {
      codeWriter.writeLine();
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== privateAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    }
  };

  RubyCodeGenerator.prototype.constructMethod = function (codeWriter, element, options) {
    if (element.name.length) {
      var parameters = element.getNonReturnParameters();
      var len = parameters.length;
      var methodVisibility = this.getVisibility(element);
      var indentationSpaces = this.getIndentString(options);
      var terms = '';

      terms += indentationSpaces;
      terms += 'def ' + element.name;
      if (len !== 0) {
        terms += '(';
        for (var i = 0; i < len; i++) {
          terms += parameters[i].name;
          if (i !== len - 1) {
            terms += ', ';
          } else {
            terms += ')';
          }
        }
      }

      terms += '\n';
      terms += indentationSpaces + indentationSpaces;
      if (methodVisibility === 'public') {
        terms += '# TODO(person name): Implement this method here.\n';
      } else {
        terms += indentationSpaces;
        terms += '# TODO(person name): Implement this method here.\n';
        terms += indentationSpaces;
      }

      terms += indentationSpaces + 'end';
    }

    return terms;
  }

  RubyCodeGenerator.prototype.writeMethod = function (publicTerms, protectedTerms, privateTerms, codeWriter, element, options) {
    if (publicTerms.length) {
      codeWriter.writeLine(publicTerms);
    }

    if (this.countAttributeByVisibility('protected', element) || protectedTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('protected');
      codeWriter.indent();
      if (options.useAttributeAccessor) {
        this.writeAttributeAccessor('short', 'protected', codeWriter, element);
        codeWriter.writeLine();
      } else if (!options.useAttributeAccessor) {
        this.writeAttributeAccessor('long', 'protected', codeWriter, element);
        codeWriter.writeLine();
      }

      codeWriter.outdent();
      if (protectedTerms.length) {
        codeWriter.writeLine(protectedTerms);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }

    if (this.countAttributeByVisibility('private', element) || privateTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('private');
      codeWriter.indent();
      if (options.useAttributeAccessor) {
        this.writeAttributeAccessor('short', 'private', codeWriter, element);
        codeWriter.writeLine();
      } else if (!options.useAttributeAccessor) {
        this.writeAttributeAccessor('long', 'private', codeWriter, element);
        codeWriter.writeLine();
      }

      codeWriter.outdent();
      if (privateTerms.length) {
        codeWriter.writeLine(privateTerms);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }
  };

  RubyCodeGenerator.prototype.countAttributeByVisibility = function (visibility, element) {
    var publicElementCount = 0;
    var protectedElementCount = 0;
    var privateElementCount = 0;
    var len = element.attributes.length;
    var elementVisibility;

    for (var i = 0; i < len; i++) {
      elementVisibility = this.getVisibility(element.attributes[i]);

      if (elementVisibility === 'public') {
        publicElementCount++;
      } else if (elementVisibility === 'protected') {
        protectedElementCount++;
      } else if (elementVisibility === 'private') {
        privateElementCount++;
      }
    }

    if (visibility === 'public') {
      return publicElementCount;
    } else if (visibility === 'protected') {
      return protectedElementCount;
    } else if (visibility === 'private') {
      return privateElementCount;
    }
  }

  RubyCodeGenerator.prototype.writeToStringMethod = function (codeWriter) {
    codeWriter.indent();
    codeWriter.writeLine('def to_s');
    codeWriter.indent();
    codeWriter.writeLine('\"Your string representation of the object will be written here.\"');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  }

  RubyCodeGenerator.prototype.writeClass = function (codeWriter, element, options) {
    var terms = [];

    terms.push('class');
    terms.push(element.name);

    var _inheritance = this.getSuperClasses(element);
    if (_inheritance.length) {
      terms.push('< ' + _inheritance[0].name);
    }

    codeWriter.writeLine(terms.join(' '));
    codeWriter.indent();

    if (options.useAttributeAccessor && this.countAttributeByVisibility('public', element)) {
      this.writeAttributeAccessor('short', 'public', codeWriter, element);
      codeWriter.writeLine();
    }

    if (options.initializeMethod) {
      this.writeConstructor(codeWriter, element, options);
      codeWriter.writeLine();
    }

    if (!options.useAttributeAccessor && this.countAttributeByVisibility('public', element)) {
      this.writeAttributeAccessor('long', 'public', codeWriter, element);
      codeWriter.writeLine();
    }

    codeWriter.outdent();

    var len = element.operations.length;
    var publicMethodLastIndex;
    var protectedMethodLastIndex;
    var privateMethodLastIndex;

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);

      if (methodVisibility === 'public') {
        publicMethodLastIndex = i;
      } else if (methodVisibility === 'protected') {
        protectedMethodLastIndex = i;
      } else if (methodVisibility === 'private') {
        privateMethodLastIndex = i;
      }
    }

    var publicTerms = '';
    var protectedTerms = '';
    var privateTerms = '';

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var methodString = this.constructMethod(codeWriter, element.operations[i], options);
      var indentationSpaces = this.getIndentString(options);

      if (methodVisibility === 'public') {
        publicTerms += methodString;
        if (i === publicMethodLastIndex) {
          publicTerms += '\n';
        } else {
          publicTerms += '\n\n';
        }
      } else if (methodVisibility === 'protected') {
        protectedTerms += methodString;
        if (i === protectedMethodLastIndex) {
          protectedTerms += '\n';
        } else {
          protectedTerms += '\n\n';
          protectedTerms += indentationSpaces;
        }
      } else if (methodVisibility === 'private') {
        privateTerms += methodString;
        if (i === privateMethodLastIndex) {
          privateTerms += '\n';
        } else {
          privateTerms += '\n\n';
          privateTerms += indentationSpaces;
        }
      }
    }

    this.writeMethod(publicTerms, protectedTerms, privateTerms, codeWriter, element, options);

    if (options.rubyToStringMethod) {
      this.writeToStringMethod(codeWriter);
    }

    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  function generate(baseModel, basePath, options) {
    var result = new $.Deferred();
    var rubyCodeGenerator = new RubyCodeGenerator(baseModel, basePath);

    return rubyCodeGenerator.generate(baseModel, basePath, options);
  }

  exports.generate = generate;
});
<commit_msg>Check if protected or private attributes exist before write them<commit_after>define(function (require, exports, module) {
  'use strict';

  var Repository = app.getModule('core/Repository');
  var ProjectManager = app.getModule('engine/ProjectManager');
  var Engine = app.getModule('engine/Engine');
  var FileSystem = app.getModule('filesystem/FileSystem');
  var FileUtils = app.getModule('file/FileUtils');
  var Async = app.getModule('utils/Async');
  var UML = app.getModule('uml/UML');

  var CodeGenUtils = require('code-generator-utils');

  function RubyCodeGenerator(baseModel, basePath) {
    this.baseModel = baseModel;
    this.basePath = basePath;
  }

  RubyCodeGenerator.prototype.getIndentString = function (options) {
    if (options.useTab) {
      return '\t';
    } else {
      var indent = [];
      var length = options.indentSpaces;
      for (var i = 0; i < length; i++) {
        indent.push(' ');
      }

      return indent.join('');
    }
  };

  RubyCodeGenerator.prototype.generate = function (element, path, options) {
    var result = new $.Deferred();
    var _this = this;
    var fullPath;
    var directory;
    var codeWriter;
    var file;

    if (element instanceof type.UMLPackage) {
      fullPath = path + '/' + element.name;
      directory = FileSystem.getDirectoryForPath(fullPath);
      directory.create(function (error, stat) {
        if (!error) {
          Async.doSequentially(element.ownedElements, function (child) {
            return _this.generate(child, fullPath, options);
          }, false).then(result.resolve, result.reject);
        } else {
          result.reject(error);
        }
      });
    } else if (element instanceof type.UMLClass) {
      if (element.stereotype !== 'annotationType') {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        var moduleName = this.writePackage(codeWriter, element);
        if (moduleName) {
          codeWriter.writeLine('module ' + moduleName);
          codeWriter.indent();
        }

        this.writeClass(codeWriter, element, options);
        if (moduleName) {
          codeWriter.outdent();
          codeWriter.writeLine('end');
        }

        fullPath = path + '/' + codeWriter.fileName(element.name) + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      }
    } else {
      result.resolve();
    }

    return result.promise();
  };

  RubyCodeGenerator.prototype.getVisibility = function (element) {
    switch (element.visibility) {
      case UML.VK_PUBLIC:
        return 'public';
      case UML.VK_PROTECTED:
        return 'protected';
      case UML.VK_PRIVATE:
        return 'private';
    }

    return null;
  };

  RubyCodeGenerator.prototype.writePackage = function (codeWriter, element) {
    var path = null;

    if (element._parent) {
      path = _.map(element._parent.getPath(this.baseModel), function (e) {
        return e.name
      }).join('.');
    }

    return path;
  };

  RubyCodeGenerator.prototype.getSuperClasses = function (element) {
    var inheritances = Repository.getRelationshipsOf(element, function (relationship) {
      return (relationship instanceof type.UMLGeneralization && relationship.source === element);
    });
    return _.map(inheritances, function (inherit) {
      return inherit.target;
    });
  };

  RubyCodeGenerator.prototype.writeConstructor = function (codeWriter, element, options) {
    if (element.name.length) {
      var terms = [];
      var len = element.attributes.length;

      terms.push('def initialize(');
      for (var i = 0; i < len; i++) {
        terms.push(element.attributes[i].name);
        if (i !== len - 1) {
          terms.push(', ');
        }
      }

      codeWriter.writeLine(terms.join('') + ')');
      codeWriter.indent();
      for (var j = 0; j < len; j++) {
        codeWriter.writeLine('@' + element.attributes[j].name + ' = ' + element.attributes[j].name);
      }

      codeWriter.outdent();
      codeWriter.writeLine('end');
    }
  };

  RubyCodeGenerator.prototype.writeAttributeAccessor = function (type, visibility, codeWriter, element) {
    var terms = [];
    var len = element.attributes.length;
    var attributeVisibility;
    var publicAttributeLastIndex;
    var protectedAttributeLastIndex;
    var privateAttributeLastIndex;

    for (var i = 0; i < len; i++) {
      attributeVisibility = this.getVisibility(element.attributes[i]);

      if (attributeVisibility === 'public') {
        publicAttributeLastIndex = i;
      } else if (attributeVisibility === 'protected') {
        protectedAttributeLastIndex = i;
      } else if (attributeVisibility === 'private') {
        privateAttributeLastIndex = i;
      }
    }

    if (type === 'short' && visibility === 'public') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public') {
          terms.push(':' + element.attributes[i].name);
          if (i !== publicAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'protected') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          terms.push(':' + element.attributes[i].name);
          if (i !== protectedAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'private') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private') {
          terms.push(':' + element.attributes[i].name);
          if (i !== privateAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'long' && visibility === 'public') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== publicAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'protected') {
      codeWriter.writeLine();
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== protectedAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'private') {
      codeWriter.writeLine();
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== privateAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    }
  };

  RubyCodeGenerator.prototype.constructMethod = function (codeWriter, element, options) {
    if (element.name.length) {
      var parameters = element.getNonReturnParameters();
      var len = parameters.length;
      var methodVisibility = this.getVisibility(element);
      var indentationSpaces = this.getIndentString(options);
      var terms = '';

      terms += indentationSpaces;
      terms += 'def ' + element.name;
      if (len !== 0) {
        terms += '(';
        for (var i = 0; i < len; i++) {
          terms += parameters[i].name;
          if (i !== len - 1) {
            terms += ', ';
          } else {
            terms += ')';
          }
        }
      }

      terms += '\n';
      terms += indentationSpaces + indentationSpaces;
      if (methodVisibility === 'public') {
        terms += '# TODO(person name): Implement this method here.\n';
      } else {
        terms += indentationSpaces;
        terms += '# TODO(person name): Implement this method here.\n';
        terms += indentationSpaces;
      }

      terms += indentationSpaces + 'end';
    }

    return terms;
  }

  RubyCodeGenerator.prototype.writeMethod = function (publicTerms, protectedTerms, privateTerms, codeWriter, element, options) {
    if (publicTerms.length) {
      codeWriter.writeLine(publicTerms);
    }

    if (this.countAttributeByVisibility('protected', element) || protectedTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('protected');
      codeWriter.indent();
      if (this.countAttributeByVisibility('protected', element)) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'protected', codeWriter, element);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'protected', codeWriter, element);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (protectedTerms.length) {
        codeWriter.writeLine(protectedTerms);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }

    if (this.countAttributeByVisibility('private', element) || privateTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('private');
      codeWriter.indent();
      if (this.countAttributeByVisibility('private', element)) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'private', codeWriter, element);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'private', codeWriter, element);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (privateTerms.length) {
        codeWriter.writeLine(privateTerms);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }
  };

  RubyCodeGenerator.prototype.countAttributeByVisibility = function (visibility, element) {
    var publicElementCount = 0;
    var protectedElementCount = 0;
    var privateElementCount = 0;
    var len = element.attributes.length;
    var elementVisibility;

    for (var i = 0; i < len; i++) {
      elementVisibility = this.getVisibility(element.attributes[i]);

      if (elementVisibility === 'public') {
        publicElementCount++;
      } else if (elementVisibility === 'protected') {
        protectedElementCount++;
      } else if (elementVisibility === 'private') {
        privateElementCount++;
      }
    }

    if (visibility === 'public') {
      return publicElementCount;
    } else if (visibility === 'protected') {
      return protectedElementCount;
    } else if (visibility === 'private') {
      return privateElementCount;
    }
  }

  RubyCodeGenerator.prototype.writeToStringMethod = function (codeWriter) {
    codeWriter.indent();
    codeWriter.writeLine('def to_s');
    codeWriter.indent();
    codeWriter.writeLine('\"Your string representation of the object will be written here.\"');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  }

  RubyCodeGenerator.prototype.writeClass = function (codeWriter, element, options) {
    var terms = [];

    terms.push('class');
    terms.push(element.name);

    var _inheritance = this.getSuperClasses(element);
    if (_inheritance.length) {
      terms.push('< ' + _inheritance[0].name);
    }

    codeWriter.writeLine(terms.join(' '));
    codeWriter.indent();

    if (options.useAttributeAccessor && this.countAttributeByVisibility('public', element)) {
      this.writeAttributeAccessor('short', 'public', codeWriter, element);
      codeWriter.writeLine();
    }

    if (options.initializeMethod) {
      this.writeConstructor(codeWriter, element, options);
      codeWriter.writeLine();
    }

    if (!options.useAttributeAccessor && this.countAttributeByVisibility('public', element)) {
      this.writeAttributeAccessor('long', 'public', codeWriter, element);
      codeWriter.writeLine();
    }

    codeWriter.outdent();

    var len = element.operations.length;
    var publicMethodLastIndex;
    var protectedMethodLastIndex;
    var privateMethodLastIndex;

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);

      if (methodVisibility === 'public') {
        publicMethodLastIndex = i;
      } else if (methodVisibility === 'protected') {
        protectedMethodLastIndex = i;
      } else if (methodVisibility === 'private') {
        privateMethodLastIndex = i;
      }
    }

    var publicTerms = '';
    var protectedTerms = '';
    var privateTerms = '';

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var methodString = this.constructMethod(codeWriter, element.operations[i], options);
      var indentationSpaces = this.getIndentString(options);

      if (methodVisibility === 'public') {
        publicTerms += methodString;
        if (i === publicMethodLastIndex) {
          publicTerms += '\n';
        } else {
          publicTerms += '\n\n';
        }
      } else if (methodVisibility === 'protected') {
        protectedTerms += methodString;
        if (i === protectedMethodLastIndex) {
          protectedTerms += '\n';
        } else {
          protectedTerms += '\n\n';
          protectedTerms += indentationSpaces;
        }
      } else if (methodVisibility === 'private') {
        privateTerms += methodString;
        if (i === privateMethodLastIndex) {
          privateTerms += '\n';
        } else {
          privateTerms += '\n\n';
          privateTerms += indentationSpaces;
        }
      }
    }

    this.writeMethod(publicTerms, protectedTerms, privateTerms, codeWriter, element, options);

    if (options.rubyToStringMethod) {
      this.writeToStringMethod(codeWriter);
    }

    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  function generate(baseModel, basePath, options) {
    var result = new $.Deferred();
    var rubyCodeGenerator = new RubyCodeGenerator(baseModel, basePath);

    return rubyCodeGenerator.generate(baseModel, basePath, options);
  }

  exports.generate = generate;
});
<|endoftext|>