<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
 <commit_msg>Someone poisoned the waterhole!<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
  <|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Stor<commit_msg>Fixed a typo<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should wo<commit_msg>Can work my way through the Kanban<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should wor<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_<commit_msg>How many more of these can I make?<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_s<|endoftext|>


<commit_before>define('bforms-form', [
    'jquery',
    'bforms-extensions',
    'jquery-ui-core',
    'bforms-validate-unobtrusive',
    'bforms-initUI',
    'bforms-ajax'
], function () {

    var Form = function (opt) {
        this.options = opt;
        this._create();
    };

    Form.prototype.options = {
        uniqueName: null,
        hasGroupToggle: false,
        style: {},
        groupToggleSelector: '.bs-selector',
        actions: []         //[{
                            //    name: 'refresh',
                            //    btnSelector: '.bs-refreshBtn',
                            //    url: '',
        //    handler: '',
        // setAdditionalData: null,
                            //    validate: true,
                            //    parse: true
                            //}]
    };

    Form.prototype._create = function () {

        if (!this.options.uniqueName){
            this.options.uniqueName = this.element.attr('id');
        }

        if (!this.options.uniqueName) {
            throw 'form needs a unique name or the element on which it is aplied has to have an id attr';
        }

        this._buttons = new Array();

        this._initSelectors();

        this._addDelegates();

        this._addActions(this.options.actions);

        var initUIPromise = this.$form.bsInitUI(this.options.style);
        initUIPromise.done($.proxy(function() {
            this._trigger('afterInitUI', 0, {
                name: this.options.uniqueName,
                form: this.$form
            });
        }, this));

    };

    Form.prototype._initSelectors = function () {

        this.$form = this.element.find('form');

    };

    Form.prototype._addDelegates = function () {

        if (this.options.hasGroupToggle) {
            this.element.find(this.options.groupToggleSelector).on('click', $.proxy(this._evToggleGroup, this));
        }

    };

    Form.prototype._addActions = function (actions) {

        if (actions) {
            for (var i = 0; i < actions.length; i++) {
                this._addAction(actions[i]);
            }
        }

    };

    Form.prototype._addAction = function (buttonOpt) {

        var $elem = this.element.find(buttonOpt.selector);

        $elem.on('click', {
            buttonOpt: buttonOpt,
            handlerContext: this.options.handlerContext
        }, $.proxy(this._evBtnClick, this));

        this._buttons.push({
            name: buttonOpt.name,
            elem: $elem
        });

    };

    Form.prototype._evBtnClick = function (e) {

        e.preventDefault();

        var $me = $(e.currentTarget);
        var buttonOpt = e.data.buttonOpt;
        var handlerContext = e.data.handlerContext;

        if (buttonOpt.validate) {
            $.validator.unobtrusive.parse(this.$form);

            var validatedForm = this.$form.validate();

            this._trigger('beforeFormValidation', 0, {
                validator: validatedForm,
                form: this.$form,
                name: this.options.uniqueName
            });

            if (!this.$form.valid()) {
                return;
            }
        }

        var data;
        if (buttonOpt.parse) {
            data = this._parse();
            if (typeof buttonOpt.getExtraData === 'function') {
                buttonOpt.setExtraData.call(this, data);
            }
        }

        var action = $me.data('action');
        if (action) {
            $.bforms.ajax({
                name: this.options.uniqueName,
                url: action,
                data: data,
                callbackData: {
                    handler: buttonOpt.handler,
                    handlerContext: handlerContext,
                    sent: data
                },
                context: this,
                success: $.proxy(this._btnClickAjaxSuccess, this),
                error: $.proxy(this._btnClickAjaxError, this),
                loadingElement: this.element,
                loadingClass: 'loading'/*,
                validationError: function (response) {
                    if (response != null && response.Errors != null) {
                        validator.showErrors(response.Errors);
                    }
                },

                loadingElement: e.elem,
                loadingClass: 'loading'*/
            });
        } else {
            if (typeof buttonOpt.handler !== 'function') {
                throw 'action ' + buttonOpt.name + ' must implement an event handler or have an url option';
            }
            buttonOpt.handler.call(this, data);
        }

    };

    Form.prototype._parse = function () {

        return this.element.parseForm();

    };

    Form.prototype._btnClickAjaxSuccess = function (data, callbackData) {
        if (typeof callbackData.handler === 'function') {
            callbackData.handler.call(this, callbackData.sent, data, this);
        }
    };

    Form.prototype._btnClickAjaxError = function (data) {
        if (data.Message) {
            var validatedForm = this.$form.data('validator');
            validatedForm.showSummaryError(data.Message);
        }
    };

    Form.prototype._evToggleGroup = function (e) {

        var $elem = $(e.currentTarget);

        $elem.toggleClass('open').parent().next().slideToggle();

    };

    Form.prototype.getFormData = function (data) {

        var form = this.element.find('form');

        form.removeData("validator");
        form.removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse(form);

        var validatedForm = form.validate();
        this._trigger('beforeFormValidation', 0, {
            validator: validatedForm,
            form: form,
            name: this.options.uniqueName
        });

        if (form.valid()) {
            data = this.element.parseForm();
        }

    };

    Form.prototype.parse = function(e) {
        return this._parse();
    };

    Form.prototype.reset = function (e) {
        this.element.bsResetForm(true);
    };

    $.widget('bforms.bsForm', Form.prototype);

    return Form;

});
<commit_msg>added exception when button selector is not found in form container<commit_after>define('bforms-form', [
    'jquery',
    'bforms-extensions',
    'jquery-ui-core',
    'bforms-validate-unobtrusive',
    'bforms-initUI',
    'bforms-ajax'
], function () {

    var Form = function (opt) {
        this.options = opt;
        this._create();
    };

    Form.prototype.options = {
        uniqueName: null,
        hasGroupToggle: false,
        style: {},
        groupToggleSelector: '.bs-selector',
        actions: []         //[{
                            //    name: 'refresh',
                            //    btnSelector: '.bs-refreshBtn',
                            //    url: '',
        //    handler: '',
        // setAdditionalData: null,
                            //    validate: true,
                            //    parse: true
                            //}]
    };

    Form.prototype._init = function () {

        if (!this.options.uniqueName){
            this.options.uniqueName = this.element.attr('id');
        }

        if (!this.options.uniqueName) {
            throw 'form needs a unique name or the element on which it is aplied has to have an id attr';
        }

        this._buttons = new Array();

        this._initSelectors();

        this._addDelegates();

        this._addActions(this.options.actions);

        var initUIPromise = this.$form.bsInitUI(this.options.style);
        initUIPromise.done($.proxy(function() {
            this._trigger('afterInitUI', 0, {
                name: this.options.uniqueName,
                form: this.$form
            });
        }, this));

    };

    Form.prototype._initSelectors = function () {

        this.$form = this.element.find('form');

    };

    Form.prototype._addDelegates = function () {

        if (this.options.hasGroupToggle) {
            this.element.find(this.options.groupToggleSelector).on('click', $.proxy(this._evToggleGroup, this));
        }

    };

    Form.prototype._addActions = function (actions) {

        if (actions) {
            for (var i = 0; i < actions.length; i++) {
                this._addAction(actions[i]);
            }
        }

    };

    Form.prototype._addAction = function (buttonOpt) {

        var $elem = this.element.find(buttonOpt.selector);

        if ($elem.length == 0) {
            throw 'element with selector ' + buttonOpt.selector + ' is not found in form container ' + this.options.uniqueName;
        }

        $elem.on('click', {
            buttonOpt: buttonOpt,
            handlerContext: this.options.handlerContext
        }, $.proxy(this._evBtnClick, this));

        this._buttons.push({
            name: buttonOpt.name,
            elem: $elem
        });

    };

    Form.prototype._evBtnClick = function (e) {

        e.preventDefault();

        var $me = $(e.currentTarget);
        var buttonOpt = e.data.buttonOpt;
        var handlerContext = e.data.handlerContext;

        if (buttonOpt.validate) {
            $.validator.unobtrusive.parse(this.$form);

            var validatedForm = this.$form.validate();

            this._trigger('beforeFormValidation', 0, {
                validator: validatedForm,
                form: this.$form,
                name: this.options.uniqueName
            });

            if (!this.$form.valid()) {
                return;
            }
        }

        var data;
        if (buttonOpt.parse) {
            data = this._parse();
            if (typeof buttonOpt.getExtraData === 'function') {
                buttonOpt.setExtraData.call(this, data);
            }
        }

        var action = $me.data('action');
        if (action) {
            $.bforms.ajax({
                name: this.options.uniqueName,
                url: action,
                data: data,
                callbackData: {
                    handler: buttonOpt.handler,
                    handlerContext: handlerContext,
                    sent: data
                },
                context: this,
                success: $.proxy(this._btnClickAjaxSuccess, this),
                error: $.proxy(this._btnClickAjaxError, this),
                loadingElement: this.element,
                loadingClass: 'loading'/*,
                validationError: function (response) {
                    if (response != null && response.Errors != null) {
                        validator.showErrors(response.Errors);
                    }
                },

                loadingElement: e.elem,
                loadingClass: 'loading'*/
            });
        } else {
            if (typeof buttonOpt.handler !== 'function') {
                throw 'action ' + buttonOpt.name + ' must implement an event handler or have an url option';
            }
            buttonOpt.handler.call(this, data);
        }

    };

    Form.prototype._parse = function () {

        return this.element.parseForm();

    };

    Form.prototype._btnClickAjaxSuccess = function (data, callbackData) {
        if (typeof callbackData.handler === 'function') {
            callbackData.handler.call(this, callbackData.sent, data, this);
        }
    };

    Form.prototype._btnClickAjaxError = function (data) {
        if (data.Message) {
            var validatedForm = this.$form.data('validator');
            validatedForm.showSummaryError(data.Message);
        }
    };

    Form.prototype._evToggleGroup = function (e) {

        var $elem = $(e.currentTarget);

        $elem.toggleClass('open').parent().next().slideToggle();

    };

    Form.prototype.getFormData = function (data) {

        var form = this.element.find('form');

        form.removeData("validator");
        form.removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse(form);

        var validatedForm = form.validate();
        this._trigger('beforeFormValidation', 0, {
            validator: validatedForm,
            form: form,
            name: this.options.uniqueName
        });

        if (form.valid()) {
            data = this.element.parseForm();
        }

    };

    Form.prototype.parse = function(e) {
        return this._parse();
    };

    Form.prototype.reset = function (e) {
        this.element.bsResetForm(true);
    };

    $.widget('bforms.bsForm', Form.prototype);

    return Form;

});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  } else {
    var ar<commit_msg>Incompatible dimensions found, Cthuhlu Error 666<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  } else {
    var arg<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  } else {
    var args = ['push']
    child_process.execFileSync('git', args)
    console.info("Finished")
  }
}

function faketime(offset)
{
  process.env.FAKETIME = offset;
}
<commit_msg>Someone poisoned the waterhole!<commit_after>var child_process = <|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
 <commit_msg>Fixing an error introduced in the last commit<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  <|endoftext|>


<commit_before>const WORKOUT_SEPARATOR = '\n\n';
const WHITESPACE = '\s';
var cfg = window.cfg;

function toHtml(text) {
	return Array.isArray(text) ?
		text.join('
') :
		text.replace(/\n/g, '
');
}

function chop(text, textToChop) {
	return typeof text !== 'string' ?
		text :
		text.replace(textToChop, '');
}

function getProp(obj, path) {
	const PATH_DELIM = '.';
	if (typeof path === 'string') {
		path = path.split(PATH_DELIM);
	}
	var prop = obj;

	while (path.length && obj && obj !== null) {
		prop = obj[path[0]];
		path = path.slice(1);
	}

	return prop;
}

/**
 * Takes in text containing slash separated date e.g. 2015/03/01
 * returns first date found as unix time
 * returns null if no date found
 * TODO: adjust for timezones
 */
function getDate(text, context) {
	const WORKOUT_HEADER_DATE_REGEXP = /(\d+\/\d+\/\d+)\s/;
	var dateString = getProp(text.match(WORKOUT_HEADER_DATE_REGEXP), [1]);
	if (!dateString) {
		return null;
	} else {
		dateString.replace(/\//g, '-');
		return Date.parse(dateString);
	}
}

/**
 * Takes in text containing unit of weight
 * returns first unit of weight found
 * returns user's default unit of weight if no date found
 */
function getUnitOfWeight(text, context) {
	if (text.contains('lbs') || text.contains('lb'))
		return cfg.unitOfWeight.pounds;
	else if (text.contains('kgs') || text.contains('kg'))
		return cfg.unitOfWeight.kilos;
	else
		return cfg.unitOfWeight.DEFAULT;
}

var getExerciseName = _.identity;

/*
 * TODO: partition text / comments somehow
 */
function splitComments(text) { return [text]; }

class Workouts {
	constructor(text) {
		this._chunks = text.split(WORKOUT_SEPARATOR);
		this._sections = this._chunks.reduce(function (sections, section, idx) {
			var w, m;
			// TODO: add workout validator static method
			// TODO: abstract this logic out to allow for more types of content
			w = new Workout(section);
			if (w.isValid()) {
				sections.push(w);
			} else {
				m = new MetaSection(section);
				sections.push(m);
			}

			return sections;
		}, []);
	}

	getAll() {
		return this._sections.slice();
	}
}

class MetaSection {
	constructor(sectionText) {
		this._meta = sectionText;
	}

	render() {
		return '
' +
			toHtml(this._meta) +
		'
';
	}
}

class Workout {
	constructor(header, exercises, meta) {
		if (arguments.length === 0) { this.parse(arguments[0]); }
		else {
			this._header = new WorkoutHeader(header);
			this._exercises = new ExerciseSetCollection(exercises);
			this._meta = meta;
		}
	}

	parse(workoutText) {
		const EXERCISE_SEPARATOR = '\n';
		this._chunks = workoutText.split(EXERCISE_SEPARATOR);
		this._header = new WorkoutHeader(this._chunks[0]);
		this._exercises = [];
		this._chunks.slice(1).forEach(exerciseText =>
			this._exercises.push(new ExerciseSetCollection(exerciseText)));
	}

	isValid() { return this._header.isValid(); }

	render() {
		return '
' +
			this._header.render() +
			toHtml(this._exercises.map(exercise => exercise.render())) +
		'
';
	}

}

class WorkoutHeader {
	constructor(headerText) {
		var txt = headerText;
		this._text = txt;

		this._workoutDate = getDate(txt);

		this._workoutUnitOfWeight = getUnitOfWeight(txt);

		this._meta = WorkoutHeader.getMeta(txt);
	}

	isValid() {
		return !!this._workoutDate;
	}

	render() {
		return '
' +
			toHtml(this._text) +
		'
';
	}

	static getMeta(text) {
		return getProp(text.match(/\(([^\)]*)\)/), [1]);
	}
}

class ExerciseSetCollection {
	constructor(name, exSetArr, exComment) {
		if (arguments.length === 1) {
			this.parse(arguments[0]);
		} else {
			this._name = name;
			this._exercises = exSetArr.map(exSet => new ExerciseSet(exset));
			this._comments = new ExerciseMeta(exComment);
		}
	}

	parse(exerciseText) {
		var isValid = true;
		// TEXT FORMAT: EXERCISE_NAME COMMA_SEPARATED_SETS OPTIONAL COMMENT
		this._text = exerciseText;
		this._sections = exerciseText.split(WHITESPACE);
		this._name = getExerciseName(this._sections[0]);
		this._exercises = this._sections.slice(1).join(''); // TODO: parse into sets and comments
		this._comments = '';
		return isValid;
	}

	render() { return toHtml(this._text); }

	validate(text) {
		return !!this._name && !!this._exercises;
	}
}

class ExerciseMeta {
	constructor (metaText) {
		this.parse(metaText);
	}

	parse(metaText) {
		this._text = metaText;
		return true;
	}

	toString { return this._text; }
}

class ExerciseSet {
	constructor(setArray) {
		// TEXT FORMAT: NUM_SETSxREP:WEIGHT
		const SET_SEPARATOR = ',';
		this._chunks = setArray;
	}

	render() { return toHtml(this._chunks); }
	isValid() { return true; }

	toString(sets, reps) {
		if (this instanceof ExerciseSet) {
			sets = this._sets;
			reps = this._reps;
		}

		return sets + cfg.setsByRepsDelim + reps;
	}

	toShortString(sets, reps) {
		if (this instanceof ExerciseSet) {
			sets = this._sets;
			reps = this._reps;
		}

		if (sets === 1) {
			return reps;
		} else {
			return sets + cfg.setsByRepsDelim + reps;
		}
	}
}

class Workset extends ExerciseSet {
	constructor(sets, reps, weight, comments) {
		this._sets = sets;
		this._reps = reps;
		this._weight = weight;
		this._comments = new ExerciseMeta(comments);
	}

	setWeight(weight) {
		this._weight = weight;
	}
}

window.WorkoutsView = class WorkoutsView {
	constructor(workouts) {
		if (!(workouts instanceof Workouts)) {
			workouts = new Workouts(workouts);
		}

		var html = [];

		workouts.getAll().forEach(function (section) {
			html.push(section.render());
		});

		this._html = html.join('');
	}

	render() { return this._html; }
};

//export {Workouts, WorkoutsView};
<commit_msg>fix toString<commit_after>const WORKOUT_SEPARATOR = '\n\n';
const WHITESPACE = '\s';
var cfg = window.cfg;

function toHtml(text) {
	return Array.isArray(text) ?
		text.join('
') :
		text.replace(/\n/g, '
');
}

function chop(text, textToChop) {
	return typeof text !== 'string' ?
		text :
		text.replace(textToChop, '');
}

function getProp(obj, path) {
	const PATH_DELIM = '.';
	if (typeof path === 'string') {
		path = path.split(PATH_DELIM);
	}
	var prop = obj;

	while (path.length && obj && obj !== null) {
		prop = obj[path[0]];
		path = path.slice(1);
	}

	return prop;
}

/**
 * Takes in text containing slash separated date e.g. 2015/03/01
 * returns first date found as unix time
 * returns null if no date found
 * TODO: adjust for timezones
 */
function getDate(text, context) {
	const WORKOUT_HEADER_DATE_REGEXP = /(\d+\/\d+\/\d+)\s/;
	var dateString = getProp(text.match(WORKOUT_HEADER_DATE_REGEXP), [1]);
	if (!dateString) {
		return null;
	} else {
		dateString.replace(/\//g, '-');
		return Date.parse(dateString);
	}
}

/**
 * Takes in text containing unit of weight
 * returns first unit of weight found
 * returns user's default unit of weight if no date found
 */
function getUnitOfWeight(text, context) {
	if (text.contains('lbs') || text.contains('lb'))
		return cfg.unitOfWeight.pounds;
	else if (text.contains('kgs') || text.contains('kg'))
		return cfg.unitOfWeight.kilos;
	else
		return cfg.unitOfWeight.DEFAULT;
}

var getExerciseName = _.identity;

/*
 * TODO: partition text / comments somehow
 */
function splitComments(text) { return [text]; }

class Workouts {
	constructor(text) {
		this._chunks = text.split(WORKOUT_SEPARATOR);
		this._sections = this._chunks.reduce(function (sections, section, idx) {
			var w, m;
			// TODO: add workout validator static method
			// TODO: abstract this logic out to allow for more types of content
			w = new Workout(section);
			if (w.isValid()) {
				sections.push(w);
			} else {
				m = new MetaSection(section);
				sections.push(m);
			}

			return sections;
		}, []);
	}

	getAll() {
		return this._sections.slice();
	}
}

class MetaSection {
	constructor(sectionText) {
		this._meta = sectionText;
	}

	render() {
		return '
' +
			toHtml(this._meta) +
		'
';
	}
}

class Workout {
	constructor(header, exercises, meta) {
		if (arguments.length === 0) { this.parse(arguments[0]); }
		else {
			this._header = new WorkoutHeader(header);
			this._exercises = new ExerciseSetCollection(exercises);
			this._meta = meta;
		}
	}

	parse(workoutText) {
		const EXERCISE_SEPARATOR = '\n';
		this._chunks = workoutText.split(EXERCISE_SEPARATOR);
		this._header = new WorkoutHeader(this._chunks[0]);
		this._exercises = [];
		this._chunks.slice(1).forEach(exerciseText =>
			this._exercises.push(new ExerciseSetCollection(exerciseText)));
	}

	isValid() { return this._header.isValid(); }

	render() {
		return '
' +
			this._header.render() +
			toHtml(this._exercises.map(exercise => exercise.render())) +
		'
';
	}

}

class WorkoutHeader {
	constructor(headerText) {
		var txt = headerText;
		this._text = txt;

		this._workoutDate = getDate(txt);

		this._workoutUnitOfWeight = getUnitOfWeight(txt);

		this._meta = WorkoutHeader.getMeta(txt);
	}

	isValid() {
		return !!this._workoutDate;
	}

	render() {
		return '
' +
			toHtml(this._text) +
		'
';
	}

	static getMeta(text) {
		return getProp(text.match(/\(([^\)]*)\)/), [1]);
	}
}

class ExerciseSetCollection {
	constructor(name, exSetArr, exComment) {
		if (arguments.length === 1) {
			this.parse(arguments[0]);
		} else {
			this._name = name;
			this._exercises = exSetArr.map(exSet => new ExerciseSet(exset));
			this._comments = new ExerciseMeta(exComment);
		}
	}

	parse(exerciseText) {
		var isValid = true;
		// TEXT FORMAT: EXERCISE_NAME COMMA_SEPARATED_SETS OPTIONAL COMMENT
		this._text = exerciseText;
		this._sections = exerciseText.split(WHITESPACE);
		this._name = getExerciseName(this._sections[0]);
		this._exercises = this._sections.slice(1).join(''); // TODO: parse into sets and comments
		this._comments = '';
		return isValid;
	}

	render() { return toHtml(this._text); }

	validate(text) {
		return !!this._name && !!this._exercises;
	}
}

class ExerciseMeta {
	constructor (metaText) {
		this.parse(metaText);
	}

	parse(metaText) {
		this._text = metaText;
		return true;
	}

	toString() { return this._text; }
}

class ExerciseSet {
	constructor(setArray) {
		// TEXT FORMAT: NUM_SETSxREP:WEIGHT
		const SET_SEPARATOR = ',';
		this._chunks = setArray;
	}

	render() { return toHtml(this._chunks); }
	isValid() { return true; }

	toString(sets, reps) {
		if (this instanceof ExerciseSet) {
			sets = this._sets;
			reps = this._reps;
		}

		return sets + cfg.setsByRepsDelim + reps;
	}

	toShortString(sets, reps) {
		if (this instanceof ExerciseSet) {
			sets = this._sets;
			reps = this._reps;
		}

		if (sets === 1) {
			return reps;
		} else {
			return sets + cfg.setsByRepsDelim + reps;
		}
	}
}

class Workset extends ExerciseSet {
	constructor(sets, reps, weight, comments) {
		this._sets = sets;
		this._reps = reps;
		this._weight = weight;
		this._comments = new ExerciseMeta(comments);
	}

	setWeight(weight) {
		this._weight = weight;
	}
}

window.WorkoutsView = class WorkoutsView {
	constructor(workouts) {
		if (!(workouts instanceof Workouts)) {
			workouts = new Workouts(workouts);
		}

		var html = [];

		workouts.getAll().forEach(function (section) {
			html.push(section.render());
		});

		this._html = html.join('');
	}

	render() { return this._html; }
};

//export {Workouts, WorkoutsView};
<|endoftext|>


<commit_before>var IllustFrame = cc.Layer.extend({
    FRAME_WIDTH: 607,
    FRAME_HEIGHT: 387,
    FRAME_X: 58,
    FRAME_Y1: 873,
    FRAME_Y2: 476,
	image_file_path: null,
	rect: null,
	index: null,
	illust: null,
	friend: null,
    offsetX: null,
    offsetY: null,

	setFriend:function(friend){
		this.friend = friend;
	},
	calledUpdate:function(dx,dy,touched){
		cc.log("IllustFrame.update()");
        if( this.illust !== undefined){
          this.illust.removeFromParent();
        }
        var rect = this.rect;
        //TODO: clipAreaを定義

        this.illust = cc.Sprite.create(this.image_file_path /*, this.makeRect(index) */ );
        this.illust.setAnchorPoint(0.5,0.5);
        this.addChild( this.illust);

//        cc.log("this.currentScale, posX, posY = " + this.currentScale + ", " + posX + ", " + posY);
        this.illust.setPosition(dx , dy);
        this.scaleIllust(index);

	},
	update:function(dx,dy, touched ){

		this.dx = dx;
		this.dy = dy;

		this.offsetX -= dx;
		this.offsetY += dy;

		this.setImage();
		//cc.log("IllustFrame.update()");

		//this.offsetX = dx / this.scale;
		//this.offsetY = dy / this.scale;

		//this.setImage();

		/*

        if( this.illust !== undefined){
          this.illust.removeFromParent();
        }
        var rect;
        this.offsetX += dx,
        this.offsetY += dy,
	    */

        //this.illust = cc.Sprite.create(this.image_file_path /*, this.makeRect(index) */ );
		/*
        this.illust.setAnchorPoint(0.5,0.5);
        this.addChild( this.illust);

//        cc.log("this.currentScale, posX, posY = " + this.currentScale + ", " + posX + ", " + posY);
        this.illust.setPosition(dx , dy);
        this.scaleIllust(index);
//        this.friend.calledUpdate(dx,dy,touched);
		*/
    },
    updateScale:function(scale){
        this.illust.setScale(scale);
    },
    getCenterPoint:function(index){
      var direction =  (1.5 - index) * 2.0;
      var dx = FRAME_WIDTH/ 2.0;
      var dy = FRAME_HEIGHT / 2.0;
//      cc.log("getCenterPoint: direction = " + direction);
//      cc.log("getCenterPoint: dx, dy = " + dx + ", " + dy);
      return cc.p(dx, direction * dy);
    },

    getCenterPointToWorld:function(index){
      var point = this.getCenterPoint();
      return cc.p(this.getPosition().x + point.x, this.getPosition().y + point.y);
    },

    ctor:function (image_file_path, rect, index ) {
		cc.log("IllustFrame.ctor");
        this._super();
//        var _image_file_path = "/app_dev.php/game/download/1/105/xml";
        this.init(image_file_path, rect, index );
    },

    init:function (image_file_path, rect, index ) {
		cc.log("IllustFrame.init: image_file_path, rect, index,  = " + image_file_path + ", " + rect + ", " + index);
        var bRet = false;
        if (this._super()) {
			this.setAnchorPoint(0, 0);
			this.setPosition(0,0);
            this.offsetX = 0;
            this.offsetY = 0;
            this.image_file_path = image_file_path;
            this.index = index;
			this.scale = 0.5;

            var dis = this;

            var image = new Image();
            image.src = image_file_path;
            image.onload = function(){
                var _this = dis;
                _this.setImage(this);
            };

          bRet = true;
        }
        return bRet;
    },
    setImage:function(sender){

		// 二回目以降は不要
		if( this.originalWidth == undefined &&
			this.originalHeight == undefined &&
			sender )
		{
	        this.originalWidth = sender.width;
			this.originalHeight = sender.height;
		} else {

			// 既にある場合は削除
			this.removeChild(this.illust);
		}

        var scale = this.scale;

        var rect3 = this.getRectForClipArea(
					this.offsetX,
					this.offsetY,
					this.originalWidth,
					this.originalHeight,
					scale);

        var illust = cc.Sprite.create(this.image_file_path, rect3);

		var rect1 = cc.rect(this.FRAME_X,this.FRAME_Y1,this.FRAME_WIDTH,this.FRAME_HEIGHT);
        var rect2 = cc.rect(this.FRAME_X,this.FRAME_Y2,this.FRAME_WIDTH,this.FRAME_HEIGHT);

        this.addChild(illust);

        switch(this.index){
            case 1:
                this.setPosition(this.FRAME_X,this.FRAME_Y1);
                this.rect = rect1;
                break;
            case 2:
                this.setPosition(this.FRAME_X,this.FRAME_Y2);
                this.rect = rect2;
        }

        var cx = this.FRAME_WIDTH  / 2;
        var cy = this.FRAME_HEIGHT / 2;
//            illust.setTextureRect(rect3);
        illust.setPosition(cx,cy);

		// 拡大率の微調整
		var new_scale;

		if( rect3.width > rect3.height ){

	        new_scale = this.FRAME_WIDTH / rect3.width;
		} else {
	        new_scale = this.FRAME_HEIGHT / rect3.height;
		}
		illust.setScale(new_scale);

        this.illust = illust;
    },

    //スプライトをカットするための領域を取得
    getRectForClipArea:function(offsetX, offsetY,  orgWidth, orgHeight, scale){

		cc.log("offsetX : " + offsetX + " offsetY : " + offsetY);

		scale = scale + 0.5;

		var cw = this.FRAME_WIDTH / scale;
		var ch = this.FRAME_HEIGHT / scale;

		var ocw = orgWidth / scale;
		var och = orgHeight / scale;

		var cx = offsetX / scale;
		var cy = offsetY / scale;

		// 読み取りエラーを無くす処理
		if ( cw > orgWidth || ch > orgHeight ){
			cw = ocw;
			ch = och;
		}

		// 左右の上限、下限の設定
		if(cw + cx > orgWidth){
			cx = orgWidth - cw;
			this.offsetX += this.dx;
		} else if(cx < 0){
			cx = 0;
			this.offsetX = 0;
		}

		// 上下の上限、下限の設定
		if(ch + cy > orgHeight){
			cy = orgHeight - ch;
			this.offsetY -= this.dy;
		} else if( cy < 0){
			cy = 0;
			this.offsetY = 0;
		}

		return cc.rect( cx , cy , cw, ch);

    },
    getScale:function(){
        return this.illust.getScale();
    }
});
<commit_msg>表示範囲の不具合修正<commit_after>var IllustFrame = cc.Layer.extend({
    FRAME_WIDTH: 607,
    FRAME_HEIGHT: 387,
    FRAME_X: 58,
    FRAME_Y1: 873,
    FRAME_Y2: 476,
	image_file_path: null,
	rect: null,
	index: null,
	illust: null,
	friend: null,
    offsetX: null,
    offsetY: null,

	setFriend:function(friend){
		this.friend = friend;
	},
	calledUpdate:function(dx,dy,touched){
		cc.log("IllustFrame.update()");
        if( this.illust !== undefined){
          this.illust.removeFromParent();
        }
        var rect = this.rect;
        //TODO: clipAreaを定義

        this.illust = cc.Sprite.create(this.image_file_path /*, this.makeRect(index) */ );
        this.illust.setAnchorPoint(0.5,0.5);
        this.addChild( this.illust);

//        cc.log("this.currentScale, posX, posY = " + this.currentScale + ", " + posX + ", " + posY);
        this.illust.setPosition(dx , dy);
        this.scaleIllust(index);

	},
	update:function(dx,dy, touched ){

		this.dx = dx;
		this.dy = dy;

		this.offsetX -= dx;
		this.offsetY += dy;

		this.setImage();
		//cc.log("IllustFrame.update()");

		//this.offsetX = dx / this.scale;
		//this.offsetY = dy / this.scale;

		//this.setImage();

		/*

        if( this.illust !== undefined){
          this.illust.removeFromParent();
        }
        var rect;
        this.offsetX += dx,
        this.offsetY += dy,
	    */

        //this.illust = cc.Sprite.create(this.image_file_path /*, this.makeRect(index) */ );
		/*
        this.illust.setAnchorPoint(0.5,0.5);
        this.addChild( this.illust);

//        cc.log("this.currentScale, posX, posY = " + this.currentScale + ", " + posX + ", " + posY);
        this.illust.setPosition(dx , dy);
        this.scaleIllust(index);
//        this.friend.calledUpdate(dx,dy,touched);
		*/
    },
    updateScale:function(scale){
        this.illust.setScale(scale);
    },
    getCenterPoint:function(index){
      var direction =  (1.5 - index) * 2.0;
      var dx = FRAME_WIDTH/ 2.0;
      var dy = FRAME_HEIGHT / 2.0;
//      cc.log("getCenterPoint: direction = " + direction);
//      cc.log("getCenterPoint: dx, dy = " + dx + ", " + dy);
      return cc.p(dx, direction * dy);
    },

    getCenterPointToWorld:function(index){
      var point = this.getCenterPoint();
      return cc.p(this.getPosition().x + point.x, this.getPosition().y + point.y);
    },

    ctor:function (image_file_path, rect, index ) {
		cc.log("IllustFrame.ctor");
        this._super();
//        var _image_file_path = "/app_dev.php/game/download/1/105/xml";
        this.init(image_file_path, rect, index );
    },

    init:function (image_file_path, rect, index ) {
		cc.log("IllustFrame.init: image_file_path, rect, index,  = " + image_file_path + ", " + rect + ", " + index);
        var bRet = false;
        if (this._super()) {
			this.setAnchorPoint(0, 0);
			this.setPosition(0,0);
            this.offsetX = 0;
            this.offsetY = 0;
            this.image_file_path = image_file_path;
            this.index = index;
			this.scale = 0.5;

            var dis = this;

            var image = new Image();
            image.src = image_file_path;
            image.onload = function(){
                var _this = dis;
                _this.setImage(this);
            };

          bRet = true;
        }
        return bRet;
    },
    setImage:function(sender){

		// 二回目以降は不要
		if( this.originalWidth == undefined &&
			this.originalHeight == undefined &&
			sender )
		{
	        this.originalWidth = sender.width;
			this.originalHeight = sender.height;
		} else {

			// 既にある場合は削除
			this.removeChild(this.illust);
		}

        var scale = this.scale;

        var rect3 = this.getRectForClipArea(
					this.offsetX,
					this.offsetY,
					this.originalWidth,
					this.originalHeight,
					scale);

        var illust = cc.Sprite.create(this.image_file_path, rect3);

		var rect1 = cc.rect(this.FRAME_X,this.FRAME_Y1,this.FRAME_WIDTH,this.FRAME_HEIGHT);
        var rect2 = cc.rect(this.FRAME_X,this.FRAME_Y2,this.FRAME_WIDTH,this.FRAME_HEIGHT);

        this.addChild(illust);

        switch(this.index){
            case 1:
                this.setPosition(this.FRAME_X,this.FRAME_Y1);
                this.rect = rect1;
                break;
            case 2:
                this.setPosition(this.FRAME_X,this.FRAME_Y2);
                this.rect = rect2;
        }

        var cx = this.FRAME_WIDTH  / 2;
        var cy = this.FRAME_HEIGHT / 2;
//            illust.setTextureRect(rect3);
        illust.setPosition(cx,cy);

		// 拡大率の微調整
		var new_scale;

		if( Math.round(this.FRAME_WIDTH / this.FRAME_HEIGHT)
				!=  Math.round(rect3.width / rect3.height) ){
			new_scale = scale;
		} else if (rect3.width / rect3.height){
	        new_scale = this.FRAME_WIDTH  / rect3.width;
		} else {
	        new_scale = this.FRAME_HEIGHT / rect3.height;
		}
		illust.setScale( new_scale );

        this.illust = illust;
    },

    //スプライトをカットするための領域を取得
    getRectForClipArea:function(offsetX, offsetY,  orgWidth, orgHeight, scale){

		scale = scale + 0.5;

		var cw = this.FRAME_WIDTH / scale;
		var ch = this.FRAME_HEIGHT / scale;

		var ocw = orgWidth / scale;
		var och = orgHeight / scale;

		var cx = offsetX / scale;
		var cy = offsetY / scale;

		// 読み取りエラーを無くす処理
		if ( cw > orgWidth || ch > orgHeight ){

			cw = ocw;
			ch = och;
		}

		// 左右の上限、下限の設定
		if(cw + cx > orgWidth){
			cx = orgWidth - cw;
			this.offsetX += this.dx;
		} else if(cx < 0){
			cx = 0;
			this.offsetX = 0;
		}

		// 上下の上限、下限の設定
		if(ch + cy > orgHeight){
			cy = orgHeight - ch;
			this.offsetY -= this.dy;
		} else if( cy < 0){
			cy = 0;
			this.offsetY = 0;
		}

		return cc.rect( cx , cy , cw, ch);

    },
    getScale:function(){
        return this.illust.getScale();
    }
});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "Wh<commit_msg>Updated the readme again<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "Wha<|endoftext|>


<commit_before>module.exports = function(fileName) {

	"use strict";

	var
		//mongoose = require("mongoose"),
		modelName = require("camelcase")(fileName),
		pluralize = require('mongoose/lib/utils').toCollectionName,
		collectionName = 	pluralize(modelName),
		DataModel = require("../models/" + fileName),
		express = require("express"),
		router = express.Router();

	router.route("/" + collectionName)
		.get(function(req, res) {

			DataModel.find({}, function(err, results) {
				if (err) {
					global.logger.error(err);
					res.status(500).json(err);
					return;
				}
				res.json(results);
			});
		});

	router.route("/" + collectionName)
		.post(function(req, res) {

			var t = new DataModel(req.body);
			t.save(function(err, result) {
				if (err) {
					global.logger.error(err);
					res.status(500).json(err);
					return;
				}
				res.json(result);
			});
		});

	router.route("/" + collectionName + "/:id")
		.get(function(req, res) {
			DataModel.findById(req.params.id,
				function(err, result) {
					if (err) {
						global.logger.error(err);
						res.status(500).json(err);
						return;
					}
					res.json(result);
				});
		})
		.put(function(req, res) {
			DataModel.findByIdAndUpdate(req.params.id,
				req.body,
				function(err, result) {
					if (err) {
						global.logger.error(err);
						res.status(500).json(err);
						return;
					}
					res.json(req.body);
				});
		})
		.delete(function(req, res) {
			DataModel.findByIdAndRemove(req.params.id,
				function(err, result) {
					if (err) {
						global.logger.error(err);
						res.status(500).json(err);
						return;
					}
					res.json(result);
				});
		});

 	return router;
}
<commit_msg>tweaked rest service<commit_after>module.exports = function(fileName) {

	"use strict";

	var
		modelName = require("camelcase")(fileName),
		pluralize = require('mongoose/lib/utils').toCollectionName,
		collectionName = 	pluralize(modelName),
		DataModel = require("../models/" + fileName),
		router = require("express").Router();

	function handleResult() {
		var res = this;
		return function(err, results) {
			if (err) {
				global.logger.error(err);
				res.status(500).end();
				return;
			}
			res.json(results);
		}
	}

	router.route("/" + collectionName)
		.get(function(req, res) {
			DataModel.find({}, handleResult.call(res));
		});

	router.route("/" + collectionName)
		.post(function(req, res) {
			var t = new DataModel(req.body);
			t.save(handleResult.call(res));
		});

	router.route("/" + collectionName + "/:id")
		.get(function(req, res) {
			DataModel.findById(req.params.id, handleResult.call(res));
		})
		.put(function(req, res) {
			DataModel.findByIdAndUpdate(req.params.id, req.body, handleResult.call(res));
		})
		.delete(function(req, res) {
			DataModel.findByIdAndRemove(req.params.id, handleResult.call(res));
		});

 	return router;
}
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes",<commit_msg>Grammar fix<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", <|endoftext|>


<commit_before>'use strict';

var path = process.cwd();

module.exports = function (app) {

	app.route('/')
		.get(function (req, res) {
			res.sendFile(path + '/public/index.html');
		});
};
<commit_msg>send ipaddress, language, and software as JSON<commit_after>'use strict';

var path = process.cwd();

module.exports = function (app) {

	app.route('/')
		.get(function (req, res) {

			var data = {
				ipaddress: null,
				language: null,
				software: null
			};

			var re;

			data.ipaddress = req.ip; //express property, depends on "trust proxy" setting

			if (req.headers) {

				if (req.headers["accept-language"]){
					//refrence https://tools.ietf.org/html/rfc7231#section-5.3.1 to remove the qvalues
					re = /;(?:q=)(?:0(?:.\d\d?\d?)?|1(?:.00?0?)?)/;
					var lang = req.headers["accept-language"].replace(re, "");
					data.language = lang;
				}

				if(req.headers["user-agent"]){
					//search for (os) and extract os, else just copy user agent
					var userAgent = req.headers["user-agent"];
					re = /\((.*)\)/;
					var result = re.exec(userAgent);
					data.software = result ? result[1] : userAgent;
				}
			}

			res.json(data);
		});
};
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', ou<commit_msg>Quick fix<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', out<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catc<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch<|endoftext|>


<commit_before>import MetaHandler from '../http-request-handlers/meta.handler';
import WebHookhandler from '../http-request-handlers/webhook.handler';
import {Router} from 'express';
import settings from '../configuration';
import {Bot, Elements} from 'facebook-messenger-bot';
require('babel-polyfill');

const bot = new Bot(settings.fb.myPageToken, settings.fb.myVerification);

const routes = new Router();
const version = settings.apiVersion;

// Use fb bot framework middleware
routes.use('/facebook', bot.router());
routes.get(`${version}/meta`, MetaHandler.index);
routes.get(`${version}/webhook`, WebHookhandler.index);

bot.on('message', async message => {
    const {sender} = message;
    await sender.fetch('first_name');

    const out = new Elements();
    out.add({text: `hey ${sender.first_name}, how are you!`});

    await bot.send(sender.id, out);
});

export default routes;
<commit_msg>applies router middleware to webhook endpoint<commit_after>import MetaHandler from '../http-request-handlers/meta.handler';
import WebHookhandler from '../http-request-handlers/webhook.handler';
import {Router} from 'express';
import settings from '../configuration';
import {Bot, Elements} from 'facebook-messenger-bot';
require('babel-polyfill');

const bot = new Bot(settings.fb.myPageToken, settings.fb.myVerification);

const routes = new Router();
const version = settings.apiVersion;

// Use fb bot framework middleware
routes.use(`${version}/webhook`, bot.router());
routes.get(`${version}/meta`, MetaHandler.index);
routes.get(`${version}/webhook`, WebHookhandler.index);

bot.on('message', async message => {
    const {sender} = message;
    await sender.fetch('first_name');

    const out = new Elements();
    out.add({text: `hey ${sender.first_name}, how are you!`});

    await bot.send(sender.id, out);
});

export default routes;
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  con<commit_msg>Five bullets or six?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  cons<|endoftext|>


<commit_before>'use strict';

var User = require('../models/users');
var Poll = require('../models/polls');
var Choice = require('../models/choices');

var path = process.cwd();
var PollHandler = require(path + '/app/controllers/pollHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var pollHandler = new PollHandler();

	app.route('/')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
				res.render('index',{poll:poll});
			})
		});

	app.route('/login')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
			res.render('login',{poll:poll, layout:'loggedout'});
			})
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile/:id')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				console.log(user);
				res.render('profile',{user:user, time:Date.now()});
			})
		});

	app.route('/createpoll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('createpoll');
			})
		});

	app.route('/poll')
		.post(isLoggedIn, function (req, res) {
			console.log(req.body);
			var newpoll = {question : req.body.question};
			newpoll.choices = {};
			var choices = req.body.choices.split(',');
			choices.forEach(function(item) {
				newpoll.choices[item]=0;
			})
			newpoll.creator = req.user._id;
			console.log(newpoll);
			Poll.create(newpoll, function(err, poll) {
				if (err) {
					console.log(err);
				}
			User.findById(req.user._id, function(err, user){
				console.log(user);
				user.polls.push(poll._id);
    			user.save();
				res.redirect('/poll/' + poll._id);
			});
			});
		});

	app.route('/poll/:id/addchoices')
		.post(function (req, res) {
			var newchoices = {};
			var choices = req.body.choices.split(',');
			choices.forEach(function(item) {
				newchoices[item]=0;
			});
			Poll.findById(req.params.id, function(err, poll) {
			var idquery= { _id: req.params.id };
			newchoices = Object.assign(poll.choices, newchoices);
			console.log(newchoices);
			poll.update({ choices: newchoices });
			poll.markModified('choices');
			poll.save();
				res.redirect('/poll/' + poll._id);
});
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render("profile",{user:req.user});
		});

	app.route('/poll/:id')
		.get(function (req, res) {
			Poll.findById(req.params.id, function(err, poll){
				console.log(poll.choices);
				res.render("poll",{
					poll:poll,
				});
			})
		})
		.delete(function (req, res) {
			console.log(req.params);
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll);
				if (poll) {
					poll.remove();
				};
			User.findById(req.user._id, function(err, user){
				console.log(user);
				var index = user.polls.indexOf(req.params.id);
				console.log(index);
				if (index > -1) {
    				user.polls.splice(index, 1);
    				user.save();
				}
				res.redirect('/profile');
			})
			})
		})
		.post(function (req, res) {
			console.log(req.body);
			if (req.body.choice) {
				Poll.findOne({"_id": req.params.id}, function(err, poll) {
					poll.choices[req.body.choice]++;
					console.log(poll);
					poll.markModified('choices');
					poll.save();
					res.redirect('/poll/' + poll._id);
				})
			}
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/auth/twitter')
		.get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/success')
		.get(function (req, res) {
		res.render('success');
		});

};
<commit_msg>displaying polls<commit_after>'use strict';

var User = require('../models/users');
var Poll = require('../models/polls');

var path = process.cwd();
var PollHandler = require(path + '/app/controllers/pollHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var pollHandler = new PollHandler();

	app.route('/')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
				res.render('index',{poll:poll});
			})
		});

	app.route('/login')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
			res.render('login',{poll:poll, layout:'loggedout'});
			})
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile/:id')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				console.log(user);
				res.render('profile',{user:user, time:Date.now()});
			})
		});

	app.route('/createpoll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('createpoll');
			})
		});

	app.route('/poll')
		.post(isLoggedIn, function (req, res) {
			console.log(req.body);
			var newpoll = {question : req.body.question};
			newpoll.choices = {};
			var choices = req.body.choices.split(',');
			choices.forEach(function(item) {
				newpoll.choices[item]=0;
			})
			newpoll.creator = req.user._id;
			console.log(newpoll);
			Poll.create(newpoll, function(err, poll) {
				if (err) {
					console.log(err);
				}
			User.findById(req.user._id, function(err, user){
				console.log(user);
				user.polls.push(poll._id);
    			user.save();
				res.redirect('/poll/' + poll._id);
			});
			});
		});

	app.route('/poll/:id/addchoices')
		.post(function (req, res) {
			var newchoices = {};
			var choices = req.body.choices.split(',');
			choices.forEach(function(item) {
				newchoices[item]=0;
			});
			Poll.findById(req.params.id, function(err, poll) {
			var idquery= { _id: req.params.id };
			newchoices = Object.assign(poll.choices, newchoices);
			console.log(newchoices);
			poll.update({ choices: newchoices });
			poll.markModified('choices');
			poll.save();
				res.redirect('/poll/' + poll._id);
});
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render("profile",{user:req.user});
		});

	app.route('/poll/:id')
		.get(function (req, res) {
			Poll.findById(req.params.id, function(err, poll){
				console.log(poll.choices);
				res.render("poll",{
					poll:poll,
				});
			})
		})
		.delete(function (req, res) {
			console.log(req.params);
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll);
				if (poll) {
					poll.remove();
				};
			User.findById(req.user._id, function(err, user){
				console.log(user);
				var index = user.polls.indexOf(req.params.id);
				console.log(index);
				if (index > -1) {
    				user.polls.splice(index, 1);
    				user.save();
				}
				res.redirect('/profile');
			})
			})
		})
		.post(function (req, res) {
			console.log(req.body);
			if (req.body.choice) {
				Poll.findOne({"_id": req.params.id}, function(err, poll) {
					poll.choices[req.body.choice]++;
					console.log(poll);
					poll.markModified('choices');
					poll.save();
					res.redirect('/poll/' + poll._id);
				})
			}
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/auth/twitter')
		.get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/success')
		.get(function (req, res) {
		res.render('success');
		});

};
<|endoftext|>