<commit_before>//Part1: Asking for guess name and 'alert' a greeting
var name;

//Part2: Evaluating 3 questions
var keys = [ ['YES','Y'], ['YES', 'Y'], ['YES', 'Y'] ];
var ans = ["I was born and raised in Vietnam", "I love all kind of food.", "I have lived in San Jose and Berkeley."]
var questions = ["Was I born and raised in Vietnam?", "Do I like food?", "Have I ever lived in the Bay Area?"];
var counter = 0;
var congrats;
var thank;
var i = 0;
var answer;
var sorry;
var checking=false;
var answerArray = ["q1", "q2", "q3"];

var ask = function (){
  var name = prompt ("Please enter you name in the box below.");
  while (name.length===0){ //Make sure that name cannot be empty
    name = prompt("Your name cannot be empty. Please enter your name in the box below.");
  }

  var greeting = "Nice meeting you "+name+"! Let's play a game. Please answer 3 questions about me using yes and no only.";
  alert(greeting);
  var j = 0;
  for (i = 0; i < questions.length; i++){
    answer = prompt(questions[i]);
    while (answer.length ===0){
      answer = prompt ("Please put answer yes (y) or no (n) for the question."+questions[i]);
    }
    checking = confirm("Your answer is "+answer+". If you want to change your answer, click Cancel to go back and input your answer again.");
    while (checking===false){
      answer = prompt(questions[i]);
      checking = confirm("Your answer is "+answer+". If you want to change your answer, click Cancel to go back and input your answer again.");
    }

    answer = answer.toUpperCase();
    if (answer===keys[i][j] || answer===keys[i][j+1]){
      counter++;
      congrats = "Congratulations "+name+"! You answered "+counter+"/"+ans.length+" questions correctly!" +
              '';
      console.log("Your score is "+counter);
      var message = document.getElementById(answerArray[i]);
      message.innerHTML = congrats;
      message.className = "right";
      //alert(congrats);
    }
    else{
      sorry = "Sorry "+name+". "+ans[i];
      console.log("Your score is "+counter);
      var message = document.getElementById(answerArray[i]);
      message.innerHTML = sorry;
      message.className = "wrong";
      //alert(sorry);
    }
  }

  thank = "Thank you "+name+" for playing.";
  alert(thank);
}
<commit_msg>fix image link<commit_after>//Part1: Asking for guess name and 'alert' a greeting
var name;

//Part2: Evaluating 3 questions
var keys = [ ['YES','Y'], ['YES', 'Y'], ['YES', 'Y'] ];
var ans = ["I was born and raised in Vietnam", "I love all kind of food.", "I have lived in San Jose and Berkeley."]
var questions = ["Was I born and raised in Vietnam?", "Do I like food?", "Have I ever lived in the Bay Area?"];
var counter = 0;
var congrats;
var thank;
var i = 0;
var answer;
var sorry;
var checking=false;
var answerArray = ["q1", "q2", "q3"];

var ask = function (){
  var name = prompt ("Please enter you name in the box below.");
  while (name.length===0){ //Make sure that name cannot be empty
    name = prompt("Your name cannot be empty. Please enter your name in the box below.");
  }

  var greeting = "Nice meeting you "+name+"! Let's play a game. Please answer 3 questions about me using yes and no only.";
  alert(greeting);
  var j = 0;
  for (i = 0; i < questions.length; i++){
    answer = prompt(questions[i]);
    while (answer.length ===0){
      answer = prompt ("Please put answer yes (y) or no (n) for the question."+questions[i]);
    }
    checking = confirm("Your answer is "+answer+". If you want to change your answer, click Cancel to go back and input your answer again.");
    while (checking===false){
      answer = prompt(questions[i]);
      checking = confirm("Your answer is "+answer+". If you want to change your answer, click Cancel to go back and input your answer again.");
    }

    answer = answer.toUpperCase();
    if (answer===keys[i][j] || answer===keys[i][j+1]){
      counter++;
      congrats = "Congratulations "+name+"! You answered "+counter+"/"+ans.length+" questions correctly!" +
              '';
      console.log("Your score is "+counter);
      var message = document.getElementById(answerArray[i]);
      message.innerHTML = congrats;
      message.className = "right";
      //alert(congrats);
    }
    else{
      sorry = "Sorry "+name+". "+ans[i];
      console.log("Your score is "+counter);
      var message = document.getElementById(answerArray[i]);
      message.innerHTML = sorry;
      message.className = "wrong";
      //alert(sorry);
    }
  }

  thank = "Thank you "+name+" for playing.";
  alert(thank);
}
<|endoftext|>


<commit_before>
(function (exports) {
    var derive = Object.create,
        plainSpec = {
            enumerable: true,
            writable: true,
            configurable: true
        },
        method, privateMethod
    ;

    //-----------------------------------------------------------------------
    // Utilities
    //-----------------------------------------------------------------------
    function slice (list, start, end) {
        return Array.prototype.slice.call(list, start, end);
    }

    function merge () {
        var args = slice(arguments);

        return args.reduce(function (base, obj) {
            return Object.keys(obj).reduce(function (b, k) {
                b[k] = obj[k];
                return b;
            }, base);
        }, args.shift());
    }

    function property (val, spec) {
        return merge({}, plainSpec, {value: val}, spec || {});
    }
    method = property;

    function privateProperty (val, spec) {
        return merge(property(val, spec), {enumerable: false});
    }
    privateMethod = privateProperty;

    function numericSort (a, b) {
        return a - b;
    }

    function rollDie (sides) {
        return Math.floor(Math.random() * sides) + 1;
    }

    function reduceSum (t, d) {
        return (t + d);
    }
    //-----------------------------------------------------------------------
    // Dice
    //-----------------------------------------------------------------------
    function Dice (num, sides, behaviors) {
        if (arguments.length === 1) {
            sides = num;
            num = 1;
        }
        this.count = num;
        this.sides = sides;

        Object.defineProperty(this, "_behaviors", privateProperty([]));

        if (behaviors) {
            this.addBehavior.apply(this, behaviors);
        }
    }

    Dice.prototype = derive(Object.prototype, {
        /**
         * The number of dice
         *
         * @property count
         * @type {number}
         * @default 1
         */
        count:  property(1),
        /**
         * The number of sides (i.e: type)
         *
         * @property sides
         * @type {number}
         * @default 0
         */
        sides:  property(0),
        /**
         * @property rolled
         * @type {boolean}
         * @default false
         */
        rolled: property(false),
        /**
         * Total of the rolled dice
         *
         * @property total
         * @type {number}
         * @default 0
         */
        total: property(0),
        /**
         * Roll the dice and return the total
         *
         * @method roll
         * @returns {number}
         */
        roll: method(function () {
            if (this.rolled) {
                return this.total;
            }
            this.total = this._roll();
            this.rolled = true;
            this._applyBehaviors();
            return this.total;
        }),
        /**
         * Reset the dice and roll again
         *
         * @method reroll
         * @returns {number}
         */
        reroll: method(function () {
            this.reset();
            return this.roll();
        }),
        /**
         * Reset the dice
         *
         * @method reset
         * @returns {Dice} the instance
         */
        reset: method(function () {
            delete this.total;
            delete this.results;
            delete this.rolled;
            this._applyBehaviors();
            return this;
        }),
        /**
         * Add a behavior function to the results set
         *
         * @method addBehavior
         * @param rest {function} one or more functions
         * @returns {Dice} the instance
         */
        addBehavior: method(function (/*rest*/) {
            slice(arguments).forEach(function (fn) {
                this.push(fn);
            }, this._behaviors);
            return this;
        }),
        /**
         * @method toString
         * @override Object#toString
         * @returns {string}
         */
        toString: method(function () {
            var count = this.count,
                total = this.total
            ;

            return (count > 1 ? count : "") + "d" + this.sides +
                (this.rolled ? " [" + this.results.join(", ") + "] = " + total : "");
        }),
        /**
         * @method _roll
         * @private
         * @returns {number}
         */
        _roll: privateMethod(function () {
            var i = 0,
                len = this.count,
                sides = this.sides,
                total = 0,
                results = (this.results = []),
                result
            ;

            for (i; i < len; i++) {
                result = rollDie(sides);
                results.push(result);
                total += result;
            }

            return total;
        }),
        /**
         * Apply any behaviors attached to this dice object
         *
         * @method _applyBehaviors
         * @private
         * @returns {Dice} the instance
         */
        _applyBehaviors: privateMethod(function () {
            this._behaviors.forEach(this._applyBehavior, this);
            return this;
        }),
        /**
         * Apply the passed behavior to this object
         *
         * @method _applyBehavior
         * @private
         * @param {function}
         */
        _applyBehavior: privateMethod(function (fn) {
            fn.call(this);
        })
    });

    exports.Dice = Dice;

    //-----------------------------------------------------------------------
    // Behaviors
    //-----------------------------------------------------------------------
    exports.behaviors = {
        /**
         * Apply a modifier to the total
         *
         * @param amt {number}
         * @mutates Dice#total
         */
        resultModifier: function (amt) {
            return function () {
                if (!this.rolled) {
                    return;
                }
                this.total += amt;
            };
        },
        /**
         * Apply a modifier to every die
         *
         * @param amt {number}
         * @mutates Dice#total
         * @mutates Dice#results
         */
        dieModifier: function (amt) {
            return function () {
                if (!this.rolled) {
                    return;
                }

                this.total += amt * this.results.length;
            };
        },
        /**
         * Remove *amt* lowest dice from the results.
         *
         * @param amt {number} number of low dice to discard
         * @mutates Dice#toal
         * @mutates Dice#toString
         * @property lowResults {array[number]}
         */
        removeLowest: function (amt) {
            return function () {
                var dice;

                if (!this.rolled) {
                    delete this.lowResults;
                    delete this.toString;
                }
                else {
                    this.lowResults = this.results.sort(numericSort).reverse().
                            splice(this.count - amt);

                    this.total = this.results.reduce(reduceSum, 0);

                    this.toString = function () {
                        return Dice.prototype.toString.call(this) +
                            " (low: [" + this.lowResults.join(", ") + "])";
                    };
                }
            };
        },
        /**
         * Count the number of dice above a certain threshold
         *
         * @param amt {number} number or greater to count as a success
         * @mutates Dice#total
         * @mutates Dice#toString
         */
        successDice: function (min) {
            return function () {
                if (!this.rolled) {
                    delete this.toString;
                }
                else {
                    this.total = this.results.filter(function (d) {
                        return d >= min;
                    }).reduce(function (t, d) {
                        return ++t;
                    }, 0);
                    this.toString = function () {
                        return Dice.prototype.toString.call(this) + " successes";
                    };
                }
            };
        },
        /**
         * Determine the amount of Stun and Body
         *
         * @mutates Dice#toString
         * @property body {number} number of body (die result: 1 = 0, 2-5 = 1, 6 = 2)
         * @property stun {number} total of dice
         */
        heroDice: function () {
            return function () {
                if (!this.rolled) {
                    delete this.body;
                    delete this.stun;
                    delete this.toString;
                }
                else {
                    this.body = this.results.reduce(function (total, d) {
                        switch (d) {
                            case 1:
                                break;
                            case 6:
                                total += 2;
                                break;
                            default:
                                total += 1;
                        }
                        return total;
                    }, 0);
                    this.stun = this.total;
                    this.toString = function () {
                        return Dice.prototype.toString.call(this) +
                            " stun, " + this.body + " body";
                    };
                }
            };
        },
        /**
         * Specify a number of dice that are *wild*.  If these dice roll the
         * maximum amount, roll another die and add that to the total.  The
         * wild di(c)e continue to add as long as they roll the maximum.
         *
         * @param amt {number}
         * @property wildDice {array[number]} results of the wild dice
         * @property complications {boolean} if the wild die comes up a 1
         * @mutates Dice#total
         */
        wildDice: function (amt) {
            return function () {
                var dicesWild;

                if (!this.rolled) {
                    delete this.wildDice;
                    delete this.complication;
                    delete this.toString;
                }
                else {
                    dicesWild = this.results.slice().reverse().
                        slice(0, amt || this.results.length);

                    dicesWild.forEach(function (die) {
                        var sides = this.sides,
                            result
                        ;

                        if (die === sides) {
                            do {
                                result = rollDie(sides);
                                this.results.push(result);
                            } while (result === sides);
                        }
                        else if (die === 1) {
                            if (!this.complications) {
                                this.complications = 0;
                            }
                            this.complications++;
                        }
                    }, this);

                    this.total = this.results.reduce(reduceSum, 0);

                    this.toString = function () {
                        var fails = this.complications;
                        return Dice.prototype.toString.call(this) +
                            (fails ? Array(fails + 1).join("!") : "");
                    };
                }
            };
        }
    };

}((typeof module !== "undefined" && module.exports) || this));<commit_msg>Rework how successDice work.<commit_after>
(function (exports) {
    var derive = Object.create,
        plainSpec = {
            enumerable: true,
            writable: true,
            configurable: true
        },
        method, privateMethod
    ;

    //-----------------------------------------------------------------------
    // Utilities
    //-----------------------------------------------------------------------
    function slice (list, start, end) {
        return Array.prototype.slice.call(list, start, end);
    }

    function merge () {
        var args = slice(arguments);

        return args.reduce(function (base, obj) {
            return Object.keys(obj).reduce(function (b, k) {
                b[k] = obj[k];
                return b;
            }, base);
        }, args.shift());
    }

    function property (val, spec) {
        return merge({}, plainSpec, {value: val}, spec || {});
    }
    method = property;

    function privateProperty (val, spec) {
        return merge(property(val, spec), {enumerable: false});
    }
    privateMethod = privateProperty;

    function numericSort (a, b) {
        return a - b;
    }

    function rollDie (sides) {
        return Math.floor(Math.random() * sides) + 1;
    }

    function reduceSum (t, d) {
        return (t + d);
    }
    //-----------------------------------------------------------------------
    // Dice
    //-----------------------------------------------------------------------
    function Dice (num, sides, behaviors) {
        if (arguments.length === 1) {
            sides = num;
            num = 1;
        }
        this.count = num;
        this.sides = sides;

        Object.defineProperty(this, "_behaviors", privateProperty([]));

        if (behaviors) {
            this.addBehavior.apply(this, behaviors);
        }
    }

    Dice.prototype = derive(Object.prototype, {
        /**
         * The number of dice
         *
         * @property count
         * @type {number}
         * @default 1
         */
        count:  property(1),
        /**
         * The number of sides (i.e: type)
         *
         * @property sides
         * @type {number}
         * @default 0
         */
        sides:  property(0),
        /**
         * @property rolled
         * @type {boolean}
         * @default false
         */
        rolled: property(false),
        /**
         * Total of the rolled dice
         *
         * @property total
         * @type {number}
         * @default 0
         */
        total: property(0),
        /**
         * Roll the dice and return the total
         *
         * @method roll
         * @returns {number}
         */
        roll: method(function () {
            if (this.rolled) {
                return this.total;
            }
            this.total = this._roll();
            this.rolled = true;
            this._applyBehaviors();
            return this.total;
        }),
        /**
         * Reset the dice and roll again
         *
         * @method reroll
         * @returns {number}
         */
        reroll: method(function () {
            this.reset();
            return this.roll();
        }),
        /**
         * Reset the dice
         *
         * @method reset
         * @returns {Dice} the instance
         */
        reset: method(function () {
            delete this.total;
            delete this.results;
            delete this.rolled;
            this._applyBehaviors();
            return this;
        }),
        /**
         * Add a behavior function to the results set
         *
         * @method addBehavior
         * @param rest {function} one or more functions
         * @returns {Dice} the instance
         */
        addBehavior: method(function (/*rest*/) {
            slice(arguments).forEach(function (fn) {
                this.push(fn);
            }, this._behaviors);
            return this;
        }),
        /**
         * @method toString
         * @override Object#toString
         * @returns {string}
         */
        toString: method(function () {
            var count = this.count,
                total = this.total
            ;

            return (count > 1 ? count : "") + "d" + this.sides +
                (this.rolled ? " [" + this.results.join(", ") + "] = " + total : "");
        }),
        /**
         * @method _roll
         * @private
         * @returns {number}
         */
        _roll: privateMethod(function () {
            var i = 0,
                len = this.count,
                sides = this.sides,
                total = 0,
                results = (this.results = []),
                result
            ;

            for (i; i < len; i++) {
                result = rollDie(sides);
                results.push(result);
                total += result;
            }

            return total;
        }),
        /**
         * Apply any behaviors attached to this dice object
         *
         * @method _applyBehaviors
         * @private
         * @returns {Dice} the instance
         */
        _applyBehaviors: privateMethod(function () {
            this._behaviors.forEach(this._applyBehavior, this);
            return this;
        }),
        /**
         * Apply the passed behavior to this object
         *
         * @method _applyBehavior
         * @private
         * @param {function}
         */
        _applyBehavior: privateMethod(function (fn) {
            fn.call(this);
        })
    });

    exports.Dice = Dice;

    //-----------------------------------------------------------------------
    // Behaviors
    //-----------------------------------------------------------------------
    exports.behaviors = {
        /**
         * Apply a modifier to the total
         *
         * @param amt {number}
         * @mutates Dice#total
         */
        resultModifier: function (amt) {
            return function () {
                if (!this.rolled) {
                    return;
                }
                this.total += amt;
            };
        },
        /**
         * Apply a modifier to every die
         *
         * @param amt {number}
         * @mutates Dice#total
         * @mutates Dice#results
         */
        dieModifier: function (amt) {
            return function () {
                if (!this.rolled) {
                    return;
                }

                this.total += amt * this.results.length;
            };
        },
        /**
         * Remove *amt* lowest dice from the results.
         *
         * @param amt {number} number of low dice to discard
         * @mutates Dice#toal
         * @mutates Dice#toString
         * @property Dice#lowResults {array[number]}
         */
        removeLowest: function (amt) {
            return function () {
                var dice;

                if (!this.rolled) {
                    delete this.lowResults;
                    delete this.toString;
                }
                else {
                    this.lowResults = this.results.sort(numericSort).reverse().
                            splice(this.count - amt);

                    this.total = this.results.reduce(reduceSum, 0);

                    this.toString = function () {
                        return Dice.prototype.toString.call(this) +
                            " (low: [" + this.lowResults.join(", ") + "])";
                    };
                }
            };
        },
        /**
         * Count the number of dice above a certain threshold
         *
         * @param amt {number} number or greater to count as a success
         * @mutates Dice#total
         * @mutates Dice#toString
         * @property Dice#successes {number}
         * @property Dice#failures {number}
         * @property Dice#fumbled {boolean}
         */
        successDice: function (min) {
            return function () {
                var total, failures, count, results, i, len, d;

                if (!this.rolled) {
                    delete this.successes;
                    delete this.failures;
                    delete this.toString;
                }
                else {
                    total    = 0;
                    failures = 0;
                    results  = this.results;
                    len      = results.length;
                    count    = this.count;

                    for (i = 0; i < len; i++) {
                        d = results[i];
                        if (d >= min) {
                            total++;
                        }
                        else if (i < count && d === 1) {
                            failures++;
                        }
                    }

                    this.successes = total;
                    this.failures = failures;
                    this.total = Math.max(total - failures, 0);
                    this.fumbled = failures > total;

                    this.toString = function () {
                        return (this.count ? this.count : "") + "d" + this.sides +
                            " [" + this.results.join(", ") + "] = " +
                            this.total + " successes" +
                            (this.fumbled ? "!" : "");
                    };
                }
            };
        },
        /**
         * Determine the amount of Stun and Body
         *
         * @mutates Dice#toString
         * @property Dice#body {number} number of body (die result: 1 = 0, 2-5 = 1, 6 = 2)
         * @property Dice#stun {number} total of dice
         */
        heroDice: function () {
            return function () {
                if (!this.rolled) {
                    delete this.body;
                    delete this.stun;
                    delete this.toString;
                }
                else {
                    this.body = this.results.reduce(function (total, d) {
                        switch (d) {
                            case 1:
                                break;
                            case 6:
                                total += 2;
                                break;
                            default:
                                total += 1;
                        }
                        return total;
                    }, 0);
                    this.stun = this.total;
                    this.toString = function () {
                        return Dice.prototype.toString.call(this) +
                            " stun, " + this.body + " body";
                    };
                }
            };
        },
        /**
         * Specify a number of dice that are *wild*.  If these dice roll the
         * maximum amount, roll another die and add that to the total.  The
         * wild di(c)e continue to add as long as they roll the maximum.
         *
         * @param amt {number}
         * @property Dice#wildDice {array[number]} results of the wild dice
         * @property Dice#complications {boolean} if the wild die comes up a 1
         * @mutates Dice#total
         */
        wildDice: function (amt) {
            return function () {
                var dicesWild;

                if (!this.rolled) {
                    delete this.wildDice;
                    delete this.complication;
                    delete this.toString;
                }
                else {
                    dicesWild = this.results.slice().reverse().
                        slice(0, amt || this.results.length);

                    dicesWild.forEach(function (die) {
                        var sides = this.sides,
                            result
                        ;

                        if (die === sides) {
                            do {
                                result = rollDie(sides);
                                this.results.push(result);
                            } while (result === sides);
                        }
                        else if (die === 1) {
                            if (!this.complications) {
                                this.complications = 0;
                            }
                            this.complications++;
                        }
                    }, this);

                    this.total = this.results.reduce(reduceSum, 0);

                    this.toString = function () {
                        var fails = this.complications;
                        return Dice.prototype.toString.call(this) +
                            (fails ? Array(fails + 1).join("!") : "");
                    };
                }
            };
        }
    };

}((typeof module !== "undefined" && module.exports) || this));<|endoftext|>


<commit_before>'use strict';

var Lodash = require('lodash');
var Path = require('path');

var BuildHelpers = require('./build-helpers');
var EsprimaHelpers = require('./esprima-helpers');
var PathingHelpers = require('./storage-helpers/pathing');

var CLOSE_ARRAY = ']';
var COMMA = ',';
var NEWLINE = '\n';
var NEWLINE_REGEXP = /\n/g;
var OPEN_ARRAY = '[';
var QUOTE = '\'';
var TAB = '    '; // 4 spaces!

function indent(str) {
    return (TAB + str).replace(NEWLINE_REGEXP, NEWLINE + TAB);
}

function copyright() {
    var startYear = '2015';
    var currYear = new Date().getFullYear().toString();
    var yearStr = startYear;
    if (currYear !== startYear) {
        yearStr += ('-' + currYear);
    }
    return '// Copyright ' + yearStr + ' (c) Famous Industries, Inc.';
}

function getFlatIncludes(flatIncludes, parcelHash) {
    if (parcelHash.includes) {
        flatIncludes = flatIncludes.concat(parcelHash.includes);
    }
    if (parcelHash.dependencies) {
        for (var dependencyName in parcelHash.dependencies) {
            getFlatIncludes(flatIncludes, parcelHash.dependencies[dependencyName]);
        }
    }
    return Lodash.uniq(flatIncludes);
}

function buildIncludesPrefix(info) {
    var parcelHash = info.parcelHash;
    var flatIncludes = getFlatIncludes([], parcelHash);
    return 'BEST.includes("' + info.name + '", "' + info.versionRef + '", ' + JSON.stringify(flatIncludes) + ',function(){';
}

function getFlatRegistrations(flatRegistrations, alreadyRegistered, parcelHash) {
    if (parcelHash.entrypoint) {
        flatRegistrations.unshift({
            name: parcelHash.name,
            version: parcelHash.version,
            entrypoint: parcelHash.entrypoint
        });
    }
    if (parcelHash.dependencies) {
        for (var dependencyName in parcelHash.dependencies) {
            getFlatRegistrations(flatRegistrations, alreadyRegistered, parcelHash.dependencies[dependencyName]);
        }
    }
    return flatRegistrations;
}

function buildRegistrationBlocks(parcelHash) {
    var flatRegistrations = getFlatRegistrations([], {}, parcelHash);
    // Remove duplicates from the registration blocks we got.
    // No point in registering them multiple times!
    var uniqRegistrations = [];
    var regTuples = {};
    for (var i = 0; i < flatRegistrations.length; i++) {
        var flatReg = flatRegistrations[i];
        var regKey = flatReg.name + '-' + flatReg.version;
        if (!regTuples[regKey]) {
            regTuples[regKey] = true;
            uniqRegistrations.push(flatReg);
        }
    }
    var flatEntrypoints = Lodash.map(uniqRegistrations, function(regObj) {
        return regObj.entrypoint;
    });
    return flatEntrypoints.join(NEWLINE);
}

function buildIncludesSuffix() {
    return '});';
}

function buildBundleString(info) {
    return [
        copyright(),
        '\'use strict\';',
        buildIncludesPrefix(info),
        indent(buildRegistrationBlocks(info.parcelHash)),
        buildIncludesSuffix(),
        copyright()
    ].join(NEWLINE);
}

function normalizeDependenciesFound(dependenciesFound) {
    var normalized = {};
    for (var depName in dependenciesFound) {
        var depJSON = dependenciesFound[depName];
        if (typeof depJSON === 'string') {
            normalized[depName] = JSON.parse(depJSON);
        }
        else {
            normalized[depName] = depJSON;
        }
    }
    return normalized;
}

function buildEntrypointString(info) {
    return EsprimaHelpers.generate(info.entrypointAST);
}

function buildParcelHash(info) {
    return {
        name: info.name,
        version: info.versionRef,
        timestamp: Date.now(),
        includes: BuildHelpers.buildIncludesArray(info),
        dependencies: normalizeDependenciesFound(info.dependenciesFound),
        entrypoint: buildEntrypointString(info)
    };
}

function buildBundle(info, cb) {
    info.parcelHash = buildParcelHash(info);
    info.bundleString = buildBundleString(info);
    cb(null, info);
}

module.exports = buildBundle;
<commit_msg>Ensure a version ref is included in the bundle no matter what<commit_after>'use strict';

var Lodash = require('lodash');
var Path = require('path');

var BuildHelpers = require('./build-helpers');
var EsprimaHelpers = require('./esprima-helpers');
var PathingHelpers = require('./storage-helpers/pathing');

var CLOSE_ARRAY = ']';
var COMMA = ',';
var NEWLINE = '\n';
var NEWLINE_REGEXP = /\n/g;
var OPEN_ARRAY = '[';
var QUOTE = '\'';
var TAB = '    '; // 4 spaces!

function indent(str) {
    return (TAB + str).replace(NEWLINE_REGEXP, NEWLINE + TAB);
}

function copyright() {
    var startYear = '2015';
    var currYear = new Date().getFullYear().toString();
    var yearStr = startYear;
    if (currYear !== startYear) {
        yearStr += ('-' + currYear);
    }
    return '// Copyright ' + yearStr + ' (c) Famous Industries, Inc.';
}

function getFlatIncludes(flatIncludes, parcelHash) {
    if (parcelHash.includes) {
        flatIncludes = flatIncludes.concat(parcelHash.includes);
    }
    if (parcelHash.dependencies) {
        for (var dependencyName in parcelHash.dependencies) {
            getFlatIncludes(flatIncludes, parcelHash.dependencies[dependencyName]);
        }
    }
    return Lodash.uniq(flatIncludes);
}

function buildIncludesPrefix(info) {
    var parcelHash = info.parcelHash;
    var flatIncludes = getFlatIncludes([], parcelHash);
    return 'BEST.includes("' + info.name + '","' + (info.explicitVersion || info.versionRef) + '",' + JSON.stringify(flatIncludes) + ',function(){';
}

function getFlatRegistrations(flatRegistrations, alreadyRegistered, parcelHash) {
    if (parcelHash.entrypoint) {
        flatRegistrations.unshift({
            name: parcelHash.name,
            version: parcelHash.version,
            entrypoint: parcelHash.entrypoint
        });
    }
    if (parcelHash.dependencies) {
        for (var dependencyName in parcelHash.dependencies) {
            getFlatRegistrations(flatRegistrations, alreadyRegistered, parcelHash.dependencies[dependencyName]);
        }
    }
    return flatRegistrations;
}

function buildRegistrationBlocks(parcelHash) {
    var flatRegistrations = getFlatRegistrations([], {}, parcelHash);
    // Remove duplicates from the registration blocks we got.
    // No point in registering them multiple times!
    var uniqRegistrations = [];
    var regTuples = {};
    for (var i = 0; i < flatRegistrations.length; i++) {
        var flatReg = flatRegistrations[i];
        var regKey = flatReg.name + '-' + flatReg.version;
        if (!regTuples[regKey]) {
            regTuples[regKey] = true;
            uniqRegistrations.push(flatReg);
        }
    }
    var flatEntrypoints = Lodash.map(uniqRegistrations, function(regObj) {
        return regObj.entrypoint;
    });
    return flatEntrypoints.join(NEWLINE);
}

function buildIncludesSuffix() {
    return '});';
}

function buildBundleString(info) {
    return [
        copyright(),
        '\'use strict\';',
        buildIncludesPrefix(info),
        indent(buildRegistrationBlocks(info.parcelHash)),
        buildIncludesSuffix(),
        copyright()
    ].join(NEWLINE);
}

function normalizeDependenciesFound(dependenciesFound) {
    var normalized = {};
    for (var depName in dependenciesFound) {
        var depJSON = dependenciesFound[depName];
        if (typeof depJSON === 'string') {
            normalized[depName] = JSON.parse(depJSON);
        }
        else {
            normalized[depName] = depJSON;
        }
    }
    return normalized;
}

function buildEntrypointString(info) {
    try {
        var generated = EsprimaHelpers.generate(info.entrypointAST);
        return generated;
    }
    catch (entrypointBuildErr) {
        // Dear developer:
        // To get insight into what may have failed, try uncommenting this
        // block and inspecting what all of the nodes in the AST are.
        // EsprimaHelpers.traverse(info.entrypointAST, function(node) {
        //     console.log(node);
        // });
        console.error('Esprima says:', entrypointBuildErr);
        console.error('Failed to build `' + info.name + '` (' + info.versionRef + ') entrypoint; this is most likely a problem with the framework build tool');
        return 'console.error("The build of `' + info.name + '` (' + info.versionRef + ') failed; this is most likely a problem with the framework build tool");';
    }
}

function buildParcelHash(info) {
    var includes = BuildHelpers.buildIncludesArray(info);
    return {
        name: info.name,
        version: info.explicitVersion || info.versionRef,
        timestamp: Date.now(),
        includes: includes,
        dependencies: normalizeDependenciesFound(info.dependenciesFound),
        entrypoint: buildEntrypointString(info)
    };
}

function buildBundle(info, cb) {
    // When building bundles in memory only (no persistence, say, when testing),
    // we might not have either a version ref or an explicit version set; in that
    // case, fall back to the dependency version so that the bundles don't have
    // a bunch of "undefined" versions listed
    if (!info.versionRef && !info.explicitVersion) {
        info.versionRef = this.options.defaultDependencyVersion;
    }

    info.parcelHash = buildParcelHash.call(this, info);
    info.bundleString = buildBundleString.call(this, info);
    cb(null, info);
}

module.exports = buildBundle;
<|endoftext|>


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

function readdirImpl(dir, iterator, finished, recurse) {
  iterator = iterator || function() {};
  finished = finished || function() {};

  fs.readdirRecursive(dir, function(err, files) {
    if (err) return finished(err); // couldn't read dir

    var fileCount = files.length; // grab the file count
    if (!fileCount) return finished(); // no files, return immediately

    files.forEach(function(file) { // iterate files
      var filePath = path.join(dir, file);
      fs.stat(filePath, function(err, stat) { // stat the file
        var doneCallback = function(err) {
          // when a done callback is invoked, decrement the file counter
          if (--fileCount == 0) finished(); // all of our direct files have been processed
        }

        // let the caller know an error occurs (expect them to still invoke cb)
        if (err) return iterator(err, null, false, doneCallback);

        if (stat.isDirectory()) {

          iterator(null, filePath, true, function() {
            if (recurse)
              exports.readdirRecursive(filePath, iterator, doneCallback, recurse); // recurse on callback
            else
              doneCallback();
          });
        }
        else
          iterator(null, filePath, false, doneCallback);
      });
    });
  });
}

/**
 * done.readdir(dir, iterator(err, path, isDir, cb){}, finished(err){})
 *
 * Reads a directory, invoking iterator() for each item discovered.
 * The iterator must call cb() after processing each item. The
 * master callback function finished() will be invoked after all items
 * have been discovered and procesed by iterator.
 */
exports.readdir = function(dir, iterator, finished) {
  readdirImpl(dir, iterator, finished, false);
}

/**
 * done.readdirRecursive(dir, iterator(err, path, isDir, cb){}, finished(err){})
 *
 * Recursively reads a directory, invoking iterator() for each item
 * discovered. The iterator must call cb() after processing each item. The
 * master callback function finished() will be invoked after all items
 * have been discovered and procesed by iterator.
 */
exports.readdirRecursive = function(dir, iterator, finished) {
  readdirImpl(dir, iterator, finished, true);
}

/**
 * done.mkdir(dir, mode, iterator(err, path, cb){}, finished(err){})
 *
 * Recursively creates a directory with the provided mode. The master
 * callback function finished() will be invoked after the entire
 * path has been created.
 */
exports.mkdir = function(dir, mode, iterator, finished) {
  dir = path.resolve(dir);
  mode = mode || 0777;
  iterator = iterator || function() {}
  finished = finished || function() {}

  fs.mkdir(dir, mode, function(err) {
    if (!err)
      return iterator(null, dir, finished);

    var parent = path.dirname(dir);
    var done = function(err) {
      // if this gets called, then we were trying to create the parent dir
      if (err) return finished(err);
      exports.mkdir(dir, mode, iterator, finished);
    }

    if (err) {
      if (err.code == "ENOENT") // parent dir doesn't exist, create it
        exports.mkdir(parent, mode, iterator, done);
      else if (err.code == "EEXIST") // dir already exists, ok
        finished();
      else // unknown error, abort
        finished(err);
    }
  });
}
<commit_msg>fixed typo in fs function call. fixed default iterator.<commit_after>var fs = require('fs'),
    path = require('path');

function readdirImpl(dir, iterator, finished, recurse) {
  iterator = iterator || function(err, path, isDir, cb) {cb();};
  finished = finished || function() {};

  fs.readdir(dir, function(err, files) {
    if (err) return finished(err); // couldn't read dir

    var fileCount = files.length; // grab the file count
    if (!fileCount) return finished(); // no files, return immediately

    files.forEach(function(file) { // iterate files
      var filePath = path.join(dir, file);
      fs.stat(filePath, function(err, stat) { // stat the file
        var doneCallback = function(err) {
          // when a done callback is invoked, decrement the file counter
          if (--fileCount == 0) finished(); // all of our direct files have been processed
        }

        // let the caller know an error occurs (expect them to still invoke cb)
        if (err) return iterator(err, null, false, doneCallback);

        if (stat.isDirectory()) {

          iterator(null, filePath, true, function() {
            if (recurse)
              exports.readdirRecursive(filePath, iterator, doneCallback, recurse); // recurse on callback
            else
              doneCallback();
          });
        }
        else
          iterator(null, filePath, false, doneCallback);
      });
    });
  });
}

/**
 * done.readdir(dir, iterator(err, path, isDir, cb){}, finished(err){})
 *
 * Reads a directory, invoking iterator() for each item discovered.
 * The iterator must call cb() after processing each item. The
 * master callback function finished() will be invoked after all items
 * have been discovered and procesed by iterator.
 */
exports.readdir = function(dir, iterator, finished) {
  readdirImpl(dir, iterator, finished, false);
}

/**
 * done.readdirRecursive(dir, iterator(err, path, isDir, cb){}, finished(err){})
 *
 * Recursively reads a directory, invoking iterator() for each item
 * discovered. The iterator must call cb() after processing each item. The
 * master callback function finished() will be invoked after all items
 * have been discovered and procesed by iterator.
 */
exports.readdirRecursive = function(dir, iterator, finished) {
  readdirImpl(dir, iterator, finished, true);
}

/**
 * done.mkdir(dir, mode, iterator(err, path, cb){}, finished(err){})
 *
 * Recursively creates a directory with the provided mode. The master
 * callback function finished() will be invoked after the entire
 * path has been created.
 */
exports.mkdir = function(dir, mode, iterator, finished) {
  dir = path.resolve(dir);
  mode = mode || 0777;
  iterator = iterator || function() {}
  finished = finished || function() {}

  fs.mkdir(dir, mode, function(err) {
    if (!err)
      return iterator(null, dir, finished);

    var parent = path.dirname(dir);
    var done = function(err) {
      // if this gets called, then we were trying to create the parent dir
      if (err) return finished(err);
      exports.mkdir(dir, mode, iterator, finished);
    }

    if (err) {
      if (err.code == "ENOENT") // parent dir doesn't exist, create it
        exports.mkdir(parent, mode, iterator, done);
      else if (err.code == "EEXIST") // dir already exists, ok
        finished();
      else // unknown error, abort
        finished(err);
    }
  });
}
<|endoftext|>


<commit_before>var Login = $.import("de.linuxdozent.gittest.test.lib", "Login");
var OData = $.import("de.linuxdozent.gittest.test.lib", "OData");

var loginResult;
var header;
var discountCodeCreate = {
    "ID": "1",
    "UserName": "BSCUSTOMER",
    "DiscountValue": 10,
    "SHA256HASH": "",
    "Redeemed": "N"
};
var discountCodeService = "/de/linuxdozent/gittest/odata/service.xsodata/DiscountCode";

describe("Admin actions", function() {

    it("should login BSADMIN and get csrfToken", function() {
        loginResult = Login.getCSRFtokenAndLogin("BSADMIN", Login.newpwd);
        header = OData.prepareRequestHeader(loginResult.csrf);
    });

    it("should create discount code for BSCUSTOMER", function() {
        var response = jasmine.callHTTPService(discountCodeService, $.net.http.POST, JSON.stringify(discountCodeCreate), header, loginResult.cookies);
        for (var i = 0; i < response.headers.length; ++i) {
            jasmine.log(response.headers[i].name + '": "' + response.headers[i].value);
        }
		jasmine.log(response.body.asString());
        expect(response.status).toBe($.net.http.CREATED);
    });

    it("should create discount code for other user", function() {
        // Read which additional customer exist
        var service = encodeURI("/de/linuxdozent/gittest/odata/service.xsodata/Customer?$filter=UserName ne '" + discountCodeCreate.UserName + "'");
        var response = jasmine.callHTTPService(service, $.net.http.GET, undefined, header, loginResult.cookies);
        expect(response.status).toBe($.net.http.OK);
		var responseBody = OData.getResponseBody(response);
		if (responseBody.d.results.length > 0) {
            discountCodeCreate.ID = "3";
            discountCodeCreate.UserName = responseBody.d.results[0].UserName;
            response = jasmine.callHTTPService(discountCodeService, $.net.http.POST, JSON.stringify(discountCodeCreate), header, loginResult.cookies);
            expect(response.status).toBe($.net.http.CREATED);
		}
    });

    it("should get a list of discounts but not the code", function() {
        var DiscountCodeURL = encodeURI( discountCodeService + "?$filter=UserName eq '" + discountCodeCreate.UserName + "'" );
        var response = jasmine.callHTTPService(DiscountCodeURL, $.net.http.GET, undefined, header, loginResult.cookies);
        expect(response.status).toBe($.net.http.OK);
		var responseBody = OData.getResponseBody(response);
        expect(responseBody.d.results[0].UserName).toBe(discountCodeCreate.UserName);
    });

    it("should logout BSADMIN", function() {
        Login.logout(loginResult.csrf, loginResult.cookies);
        Login.checkSession();
    });
});<commit_msg>Remove SHA256HASH from create<commit_after>var Login = $.import("de.linuxdozent.gittest.test.lib", "Login");
var OData = $.import("de.linuxdozent.gittest.test.lib", "OData");

var loginResult;
var header;
var discountCodeCreate = {
    "ID": "1",
    "UserName": "BSCUSTOMER",
    "DiscountValue": 10,
    "Redeemed": "N"
};
var discountCodeService = "/de/linuxdozent/gittest/odata/service.xsodata/DiscountCode";

describe("Admin actions", function() {

    it("should login BSADMIN and get csrfToken", function() {
        loginResult = Login.getCSRFtokenAndLogin("BSADMIN", Login.newpwd);
        header = OData.prepareRequestHeader(loginResult.csrf);
    });

    it("should create discount code for BSCUSTOMER", function() {
        var response = jasmine.callHTTPService(discountCodeService, $.net.http.POST, JSON.stringify(discountCodeCreate), header, loginResult.cookies);
        for (var i = 0; i < response.headers.length; ++i) {
            jasmine.log(response.headers[i].name + '": "' + response.headers[i].value);
        }
		jasmine.log(response.body.asString());
        expect(response.status).toBe($.net.http.CREATED);
    });

    it("should create discount code for other user", function() {
        // Read which additional customer exist
        var service = encodeURI("/de/linuxdozent/gittest/odata/service.xsodata/Customer?$filter=UserName ne '" + discountCodeCreate.UserName + "'");
        var response = jasmine.callHTTPService(service, $.net.http.GET, undefined, header, loginResult.cookies);
        expect(response.status).toBe($.net.http.OK);
		var responseBody = OData.getResponseBody(response);
		if (responseBody.d.results.length > 0) {
            discountCodeCreate.ID = "3";
            discountCodeCreate.UserName = responseBody.d.results[0].UserName;
            response = jasmine.callHTTPService(discountCodeService, $.net.http.POST, JSON.stringify(discountCodeCreate), header, loginResult.cookies);
            expect(response.status).toBe($.net.http.CREATED);
		}
    });

    it("should get a list of discounts but not the code", function() {
        var DiscountCodeURL = encodeURI( discountCodeService + "?$filter=UserName eq '" + discountCodeCreate.UserName + "'" );
        var response = jasmine.callHTTPService(DiscountCodeURL, $.net.http.GET, undefined, header, loginResult.cookies);
        expect(response.status).toBe($.net.http.OK);
		var responseBody = OData.getResponseBody(response);
        expect(responseBody.d.results[0].UserName).toBe(discountCodeCreate.UserName);
    });

    it("should logout BSADMIN", function() {
        Login.logout(loginResult.csrf, loginResult.cookies);
        Login.checkSession();
    });
});<|endoftext|>


<commit_before>const assert = require("assert");
const CommandRunner = require("../commandrunner");
const MemoryLogger = require("../memorylogger");
const sandbox = require("../sandbox");
const path = require("path");

describe("truffle build [ @standalone ]", () => {
  const logger = new MemoryLogger();
  let config, project;

  describe("when there is no build script in config", () => {
    beforeEach("set up sandbox", function () {
      project = path.join(
        __dirname,
        "../../sources/build/projectWithoutBuildScript"
      );
      return sandbox.create(project).then(conf => {
        config = conf;
        config.logger = logger;
      });
    });

    it("should not error", async () => {
      try {
        await CommandRunner.run("build", config);
      } catch (error) {
        assert(false, "An error should not have occurred.");
      }
    }).timeout(30000);

    it("whines about having no build config", async () => {
      await CommandRunner.run("build", config);
      const output = logger.contents();
      assert(output.includes("No build configuration found."));
    });
  });

  describe("when there is a proper build config", () => {
    beforeEach("set up sandbox", function () {
      project = path.join(
        __dirname,
        "../../sources/build/projectWithBuildScript"
      );
      return sandbox.create(project).then(conf => {
        config = conf;
        config.logger = logger;
      });
    });
    it("runs the build script", async () => {
      await CommandRunner.run("build", config);
      const output = logger.contents();
      assert(output.includes("'this is the build script'"));
    });
  });

  describe("when there is an object in the build config", () => {
    beforeEach("set up sandbox", function () {
      project = path.join(
        __dirname,
        "../../sources/build/projectWithObjectInBuildScript"
      );
      return sandbox.create(project).then(conf => {
        config = conf;
        config.logger = logger;
      });
    });
    it("tells the user it shouldn't use an object", async () => {
      try {
        await CommandRunner.run("build", config);
      } catch (error) {
        const output = logger.contents();
        assert(
          output.includes(
            "Build configuration can no longer be specified as an object."
          )
        );
      }
    });
  });
});
<commit_msg>Update packages/truffle/test/scenarios/commands/build.js<commit_after>const assert = require("assert");
const CommandRunner = require("../commandrunner");
const MemoryLogger = require("../memorylogger");
const sandbox = require("../sandbox");
const path = require("path");

describe("truffle build [ @standalone ]", () => {
  const logger = new MemoryLogger();
  let config, project;

  describe("when there is no build script in config", () => {
    beforeEach("set up sandbox", function () {
      project = path.join(
        __dirname,
        "../../sources/build/projectWithoutBuildScript"
      );
      return sandbox.create(project).then(conf => {
        config = conf;
        config.logger = logger;
      });
    });

    it("should not error", async () => {
      try {
        await CommandRunner.run("build", config);
      } catch (error) {
        assert(false, "An error should not have occurred.");
      }
    }).timeout(30000);

    it("whines about having no build config", async () => {
      await CommandRunner.run("build", config);
      const output = logger.contents();
      assert(output.includes("No build configuration found."));
    });
  });

  describe("when there is a proper build config", () => {
    beforeEach("set up sandbox", function () {
      project = path.join(
        __dirname,
        "../../sources/build/projectWithBuildScript"
      );
      return sandbox.create(project).then(conf => {
        config = conf;
        config.logger = logger;
      });
    });
    it("runs the build script", async () => {
      await CommandRunner.run("build", config);
      const output = logger.contents();
      assert(output.includes("'this is the build script'"));
    });
  });

  describe("when there is an object in the build config", () => {
    beforeEach("set up sandbox", function () {
      project = path.join(
        __dirname,
        "../../sources/build/projectWithObjectInBuildScript"
      );
      return sandbox.create(project).then(conf => {
        config = conf;
        config.logger = logger;
      });
    });
    it("tells the user it shouldn't use an object", async function () {
      try {
        await CommandRunner.run("build", config);
      } catch (error) {
        const output = logger.contents();
        assert(
          output.includes(
            "Build configuration can no longer be specified as an object."
          )
        );
      }
    });
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs'),
    parse = require('csv-parse'),
    _ = require('underscore'),
    moment = require('moment'),
    db = require('./db'),
    csvOptions = {columns: true},
    currentCommittees = {},
    batchSize = 10,
    committeeTableName = 'committees',
    contributionTableName = 'contributions',
    expenditureTableName = 'expenditures',
    abbrev = {
        STREET: 'ST',
        ROAD: 'RD',
        DRIVE: 'DR',
        AVENUE: 'AVE',
        COURT: 'CT',
        LANE: 'LN',
        TERRACE: 'TER',
        CIRCLE: 'CIR',
        BOULEVARD: 'BLVD',
        HIGHWAY: 'HWY',
        PLACE: 'PL'
    },
    abbrevRegexp = new RegExp('\\b(' + Object.keys(abbrev).join('|') + ')\\b');

db.schema.dropTableIfExists(contributionTableName)
    .dropTableIfExists(expenditureTableName)
    .dropTableIfExists(committeeTableName)
    .createTable(
        committeeTableName,
        function (table) {
            var columnNames = [
                'committee_name',
                'candidate_name',
                'election_year',
                'status',
                'office'
            ];
            table.increments();
            columnNames.forEach(function (columnName) {
                if (/year/.test(columnName)) {
                    table.integer(columnName);
                }
                else {
                    table.string(columnName);
                }
            });
        }
    )
    .createTable(
        contributionTableName,
        function (table) {
            var columnNames = [
                    'committee_name',
                    'contributor_name',
                    'contributor_address',
                    'normalized',
                    'contributor_type',
                    'contribution_type',
                    'employer_name',
                    'employer_address',
                    'occupation',
                    'receipt_date',
                    'amount'
                ];
            table.increments();
            columnNames.forEach(function (columnName) {
                if (/date/.test(columnName)) {
                    table.date(columnName);
                }
                else if (/amount|total/.test(columnName)) {
                    table.float(columnName);
                }
                else {
                    table.string(columnName);
                }
            });
        }
    )
    .createTable(
        expenditureTableName,
        function (table) {
            var columnNames = [
                'committee_name',
                'payee_name',
                'payee_address',
                'normalized',
                'purpose_of_expenditure',
                'payment_date',
                'amount'
            ];
            table.increments();
            columnNames.forEach(function (columnName) {
                if (/date/.test(columnName)) {
                    table.date(columnName);
                }
                else if (/amount|total/.test(columnName)) {
                    table.float(columnName);
                }
                else {
                    table.string(columnName);
                }
            });
        }
    )
    .then(readCommittees);

function readCommittees() {
    var parser = parse(csvOptions),
        input = fs.createReadStream(__dirname + '/' + committeeTableName + '.csv'),
        records = [];
    parser.on('readable', function () {
        var record;
        while(record = parser.read()) {
            record = transformRecord(record);
            currentCommittees[record.committee_name] = true;
            records.push(record);
        }
    });
    parser.on('error', function (err) {
        console.error(err.message);
        throw err;
    });
    parser.on('finish', function () {
        console.log('Finished reading committees');
        console.log(Object.keys(currentCommittees).sort());
        db.batchInsert(committeeTableName, records, batchSize)
            .returning('id')
            .then(readContributions);
    });
    input.pipe(parser);
}

function readContributions() {
    var parser = parse(csvOptions),
        input = fs.createReadStream(__dirname + '/' + contributionTableName + '.csv'),
        seen = {},
        unrecognized = [],
        totalCount = 0,
        currentCount = 0,
        batch = [];
    parser.on('readable', function () {
        var record;
        while (record = parser.read()) {
            var name;
            totalCount++;
            record = transformRecord(record);
            name = record.committee_name;
            if (!seen[name]) {
                seen[name] = true;
                console.log(name);
                if (!currentCommittees[name]) {
                    unrecognized.push(name);
                }
            }
            if (!currentCommittees[name]) {
                continue;
            }
            record.normalized = normalizeNameAndAddress(record.contributor_name, record.contributor_address);
            batch.push(record);
            if (batch.length >= batchSize) {
                batchInsert(contributionTableName, batch);
                batch = [];
            }
            currentCount++;
        }
    });
    parser.on('error', function (err) {
        console.error(err.message);
        throw err;
    });
    parser.on('finish', function () {
        if (batch.length) {
            batchInsert(contributionTableName, batch);
        }
        console.log('Finished reading %d contributions', totalCount);
        console.log('Inserted %d contributions', currentCount);
        console.log('Unrecognized committees:\n', unrecognized.sort());
        readExpenditures();
    });
    input.pipe(parser);
}

function readExpenditures() {
    var parser = parse(csvOptions),
        input = fs.createReadStream(__dirname + '/' + expenditureTableName + '.csv'),
        seen = {},
        unrecognized = [],
        totalCount = 0,
        currentCount = 0,
        batch = [];
    parser.on('readable', function () {
        var record;
        while (record = parser.read()) {
            var name;
            totalCount++;
            record = transformRecord(record);
            name = record.committee_name;
            if (!seen[name]) {
                seen[name] = true;
                console.log(name);
                if (!currentCommittees[name]) {
                    unrecognized.push(name);
                }
            }
            if (!currentCommittees[name]) {
                continue;
            }
            record.normalized = normalizeNameAndAddress(record.payee_name, record.payee_address);
            batch.push(record);
            if (batch.length >= batchSize) {
                batchInsert(expenditureTableName, batch);
                batch = [];
            }
            currentCount++;
        }
    });
    parser.on('error', function (err) {
        console.error(err.message);
        throw err;
    });
    parser.on('finish', function () {
        if (batch.length) {
            batchInsert(expenditureTableName, batch);
        }
        console.log('Finished reading %d expenditures', totalCount);
        console.log('Inserted %d v', currentCount);
        console.log('Unrecognized committees:\n', unrecognized.sort());
        addDummyContributions();
    });
    input.pipe(parser);
}

// Add negative contributions corresponding to refunds and bounced checks
function addDummyContributions() {
    db.select(
            'e.committee_name',
            'e.payee_name as contributor_name',
            'e.payee_address as contributor_address',
            'e.normalized',
            'c.contributor_type',
            'e.purpose_of_expenditure as contribution_type',
            'c.employer_name',
            'c.employer_address',
            'c.occupation',
            'e.payment_date as receipt_date',
            db.raw('-e.amount as amount')
        )
        .from('expenditures as e')
        .innerJoin('contributions as c', function () {
            this.on('e.committee_name', 'c.committee_name')
                .andOn('e.normalized', 'c.normalized')
        })
        .whereIn('purpose_of_expenditure', ['Refund', 'Return Check and Fees'])
        .groupBy('e.id')
        .orderBy('e.committee_name')
        .orderBy('e.payee_name')
        .then(function (rows) {
            batchInsert(contributionTableName, rows);
        })
}

function transformRecord(record) {
    var newRecord = {};
    _.each(record, function (value, key) {
        value = trim(value);
        key = nameToCode(key);
        if (/date/.test(key) && /^\d\d?\/\d\d?\/\d{4}$/.test(value)) {
            value = moment(value, 'MM/DD/YYYY').format('YYYY-MM-DD');
        }
        else if (/amount|total/.test(key) && /^[\$\.,\d]+$/.test(value)) {
            value = value.replace(/[\$,]/g, '');
        }
        newRecord[key] = value;
    });
    return newRecord;
}

function nameToCode(s) {
    return s.toLowerCase()
        .replace(/\W+/g, '_')
        .replace(/^_|_$/g, '');
}

function trim(s) {
    return s ? s.replace(/\s+/g, ' ').replace(/^ | $/g, '') : '';
}

function batchInsert(tableName, batch) {
    db.batchInsert(tableName, batch, batchSize)
        .returning('id')
        .then(function () {});
}

function normalizeNameAndAddress(name, address) {
    var normalized = name.toUpperCase()
        .replace(/[ ,]*,[ ,]*/g, ' ')
        .replace(/\./g, '')
//        .replace(/ [A-Z] /g, ' ') // remove middle initials
//        .replace(/ (JR|SR|I{1,3})$/, '')
        .replace(/[\- ]*\-[\- ]*/g, ' ');
    if (address) {
        normalized += ', ' + address.toUpperCase()
            .replace(/[ ,]*,[ ,]*/g, ' ')
            .replace(/\./g, '')
            .replace(/'/g, '')
            .replace(/,?\s*([NS][EW],)/, ' $1')
            .replace(/ \d{5}(?:-?\d{4})?$/, '') // remove zip
            .replace(/[\- ]*\-[\- ]*/g, ' ')
            .replace(/\b(SUITE|STE|APT) /, '#')
            .replace(/# /, '#')
            .replace(abbrevRegexp, function (m, p1) {
                return abbrev[p1];
            });
    }
    return normalized;
}
<commit_msg>improve normalization of addresses<commit_after>#!/usr/bin/env node

var fs = require('fs'),
    parse = require('csv-parse'),
    _ = require('underscore'),
    moment = require('moment'),
    db = require('./db'),
    csvOptions = {columns: true},
    currentCommittees = {},
    batchSize = 10,
    committeeTableName = 'committees',
    contributionTableName = 'contributions',
    expenditureTableName = 'expenditures',
    abbrev = {
        STREET: 'ST',
        ROAD: 'RD',
        DRIVE: 'DR',
        AVENUE: 'AVE',
        COURT: 'CT',
        LANE: 'LN',
        TERRACE: 'TER',
        CIRCLE: 'CIR',
        BOULEVARD: 'BLVD',
        HIGHWAY: 'HWY',
        PLACE: 'PL'
    },
    abbrevRegexp = new RegExp('\\b(' + Object.keys(abbrev).join('|') + ')\\b');

db.schema.dropTableIfExists(contributionTableName)
    .dropTableIfExists(expenditureTableName)
    .dropTableIfExists(committeeTableName)
    .createTable(
        committeeTableName,
        function (table) {
            var columnNames = [
                'committee_name',
                'candidate_name',
                'election_year',
                'status',
                'office'
            ];
            table.increments();
            columnNames.forEach(function (columnName) {
                if (/year/.test(columnName)) {
                    table.integer(columnName);
                }
                else {
                    table.string(columnName);
                }
            });
        }
    )
    .createTable(
        contributionTableName,
        function (table) {
            var columnNames = [
                    'committee_name',
                    'contributor_name',
                    'contributor_address',
                    'normalized',
                    'contributor_type',
                    'contribution_type',
                    'employer_name',
                    'employer_address',
                    'occupation',
                    'receipt_date',
                    'amount'
                ];
            table.increments();
            columnNames.forEach(function (columnName) {
                if (/date/.test(columnName)) {
                    table.date(columnName);
                }
                else if (/amount|total/.test(columnName)) {
                    table.float(columnName);
                }
                else {
                    table.string(columnName);
                }
            });
        }
    )
    .createTable(
        expenditureTableName,
        function (table) {
            var columnNames = [
                'committee_name',
                'payee_name',
                'payee_address',
                'normalized',
                'purpose_of_expenditure',
                'payment_date',
                'amount'
            ];
            table.increments();
            columnNames.forEach(function (columnName) {
                if (/date/.test(columnName)) {
                    table.date(columnName);
                }
                else if (/amount|total/.test(columnName)) {
                    table.float(columnName);
                }
                else {
                    table.string(columnName);
                }
            });
        }
    )
    .then(readCommittees);

function readCommittees() {
    var parser = parse(csvOptions),
        input = fs.createReadStream(__dirname + '/' + committeeTableName + '.csv'),
        records = [];
    parser.on('readable', function () {
        var record;
        while(record = parser.read()) {
            record = transformRecord(record);
            currentCommittees[record.committee_name] = true;
            records.push(record);
        }
    });
    parser.on('error', function (err) {
        console.error(err.message);
        throw err;
    });
    parser.on('finish', function () {
        console.log('Finished reading committees');
        console.log(Object.keys(currentCommittees).sort());
        db.batchInsert(committeeTableName, records, batchSize)
            .returning('id')
            .then(readContributions);
    });
    input.pipe(parser);
}

function readContributions() {
    var parser = parse(csvOptions),
        input = fs.createReadStream(__dirname + '/' + contributionTableName + '.csv'),
        seen = {},
        unrecognized = [],
        totalCount = 0,
        currentCount = 0,
        batch = [];
    parser.on('readable', function () {
        var record;
        while (record = parser.read()) {
            var name;
            totalCount++;
            record = transformRecord(record);
            name = record.committee_name;
            if (!seen[name]) {
                seen[name] = true;
                console.log(name);
                if (!currentCommittees[name]) {
                    unrecognized.push(name);
                }
            }
            if (!currentCommittees[name]) {
                continue;
            }
            record.normalized = normalizeNameAndAddress(record.contributor_name, record.contributor_address);
            batch.push(record);
            if (batch.length >= batchSize) {
                batchInsert(contributionTableName, batch);
                batch = [];
            }
            currentCount++;
        }
    });
    parser.on('error', function (err) {
        console.error(err.message);
        throw err;
    });
    parser.on('finish', function () {
        if (batch.length) {
            batchInsert(contributionTableName, batch);
        }
        console.log('Finished reading %d contributions', totalCount);
        console.log('Inserted %d contributions', currentCount);
        console.log('Unrecognized committees:\n', unrecognized.sort());
        readExpenditures();
    });
    input.pipe(parser);
}

function readExpenditures() {
    var parser = parse(csvOptions),
        input = fs.createReadStream(__dirname + '/' + expenditureTableName + '.csv'),
        seen = {},
        unrecognized = [],
        totalCount = 0,
        currentCount = 0,
        batch = [];
    parser.on('readable', function () {
        var record;
        while (record = parser.read()) {
            var name;
            totalCount++;
            record = transformRecord(record);
            name = record.committee_name;
            if (!seen[name]) {
                seen[name] = true;
                console.log(name);
                if (!currentCommittees[name]) {
                    unrecognized.push(name);
                }
            }
            if (!currentCommittees[name]) {
                continue;
            }
            record.normalized = normalizeNameAndAddress(record.payee_name, record.payee_address);
            batch.push(record);
            if (batch.length >= batchSize) {
                batchInsert(expenditureTableName, batch);
                batch = [];
            }
            currentCount++;
        }
    });
    parser.on('error', function (err) {
        console.error(err.message);
        throw err;
    });
    parser.on('finish', function () {
        if (batch.length) {
            batchInsert(expenditureTableName, batch);
        }
        console.log('Finished reading %d expenditures', totalCount);
        console.log('Inserted %d v', currentCount);
        console.log('Unrecognized committees:\n', unrecognized.sort());
        addDummyContributions();
    });
    input.pipe(parser);
}

// Add negative contributions corresponding to refunds and bounced checks
function addDummyContributions() {
    db.select(
            'e.committee_name',
            'e.payee_name as contributor_name',
            'e.payee_address as contributor_address',
            'e.normalized',
            'c.contributor_type',
            'e.purpose_of_expenditure as contribution_type',
            'c.employer_name',
            'c.employer_address',
            'c.occupation',
            'e.payment_date as receipt_date',
            db.raw('-e.amount as amount')
        )
        .from('expenditures as e')
        .innerJoin('contributions as c', function () {
            this.on('e.committee_name', 'c.committee_name')
                .andOn('e.normalized', 'c.normalized')
        })
        .whereIn('purpose_of_expenditure', ['Refund', 'Return Check and Fees'])
        .groupBy('e.id')
        .orderBy('e.committee_name')
        .orderBy('e.payee_name')
        .then(function (rows) {
            batchInsert(contributionTableName, rows);
        })
}

function transformRecord(record) {
    var newRecord = {};
    _.each(record, function (value, key) {
        value = trim(value);
        key = nameToCode(key);
        if (/date/.test(key) && /^\d\d?\/\d\d?\/\d{4}$/.test(value)) {
            value = moment(value, 'MM/DD/YYYY').format('YYYY-MM-DD');
        }
        else if (/amount|total/.test(key) && /^[\$\.,\d]+$/.test(value)) {
            value = value.replace(/[\$,]/g, '');
        }
        newRecord[key] = value;
    });
    return newRecord;
}

function nameToCode(s) {
    return s.toLowerCase()
        .replace(/\W+/g, '_')
        .replace(/^_|_$/g, '');
}

function trim(s) {
    return s ? s.replace(/\s+/g, ' ').replace(/^ | $/g, '') : '';
}

function batchInsert(tableName, batch) {
    db.batchInsert(tableName, batch, batchSize)
        .returning('id')
        .then(function () {});
}

function normalizeNameAndAddress(name, address) {
    var normalized = name.toUpperCase()
        .replace(/[ ,]*,[ ,]*/g, ' ')
        .replace(/\./g, '')
//        .replace(/ [A-Z] /g, ' ') // remove middle initials
//        .replace(/ (JR|SR|I{1,3})$/, '')
        .replace(/[\- ]*\-[\- ]*/g, ' ');
    if (address) {
        normalized += ', ' + address.toUpperCase()
            .replace(/[ ,]*,[ ,]*/g, ' ')
            .replace(/\./g, '')
            .replace(/'/g, '')
            .replace(/,?\s*([NS][EW],)/, ' $1')
            .replace(/ [\d \-]+$/, '') // remove zip
            .replace(/[\- ]*\-[\- ]*/g, ' ')
            .replace(/\b(SUITE|STE|APT) /, '#')
            .replace(/# /, '#')
            .replace(/ VIRGINIA$/, ' VA')
            .replace(/ MARYLAND$/, ' MD')
            .replace(/ DISTRICT OF COLUMBIA$/, ' DC')
            .replace(/( \w+)(\1 [A-Z]{2})$/, '$2')
            .replace(/( \w+ [A-Z]{2})\1$/, '$1')
            .replace(/ #\S+/, '') // remove apartment number
            .replace(abbrevRegexp, function (m, p1) {
                return abbrev[p1];
            });
    }
    return normalized;
}
<|endoftext|>


<commit_before>var Boom = require('boom');
var Fs = require('fs');
var Hoek = require('hoek');
var Url = require('url');
var Wreck = require('wreck');

const GITHUB_HOST = "api.github.com";

exports.register = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/local/{jsonFile*}',
        handler: function (request, reply) {

            var filePath = [__dirname, 'fixtures', '..', encodeURIComponent(request.params.jsonFile)].join('/');
            reply.file(filePath);
        }
    });

    server.route({
        method: 'GET',
        path: '/local/fb',
        handler: function (request, reply) {

            var rawFile = Fs.readFileSync(__dirname + '/../fixtures/facebook.json', 'utf-8');
            parsedJson = JSON.parse(rawFile);

            var transformedJson = Hoek.transform(parsedJson.data, {
                'messageId': 'id',
                'message': 'message',
                'name': 'from.name',
                'userId': 'from.id',
                'createdTimestamp': 'created_time',
                // JS property order is not guaranteed; YMMV
                'comment': 'actions.0.link',
                'like': 'actions.1.link'
            });

            reply(transformedJson);
        }
    });

    // https://gist.github.com/jasonrudolph/6065289#file-01-trending-repos-md

    server.route({
        method: 'GET',
        path: '/github/repos/hapi',
        handler: function (request, reply) {

            var uri = Url.format({
                protocol: "https",
                hostname: GITHUB_HOST,
                pathname: "search/repositories",
                query:{
                    q: "hapijs",
                    sort: "stars"

                }
            });

            console.log('uri: ', uri)

            var wreckOptions = {
                 timeout: 1500,
                 json: true,
                 headers: {
                    // required for Github; https://developer.github.com/v3/#user-agent-required
                    "User-Agent": "zedd45"
                 }

            };

            Wreck.get(uri, wreckOptions, function (err, response, payload) {

                if (err) {
                    var msg = 'problem reading from Github:';
                    var badGateway = Boom.badGateway(msg, {err: err});
                    console.error(msg, err);
                    return reply(badGateway);
                }

                if (response.statusCode >= 400) {
                    var msg = 'Github returned an HTTP status code corresponding to an error:';
                    var httpError = Boom.create(response.statusCode, msg, {payload: payload});
                    console.error(msg);
                    return reply(httpError);
                }

                return reply(payload).code(response.statusCode);
            });
        }
    });

    next();
};

exports.register.attributes = {
    name: 'api-routes',
    version: '1.0.0'
};
<commit_msg>version bump.<commit_after>var Boom = require('boom');
var Fs = require('fs');
var Hoek = require('hoek');
var Url = require('url');
var Wreck = require('wreck');

const GITHUB_HOST = "api.github.com";

exports.register = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/local/{jsonFile*}',
        handler: function (request, reply) {

            var filePath = [__dirname, 'fixtures', '..', encodeURIComponent(request.params.jsonFile)].join('/');
            reply.file(filePath);
        }
    });

    server.route({
        method: 'GET',
        path: '/local/fb',
        handler: function (request, reply) {

            var rawFile = Fs.readFileSync(__dirname + '/../fixtures/facebook.json', 'utf-8');
            parsedJson = JSON.parse(rawFile);

            var transformedJson = Hoek.transform(parsedJson.data, {
                'messageId': 'id',
                'message': 'message',
                'name': 'from.name',
                'userId': 'from.id',
                'createdTimestamp': 'created_time',
                // JS property order is not guaranteed; YMMV
                'comment': 'actions.0.link',
                'like': 'actions.1.link'
            });

            reply(transformedJson);
        }
    });

    // https://gist.github.com/jasonrudolph/6065289#file-01-trending-repos-md

    server.route({
        method: 'GET',
        path: '/github/repos/hapi',
        handler: function (request, reply) {

            var uri = Url.format({
                protocol: "https",
                hostname: GITHUB_HOST,
                pathname: "search/repositories",
                query:{
                    q: "hapijs",
                    sort: "stars"

                }
            });

            console.log('uri: ', uri)

            var wreckOptions = {
                 timeout: 1500,
                 json: true,
                 headers: {
                    // required for Github; https://developer.github.com/v3/#user-agent-required
                    "User-Agent": "zedd45"
                 }

            };

            Wreck.get(uri, wreckOptions, function (err, response, payload) {

                if (err) {
                    var msg = 'problem reading from Github:';
                    var badGateway = Boom.badGateway(msg, {err: err});
                    console.error(msg, err);
                    return reply(badGateway);
                }

                if (response.statusCode >= 400) {
                    var msg = 'Github returned an HTTP status code corresponding to an error:';
                    var httpError = Boom.create(response.statusCode, msg, {payload: payload});
                    console.error(msg);
                    return reply(httpError);
                }

                return reply(payload).code(response.statusCode);
            });
        }
    });

    next();
};

exports.register.attributes = {
    name: 'api-routes',
    version: '1.1.0'
};
<|endoftext|>


<commit_before>import {inject, Lazy} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import {RestService} from '../rest-service';

const serviceUri = require('../host').inventory + '/docs/efr-tb-bjr';
const serviceOutUri = require('../host').inventory + '/docs/efr-kb-rtf';

export class Service extends RestService{

  constructor(http, aggregator) {
      super(http, aggregator);
  }

  search(keyword) {
      return super.get(serviceUri);
  }

  getById(id)
  {
      var endpoint = `${serviceUri}/${id}`;
      return super.get(endpoint);
  }

  getOutByCode(code)
  {
      var endpoint = `${serviceOutUri}?keyword=${code}`;
      return super.get(endpoint);
  }

  create(data)
  {
      var endpoint = `${serviceUri}`;
      return super.post(endpoint, data);
  }

}<commit_msg>change name of function getOutCode in efr-tb-bjr<commit_after>import {inject, Lazy} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import {RestService} from '../rest-service';

const serviceUri = require('../host').inventory + '/docs/efr-tb-bjr';
const serviceOutUri = require('../host').inventory + '/docs/efr-kb-rtf';

export class Service extends RestService{

  constructor(http, aggregator) {
      super(http, aggregator);
  }

  search(keyword) {
      return super.get(serviceUri);
  }

  getById(id)
  {
      var endpoint = `${serviceUri}/${id}`;
      return super.get(endpoint);
  }

  getEFRKBRTFByCode(code)
  {
      var endpoint = `${serviceOutUri}?keyword=${code}`;
      return super.get(endpoint);
  }

  create(data)
  {
      var endpoint = `${serviceUri}`;
      return super.post(endpoint, data);
  }

}<|endoftext|>