<commit_before>(function ($) {

   var UDBrains = function () {
      return new UDBrains.fn.init();
   }

   UDBrains.fn = UDBrains.prototype = {
      version: 2.0,
      reportURL: 'http://localhost:8989/',
      surroundings: {
         inside: false,
         position: [],
         map: [],
      },
      user: {
         name: "",
         id: 0
      },
      UI: {},
      init: function () {
         var udb = this;
         $(document).ready(function () {
            udb.populateSurroundings();
            udb.populateUser();
            //udb.sendReport();
            $(udb).trigger('ready', [this]);
            udb.renderUI();
         });
         return this;
      },

      populateUser: function () {
         var playerInfo = $('.cp .gt');
         $.extend(this.user, {
            name:       playerInfo.find('a[href^=profile]').text(),
            id:         playerInfo.find('a[href^=profile]').attr('href').split('=')[1],
            alive:      playerInfo.text().search(/you are dead/) == -1 ? true : false,
            health:     playerInfo.text().match(/You have (\d+) Hit Points?/)[1],
            ap:         playerInfo.text().match(/You have (\d+) Action Points?/)[1],
            experience: playerInfo.text().match(/and (\d+) Experience Points?/)[1],
            inventory:  []
         });
         var udb = this;
         $('select[name=drop] option[value!=""]').each(function () {
            udb.user.inventory.push({
               id:   $(this).val(),
               name: $(this).text()
            });
         });

      },

      populateSurroundings: function () {
         var udb = this;
         this.surroundings.inside = this.isInside();
         $('table.c tr:has(td.b)').each(function (row) {
            udb.surroundings.map.push([]);
            $(this).find('td.b').each(function (col) {
               udb.surroundings.map[row].push({
                  element:          this,
                  coords:           udb.getCoordsFromMapTile(this),
                  zombies:          udb.getZombieCountFromMapTile(this),
                  survivors:        udb.getSurvivorsFromMapTile(this),
                  ruined:           udb.isMapTileRuined(this),
                  illuminated:      udb.isMapTileLit(this)
               });
               // Note the coordinates of our position in relation to surroundings.
               if(udb.isPositionElement(this))
                  udb.surroundings.position = udb.surroundings.map[row][udb.surroundings.map[row].length-1];
            });
            // Current position specific data.
            $.extend(udb.surroundings.position, {
               barricades:       udb.getBarricadeLevel(),
               christmasTree:    udb.hasXmasTree()
            });
         });
      },

      hasXmasTree: function () {
        /*
         A recently-cut fir tree has been propped up in a crude stand. The bar has been decorated with a historical tapestry and a carved pumpkin.
        */
        return ($('.gp .gt').text().search(/A recently-cut fir tree/) != -1);
      },

      isPositionElement: function (elem) {
         // Position element has input with no form.
         return $(elem).is('td:has(>input)');
      },

      isInside: function () {
         //Check for the leave button to determine if we're inside a building.
         return ($('.gp form[action$=out]').length == 1);
      },

      isOutsideBuilding: function () {
         //Check for the enter button to see if we're outside a building.
         return ($('.gp form[action$=in]').length == 1);
      },

      isEmptyLot: function () {
         //Returns true if current tile is empty lot
         return (!this.isInside() && !this.isOutsideBuilding());
      },

      isMapTileRuined: function (elem) {
         //.mr = ruined or inside dark
         if(this.isPositionElement(elem)){
            return false;//fucking special cases
         } else {
            return $(elem).find('input[type=submit]').hasClass('mr');
         }
      },

      isMapTileLit: function (elem) {
         //.ml = lit tile
         //.mrl = ruined + powered
         var button = $(elem).find('input[type=submit]');
         return ( button.hasClass('ml') || button.hasClass('mrl') );
      },

      isHPDataAvailable: function () {
         return ( $('.gp .gt sub').length != 0 );
      },

      getCoordsFromMapTile: function (elem) {
         // Parse out the coordinates for the provided tile.
         var coords;
         if (this.isPositionElement(elem)) {
            // Player position has to be calculated from a nearby tile.
            coords = this.calculatePositionCoords(elem);
         } else {
            coords = this.parseCoords($(elem).find('input[type=hidden]').val());
         }
         return coords;
      },

      calculatePositionCoords: function (elem) {
         var locationTD = $('table.c td:has(>input)'); //Location TD always has an input without a form.
         var locationRow = locationTD.parent().find('td');
         var xOffset = 1;
         var offsetTDIndex = 0;
         if (locationRow.index(elem) == 0) {//We are at the left edge of the map.
            xOffset = -1;
            offsetTDIndex = 1;
         }
         var offset = this.parseCoords(
            // Get the coordinates of the tile to our left/right
            locationRow.eq(offsetTDIndex).find('input[type=hidden]').val()
         );
         return {
            x: offset.x + xOffset,
            y: offset.y
         }
      },

      parseCoords: function (coords) {
         coords = coords.split('-');
         return {
            x: parseInt(coords[0], 10),
            y: parseInt(coords[1], 10)
         }
      },

      getSurvivorsFromMapTile: function (elem) {
         //Returns an array of objects with survivor names and ids.
         var survivors = [];
         var survivorLinks = $(elem).find('a[href^=profile]');
         if (this.isPositionElement(elem)) {
            // If the query is for our current position we can provide a full list.
            survivorLinks = $('.gp .gt a');
         }
         var udb = this;
         survivorLinks.each(function (i) {
            survivors.push({
               name: $(this).text(),
               id:   $(this).attr('href').split('=')[1]
            })
            if (udb.isPositionElement(elem) && udb.isHPDataAvailable()) {
               survivors[i].hp = udb.getHPDataForSurvivor(survivors[i]);
            }
         });
         return survivors;
      },

      getHPDataForSurvivor: function (survivor) {
         var reg = new RegExp( survivor.name + "\\s\\((\\d+)HP\\)" );
         return $('.gp .gt').text().match(reg)[1];
      },

      getZombieCountFromMapTile: function (elem) {
         if($(elem).is('td:has(.fz)'))
            return parseInt($(elem).find('.fz').text().split(' ')[0], 10);
         else
            return 0;
      },

      getBarricadeLevel: function () {
         var reg = /The (building|doors to the street|building\'s doors) (has|have) been ([^\.]*(secured|barricaded|left wide open))[^\.]*./;
         if (this.isEmptyLot())
            var barricadeText = 'no building';
         else
            var barricadeText = $('.gp .gt').text().match(reg);
         return this.barricadeLevels[barricadeText ? barricadeText[3] : 0];
      },

      getLocationByCoord: function (locx, locy) {
         var location = false;
         $.each(this.surroundings, function () {
            $.each(this, function () {
               if (this.coords.x == locx && this.coords.y == locy)
                  location = this;
            });
         });
         return location;
      },

      sendReport: function () {
         //Copy the surroundings object so we can prune some of the data off of it.
         var surroundings = $.extend({}, this.surroundings);
         surroundings.map = surroundings.map.map(function (row) {
            return row.map(function (col) {
               delete col.element;
               return col;
            });
         });
         $.ajax({
            type: "POST",
            url: this.reportURL,
            data: {data: JSON.stringify({user: this.user, surroundings: surroundings})},
            dataType: 'json',
            success: this.receiveReport
         });
      },

      receiveReport: function (data, status, xhr) {
         //placeholder
      },

      barricadeLevels: {
         'no building':                      0,
         'left wide open' :                  1,
         'secured' :                         2,
         'loosely barricaded' :              3,
         'lightly barricaded' :              4,
         'quite strongly barricaded' :       5,
         'very strongly barricaded' :        6,
         'heavily barricaded' :              7,
         'very heavily barricaded' :         8,
         'extremely heavily barricaded' :    9
      },

      renderUI: function () {
         for( ext in this.UI ) {

            this.UI[ext].init(this);
         }
      }

   }

   UDBrains.fn.init.prototype = UDBrains.fn;

   UDBrains.UI = UDBrains.fn.UI;

   UDBrains.UI.ordersPane = {
      url: 'http://brains.somethingdead.com/orders/',
      init: function (udb) {
         var iframe = $('<iframe>').attr('id', 'orders').attr('src', this.url).css({
            width: '100%',
            height: '200px',
            border: '4px solid #445544'
         });
         var ordersLink = $('<a>').attr('href', '#orders').bind('click', function () {
            localStorage.ordersVisible = $('#orders').toggle().is(':visible');
         }).text('Click here to toggle orders.');
         $('.gp').append(ordersLink);
         $('.gp').append(iframe);
         if (localStorage.ordersVisible == "false")
            iframe.hide();
      }
   }

   UDBrains.UI.colorNames = {
      init: function (udb) {
          var ids = udb.surroundings.position.survivors.map(function (survivor) {
             return survivor.id;
          });

          ids.push(udb.user.id);

          $.post('http://brains.somethingdead.com/names/colors/', {players:ids}, function (data) {
              $.each(data, function (index, elem) {
                 $('a[href="profile.cgi?id=' + elem.id + '"]').css('color', elem.color_code);
              });
          }, 'json');
      }
   }

   UDBrains.UI.suburbTitle = {
      mapURL: 'http://map.aypok.co.uk/index.php?suburb=',
      init: function (udb) {
         var coords = udb.surroundings.position.coords;
         var link = $('<a>').attr('href', this.mapURL+this.calculateSuburb(coords.x, coords.y));
         link.attr('target', '_blank');
         $('.sb').append(' - ['+coords.x+','+coords.y+']').wrapInner(link);
      },
      calculateSuburb: function (x,y) {
         return Math.ceil((x+1)/10) + Math.floor(y/10) * 10;
      }
   }

   UDBrains.UI.mibbit = {
       channelURL: 'http://01.chat.mibbit.com/?server=irc.synirc.net&channel=%23urbandead',
       init: function (udb) {
           var header = $('<h2>');
           var link = $('<a>').attr('href', this.channelURL).attr('target', '_blank')
           link.text('Come hang out on IRC!');
           link.appendTo(header);
           header.insertBefore('.gp .gt');
       }
   }

   UDBrains = window.UDBrains = UDBrains();

})(jQuery);<commit_msg>Add the link inside the main message box, looks better in my opinion.<commit_after>(function ($) {

   var UDBrains = function () {
      return new UDBrains.fn.init();
   }

   UDBrains.fn = UDBrains.prototype = {
      version: 2.0,
      reportURL: 'http://localhost:8989/',
      surroundings: {
         inside: false,
         position: [],
         map: [],
      },
      user: {
         name: "",
         id: 0
      },
      UI: {},
      init: function () {
         var udb = this;
         $(document).ready(function () {
            udb.populateSurroundings();
            udb.populateUser();
            //udb.sendReport();
            $(udb).trigger('ready', [this]);
            udb.renderUI();
         });
         return this;
      },

      populateUser: function () {
         var playerInfo = $('.cp .gt');
         $.extend(this.user, {
            name:       playerInfo.find('a[href^=profile]').text(),
            id:         playerInfo.find('a[href^=profile]').attr('href').split('=')[1],
            alive:      playerInfo.text().search(/you are dead/) == -1 ? true : false,
            health:     playerInfo.text().match(/You have (\d+) Hit Points?/)[1],
            ap:         playerInfo.text().match(/You have (\d+) Action Points?/)[1],
            experience: playerInfo.text().match(/and (\d+) Experience Points?/)[1],
            inventory:  []
         });
         var udb = this;
         $('select[name=drop] option[value!=""]').each(function () {
            udb.user.inventory.push({
               id:   $(this).val(),
               name: $(this).text()
            });
         });

      },

      populateSurroundings: function () {
         var udb = this;
         this.surroundings.inside = this.isInside();
         $('table.c tr:has(td.b)').each(function (row) {
            udb.surroundings.map.push([]);
            $(this).find('td.b').each(function (col) {
               udb.surroundings.map[row].push({
                  element:          this,
                  coords:           udb.getCoordsFromMapTile(this),
                  zombies:          udb.getZombieCountFromMapTile(this),
                  survivors:        udb.getSurvivorsFromMapTile(this),
                  ruined:           udb.isMapTileRuined(this),
                  illuminated:      udb.isMapTileLit(this)
               });
               // Note the coordinates of our position in relation to surroundings.
               if(udb.isPositionElement(this))
                  udb.surroundings.position = udb.surroundings.map[row][udb.surroundings.map[row].length-1];
            });
            // Current position specific data.
            $.extend(udb.surroundings.position, {
               barricades:       udb.getBarricadeLevel(),
               christmasTree:    udb.hasXmasTree()
            });
         });
      },

      hasXmasTree: function () {
        /*
         A recently-cut fir tree has been propped up in a crude stand. The bar has been decorated with a historical tapestry and a carved pumpkin.
        */
        return ($('.gp .gt').text().search(/A recently-cut fir tree/) != -1);
      },

      isPositionElement: function (elem) {
         // Position element has input with no form.
         return $(elem).is('td:has(>input)');
      },

      isInside: function () {
         //Check for the leave button to determine if we're inside a building.
         return ($('.gp form[action$=out]').length == 1);
      },

      isOutsideBuilding: function () {
         //Check for the enter button to see if we're outside a building.
         return ($('.gp form[action$=in]').length == 1);
      },

      isEmptyLot: function () {
         //Returns true if current tile is empty lot
         return (!this.isInside() && !this.isOutsideBuilding());
      },

      isMapTileRuined: function (elem) {
         //.mr = ruined or inside dark
         if(this.isPositionElement(elem)){
            return false;//fucking special cases
         } else {
            return $(elem).find('input[type=submit]').hasClass('mr');
         }
      },

      isMapTileLit: function (elem) {
         //.ml = lit tile
         //.mrl = ruined + powered
         var button = $(elem).find('input[type=submit]');
         return ( button.hasClass('ml') || button.hasClass('mrl') );
      },

      isHPDataAvailable: function () {
         return ( $('.gp .gt sub').length != 0 );
      },

      getCoordsFromMapTile: function (elem) {
         // Parse out the coordinates for the provided tile.
         var coords;
         if (this.isPositionElement(elem)) {
            // Player position has to be calculated from a nearby tile.
            coords = this.calculatePositionCoords(elem);
         } else {
            coords = this.parseCoords($(elem).find('input[type=hidden]').val());
         }
         return coords;
      },

      calculatePositionCoords: function (elem) {
         var locationTD = $('table.c td:has(>input)'); //Location TD always has an input without a form.
         var locationRow = locationTD.parent().find('td');
         var xOffset = 1;
         var offsetTDIndex = 0;
         if (locationRow.index(elem) == 0) {//We are at the left edge of the map.
            xOffset = -1;
            offsetTDIndex = 1;
         }
         var offset = this.parseCoords(
            // Get the coordinates of the tile to our left/right
            locationRow.eq(offsetTDIndex).find('input[type=hidden]').val()
         );
         return {
            x: offset.x + xOffset,
            y: offset.y
         }
      },

      parseCoords: function (coords) {
         coords = coords.split('-');
         return {
            x: parseInt(coords[0], 10),
            y: parseInt(coords[1], 10)
         }
      },

      getSurvivorsFromMapTile: function (elem) {
         //Returns an array of objects with survivor names and ids.
         var survivors = [];
         var survivorLinks = $(elem).find('a[href^=profile]');
         if (this.isPositionElement(elem)) {
            // If the query is for our current position we can provide a full list.
            survivorLinks = $('.gp .gt a');
         }
         var udb = this;
         survivorLinks.each(function (i) {
            survivors.push({
               name: $(this).text(),
               id:   $(this).attr('href').split('=')[1]
            })
            if (udb.isPositionElement(elem) && udb.isHPDataAvailable()) {
               survivors[i].hp = udb.getHPDataForSurvivor(survivors[i]);
            }
         });
         return survivors;
      },

      getHPDataForSurvivor: function (survivor) {
         var reg = new RegExp( survivor.name + "\\s\\((\\d+)HP\\)" );
         return $('.gp .gt').text().match(reg)[1];
      },

      getZombieCountFromMapTile: function (elem) {
         if($(elem).is('td:has(.fz)'))
            return parseInt($(elem).find('.fz').text().split(' ')[0], 10);
         else
            return 0;
      },

      getBarricadeLevel: function () {
         var reg = /The (building|doors to the street|building\'s doors) (has|have) been ([^\.]*(secured|barricaded|left wide open))[^\.]*./;
         if (this.isEmptyLot())
            var barricadeText = 'no building';
         else
            var barricadeText = $('.gp .gt').text().match(reg);
         return this.barricadeLevels[barricadeText ? barricadeText[3] : 0];
      },

      getLocationByCoord: function (locx, locy) {
         var location = false;
         $.each(this.surroundings, function () {
            $.each(this, function () {
               if (this.coords.x == locx && this.coords.y == locy)
                  location = this;
            });
         });
         return location;
      },

      sendReport: function () {
         //Copy the surroundings object so we can prune some of the data off of it.
         var surroundings = $.extend({}, this.surroundings);
         surroundings.map = surroundings.map.map(function (row) {
            return row.map(function (col) {
               delete col.element;
               return col;
            });
         });
         $.ajax({
            type: "POST",
            url: this.reportURL,
            data: {data: JSON.stringify({user: this.user, surroundings: surroundings})},
            dataType: 'json',
            success: this.receiveReport
         });
      },

      receiveReport: function (data, status, xhr) {
         //placeholder
      },

      barricadeLevels: {
         'no building':                      0,
         'left wide open' :                  1,
         'secured' :                         2,
         'loosely barricaded' :              3,
         'lightly barricaded' :              4,
         'quite strongly barricaded' :       5,
         'very strongly barricaded' :        6,
         'heavily barricaded' :              7,
         'very heavily barricaded' :         8,
         'extremely heavily barricaded' :    9
      },

      renderUI: function () {
         for( ext in this.UI ) {

            this.UI[ext].init(this);
         }
      }

   }

   UDBrains.fn.init.prototype = UDBrains.fn;

   UDBrains.UI = UDBrains.fn.UI;

   UDBrains.UI.ordersPane = {
      url: 'http://brains.somethingdead.com/orders/',
      init: function (udb) {
         var iframe = $('<iframe>').attr('id', 'orders').attr('src', this.url).css({
            width: '100%',
            height: '200px',
            border: '4px solid #445544'
         });
         var ordersLink = $('<a>').attr('href', '#orders').bind('click', function () {
            localStorage.ordersVisible = $('#orders').toggle().is(':visible');
         }).text('Click here to toggle orders.');
         $('.gp').append(ordersLink);
         $('.gp').append(iframe);
         if (localStorage.ordersVisible == "false")
            iframe.hide();
      }
   }

   UDBrains.UI.colorNames = {
      init: function (udb) {
          var ids = udb.surroundings.position.survivors.map(function (survivor) {
             return survivor.id;
          });

          ids.push(udb.user.id);

          $.post('http://brains.somethingdead.com/names/colors/', {players:ids}, function (data) {
              $.each(data, function (index, elem) {
                 $('a[href="profile.cgi?id=' + elem.id + '"]').css('color', elem.color_code);
              });
          }, 'json');
      }
   }

   UDBrains.UI.suburbTitle = {
      mapURL: 'http://map.aypok.co.uk/index.php?suburb=',
      init: function (udb) {
         var coords = udb.surroundings.position.coords;
         var link = $('<a>').attr('href', this.mapURL+this.calculateSuburb(coords.x, coords.y));
         link.attr('target', '_blank');
         $('.sb').append(' - ['+coords.x+','+coords.y+']').wrapInner(link);
      },
      calculateSuburb: function (x,y) {
         return Math.ceil((x+1)/10) + Math.floor(y/10) * 10;
      }
   }

   UDBrains.UI.mibbit = {
       channelURL: 'http://01.chat.mibbit.com/?server=irc.synirc.net&channel=%23urbandead',
       init: function (udb) {
           var header = $('<h2>');
           var link = $('<a>').attr('href', this.channelURL).attr('target', '_blank')
           link.text('Come hang out on IRC!');
           link.appendTo(header);
           header.prependTo('.gp .gt');
       }
   }

   UDBrains = window.UDBrains = UDBrains();

})(jQuery);<|endoftext|>


<commit_before>import {copyFiles} from "./steps/copy-files";
import {modifyFiles} from "./steps/modify-files";
import {removeServices} from "./steps/remove-services";

import {
    SERVICES
} from "../../config";

export async function initCommand(lambdaName, organizationName, selectedServices) {
    await copyFiles();
    await modifyFiles(lambdaName, organizationName);
    await removeServices(selectedServices);
}

export default async function wrappedInitCommand() {

    const lambda = await this.prompt({
        type: "input",
        name: "name",
        message: "Enter your lambda name: ",
    });

    console.log(lambda);

    const organization = await this.prompt({
        type: "input",
        name: "name",
        message: "Enter your organization name: ",
    });

    console.log(organization);

    const services = await this.prompt({
        type: "checkbox",
        "message": "Select services: ",
        "name": "selected",
        choices: SERVICES
    });

    console.log(services);

    await initCommand(lambda.name, organization, services);
}
<commit_msg>Fixed prompts<commit_after>import {copyFiles} from "./steps/copy-files";
import {modifyFiles} from "./steps/modify-files";
import {removeServices} from "./steps/remove-services";

import {
    SERVICES
} from "../../config";

export async function initCommand(lambdaName, organizationName, selectedServices) {
    await copyFiles();
    await modifyFiles(lambdaName, organizationName);
    await removeServices(selectedServices);
}

export default async function wrappedInitCommand() {

    const lambda = await this.prompt({
        type: "input",
        name: "name",
        message: "Enter your lambda name: ",
    });

    console.log(lambda);

    const organization = await this.prompt({
        type: "input",
        name: "name",
        message: "Enter your organization name: ",
    });

    console.log(organization);

    const services = await this.prompt({
        type: "checkbox",
        "message": "Select services: ",
        "name": "selected",
        choices: SERVICES
    });

    console.log(services);

    await initCommand(lambda.name, organization.name, services.selected);
}
<|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', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileS<commit_msg>Fixing a typo added in the last readme update<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', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSy<|endoftext|>


<commit_before>const r = require("rethinkdb");
const meta = require("./meta.json");
const data = require("./data.json");

module.exports = function (message) {
	//Split message into keywords
	let input = message.content.replace(/\n/g, "").split(" ");

	//If there is no input, send a list of languages
	if (!input[2]) {
		let print = typeof meta[message.data.lang] != "undefined" && meta[message.data.lang].message_choose_lang || "message_choose_lang";
		let langs = [];
		print += "\n```\n"
		Object.keys(data.languages).forEach(function(item) {
			langs.push(data.languages[message.data.lang][item]);
		});

		print += langs.join(`, `);
		print += "```";
		return message.reply(print);
	}

	console.dir(input);

	if(!data.languages[message.data.lang]) return message.reply(typeof meta[message.data.lang] != "undefined" && meta[message.data.lang].err_not_found || "err_not_found");

	//ONLY EXCEPTION FOR LANGUAGE
	//Gets the language code from the message,
	//as it is the one that was just set by
	//the (l)user
	message.reply(typeof meta[input[2]] != "undefined" && meta[input[2]].success_found || "success_found");

	r.table("users").insert({
		id: message.member.id,
		lang: input[2]
	},{
		conflict: "replace"
	}).run(message.client.rethonk);
}
<commit_msg>log item<commit_after>const r = require("rethinkdb");
const meta = require("./meta.json");
const data = require("./data.json");

module.exports = function (message) {
	//Split message into keywords
	let input = message.content.replace(/\n/g, "").split(" ");

	//If there is no input, send a list of languages
	if (!input[2]) {
		let print = typeof meta[message.data.lang] != "undefined" && meta[message.data.lang].message_choose_lang || "message_choose_lang";
		let langs = [];
		print += "\n```\n"
		Object.keys(data.languages).forEach(function(item) {
			console.log(item);
			langs.push(data.languages[message.data.lang][item]);
		});

		print += langs.join(`, `);
		print += "```";
		return message.reply(print);
	}

	console.dir(input);

	if(!data.languages[message.data.lang]) return message.reply(typeof meta[message.data.lang] != "undefined" && meta[message.data.lang].err_not_found || "err_not_found");

	//ONLY EXCEPTION FOR LANGUAGE
	//Gets the language code from the message,
	//as it is the one that was just set by
	//the (l)user
	message.reply(typeof meta[input[2]] != "undefined" && meta[input[2]].success_found || "success_found");

	r.table("users").insert({
		id: message.member.id,
		lang: input[2]
	},{
		conflict: "replace"
	}).run(message.client.rethonk);
}
<|endoftext|>


<commit_before>'use strict';

// ------- Imports -------------------------------------------------------------

const test = require('ava');
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');

const Dequeuer = require('../../src/lib/Dequeuer');
const FreeFormMessage = require('../../src/messages/FreeFormMessage');
const HooksHelper = require('../helpers/HooksHelper');
const MessageFactoryHelper = require('../helpers/MessageFactoryHelper');

// ------- Init ----------------------------------------------------------------

chai.should();
chai.use(sinonChai);

// Setup blink app for each test.
test.beforeEach(HooksHelper.createRandomQueue);
test.afterEach.always(HooksHelper.destroyRandomQueue);

// ------- Tests ---------------------------------------------------------------
// Important! Test should be executed serially, because they are overriding
// same static methods on Message class.

/**
 * Dequeuer: Test class interface
 */
test.serial('Dequeuer: Test class interface', (t) => {
  const dequeuer = new Dequeuer(t.context.queue);
  dequeuer.should.respondTo('dequeue');
  dequeuer.should.respondTo('executeCallback');
  dequeuer.should.respondTo('processCallbackResult');
  dequeuer.should.respondTo('processCallbackError');
  dequeuer.should.respondTo('extractOrDiscard');
  dequeuer.should.respondTo('unpack');
  dequeuer.should.respondTo('validate');
  dequeuer.should.respondTo('log');
});

/**
 * Dequeuer: executeCallback()
 */
test.serial('Dequeuer: executeCallback() should ack successfully processed message', async (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure ack() will be called.
  const ackStub = sinon.stub(queue, 'ack').returns(null);

  // Create dequeue callback and spu on it.
  const callback = async () => true;
  const callbackSpy = sinon.spy(callback);

  // Prepare random message to make dequeur think it fot it from Rabbit.
  const message = MessageFactoryHelper.getRandomMessage();

  // Dequeue test message.
  const dequeuer = new Dequeuer(queue, callbackSpy);
  const result = await dequeuer.executeCallback(message);
  result.should.be.true;

  // Ensure callback has been called.
  callbackSpy.should.have.been.calledOnce;

  // Make sure the message has been acknowledged.
  ackStub.should.have.been.calledWith(message);

  // Cleanup.
  ackStub.restore();
});

/**
 * Dequeuer: executeCallback()
 */
test.serial('Dequeuer: executeCallback() ensure that expectedly not processed message is still acked', async (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure ack() will be called.
  const ackStub = sinon.stub(queue, 'ack').returns(null);

  // Create dequeue callback and spu on it.
  const callback = async () => false;
  const callbackSpy = sinon.spy(callback);

  // Prepare random message to make dequeur think it fot it from Rabbit.
  const message = MessageFactoryHelper.getRandomMessage();

  // Dequeue test message.
  const dequeuer = new Dequeuer(queue, callbackSpy);
  const result = await dequeuer.executeCallback(message);
  result.should.be.true;

  // Ensure callback has been called.
  callbackSpy.should.have.been.calledOnce;

  // Make sure the message has been acknowledged.
  ackStub.should.have.been.calledWith(message);

  // Cleanup.
  ackStub.restore();
});

/**
 * Dequeuer: executeCallback()
 */
test.serial('Dequeuer: executeCallback() should nack when unexpected error is thrown from callback', async (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure nack() will be called.
  const nackStub = sinon.stub(queue, 'nack').returns(null);

  // Create dequeue callback and spu on it.
  const callback = async () => {
    throw new Error('Testing unexpected exception from worker callback');
  };
  const callbackSpy = sinon.spy(callback);

  // Prepare random message to make dequeur think it fot it from Rabbit.
  const message = MessageFactoryHelper.getRandomMessage();

  // Dequeue test message.
  const dequeuer = new Dequeuer(queue, callbackSpy);
  const result = await dequeuer.executeCallback(message);
  result.should.be.false;

  // Ensure callback has been called.
  callbackSpy.should.have.been.calledOnce;

  // Ensure the message has been nacked.
  nackStub.should.have.been.calledWith(message);

  // Cleanup.
  nackStub.restore();
});

/**
 * Dequeuer: extractOrDiscard() incorrect json.
 */
test.serial('Dequeuer: extractOrDiscard() should nack message with incorrect JSON payload', (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure nack() will be called.
  const nackStub = sinon.stub(queue, 'nack').returns(null);

  // Ensure Message.fromRabbitMessage throws MessageParsingBlinkError
  const blinkParsingErrorSpy = sinon.spy(queue.messageClass, 'parseIncomingPayload');

  // Create deliberaly incorrect JSON and feed it to extractOrDiscard.
  const rabbitMessage = MessageFactoryHelper.getFakeRabbitMessage('{incorrect-json}');
  const dequeuer = new Dequeuer(queue);
  const result = dequeuer.extractOrDiscard(rabbitMessage);
  result.should.be.false;

  // Ensure the message been nacked.
  nackStub.should.have.been.calledOnce;

  // Ensure MessageParsingBlinkError has been thrown.
  blinkParsingErrorSpy.should.have.thrown('MessageParsingBlinkError');

  // Cleanup.
  nackStub.restore();
  blinkParsingErrorSpy.restore();
});

/**
 * Dequeuer: extractOrDiscard() unknown error.
 */
test.serial('Dequeuer: extractOrDiscard() should nack message on unknown unpack error', (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure nack() will be called.
  const nackStub = sinon.stub(queue, 'nack').returns(null);

  // Simulate unknown error in Message.fromRabbitMessage().
  // This method is static so we can stub it on Message constructor itself.
  const fromRabbitMessageStub = sinon.stub(queue.messageClass, 'fromRabbitMessage');
  fromRabbitMessageStub.throws(() => {
    // Fake unexpected error thrown from Message.fromRabbitMessage().
    const error = new Error('Testing unexpected exception from Message.fromRabbitMessage()');
    return error;
  });

  // Create random valid message.
  // It will be successfully unpacked from JSON,  but discarded anyways
  //  because we've overridden Message.fromRabbitMessage().
  const message = MessageFactoryHelper.getRandomMessage();
  const rabbitMessage = MessageFactoryHelper.getFakeRabbitMessage(message.toString());

  const dequeuer = new Dequeuer(queue);
  const result = dequeuer.extractOrDiscard(rabbitMessage);
  result.should.be.false;

  // Ensure the message been nacked.
  nackStub.should.have.been.calledOnce;

  // Cleanup.
  nackStub.restore();
  fromRabbitMessageStub.restore();
});

/**
 * Dequeuer: extractOrDiscard() nack invalid message.
 */
test.serial('Dequeuer: extractOrDiscard() should nack invalid message', (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure nack() will be called.
  const nackStub = sinon.stub(queue, 'nack').returns(null);

  // Create invalid message (data expected to be an object)
  // and ensure it has been rejected with MessageValidationBlinkError.
  const invalidMessage = new FreeFormMessage({
    data: [],
    meta: {},
  });
  const validateSpy = sinon.spy(invalidMessage, 'validate');

  // Feed invalid message to Dequeuer.
  const rabbitMessage = MessageFactoryHelper.getFakeRabbitMessage(invalidMessage.toString());
  const dequeuer = new Dequeuer(queue);

  // Stub Dequeuer.unpack() to make it return message we actually spy on.
  const unpackStub = sinon.stub(dequeuer, 'unpack');
  unpackStub.callsFake(() => invalidMessage);

  const result = dequeuer.extractOrDiscard(rabbitMessage);
  result.should.be.false;

  // Ensure the message been nacked.
  nackStub.should.have.been.calledOnce;

  // Ensure MessageValidationBlinkError has been thrown.
  validateSpy.should.have.thrown('MessageValidationBlinkError');

  // Cleanup.
  nackStub.restore();
  validateSpy.restore();
  unpackStub.restore();
});

// ------- End -----------------------------------------------------------------
<commit_msg>After proper test cleanup tests should be able to run concurrently<commit_after>'use strict';

// ------- Imports -------------------------------------------------------------

const test = require('ava');
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');

const Dequeuer = require('../../src/lib/Dequeuer');
const FreeFormMessage = require('../../src/messages/FreeFormMessage');
const HooksHelper = require('../helpers/HooksHelper');
const MessageFactoryHelper = require('../helpers/MessageFactoryHelper');

// ------- Init ----------------------------------------------------------------

chai.should();
chai.use(sinonChai);

// Setup blink app for each test.
test.beforeEach(HooksHelper.createRandomQueue);
test.afterEach.always(HooksHelper.destroyRandomQueue);

// ------- Tests ---------------------------------------------------------------

/**
 * Dequeuer: Test class interface
 */
test('Dequeuer: Test class interface', (t) => {
  const dequeuer = new Dequeuer(t.context.queue);
  dequeuer.should.respondTo('dequeue');
  dequeuer.should.respondTo('executeCallback');
  dequeuer.should.respondTo('processCallbackResult');
  dequeuer.should.respondTo('processCallbackError');
  dequeuer.should.respondTo('extractOrDiscard');
  dequeuer.should.respondTo('unpack');
  dequeuer.should.respondTo('validate');
  dequeuer.should.respondTo('log');
});

/**
 * Dequeuer: executeCallback()
 */
test('Dequeuer: executeCallback() should ack successfully processed message', async (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure ack() will be called.
  const ackStub = sinon.stub(queue, 'ack').returns(null);

  // Create dequeue callback and spu on it.
  const callback = async () => true;
  const callbackSpy = sinon.spy(callback);

  // Prepare random message to make dequeur think it fot it from Rabbit.
  const message = MessageFactoryHelper.getRandomMessage();

  // Dequeue test message.
  const dequeuer = new Dequeuer(queue, callbackSpy);
  const result = await dequeuer.executeCallback(message);
  result.should.be.true;

  // Ensure callback has been called.
  callbackSpy.should.have.been.calledOnce;

  // Make sure the message has been acknowledged.
  ackStub.should.have.been.calledWith(message);

  // Cleanup.
  ackStub.restore();
});

/**
 * Dequeuer: executeCallback()
 */
test('Dequeuer: executeCallback() ensure that expectedly not processed message is still acked', async (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure ack() will be called.
  const ackStub = sinon.stub(queue, 'ack').returns(null);

  // Create dequeue callback and spu on it.
  const callback = async () => false;
  const callbackSpy = sinon.spy(callback);

  // Prepare random message to make dequeur think it fot it from Rabbit.
  const message = MessageFactoryHelper.getRandomMessage();

  // Dequeue test message.
  const dequeuer = new Dequeuer(queue, callbackSpy);
  const result = await dequeuer.executeCallback(message);
  result.should.be.true;

  // Ensure callback has been called.
  callbackSpy.should.have.been.calledOnce;

  // Make sure the message has been acknowledged.
  ackStub.should.have.been.calledWith(message);

  // Cleanup.
  ackStub.restore();
});

/**
 * Dequeuer: executeCallback()
 */
test('Dequeuer: executeCallback() should nack when unexpected error is thrown from callback', async (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure nack() will be called.
  const nackStub = sinon.stub(queue, 'nack').returns(null);

  // Create dequeue callback and spu on it.
  const callback = async () => {
    throw new Error('Testing unexpected exception from worker callback');
  };
  const callbackSpy = sinon.spy(callback);

  // Prepare random message to make dequeur think it fot it from Rabbit.
  const message = MessageFactoryHelper.getRandomMessage();

  // Dequeue test message.
  const dequeuer = new Dequeuer(queue, callbackSpy);
  const result = await dequeuer.executeCallback(message);
  result.should.be.false;

  // Ensure callback has been called.
  callbackSpy.should.have.been.calledOnce;

  // Ensure the message has been nacked.
  nackStub.should.have.been.calledWith(message);

  // Cleanup.
  nackStub.restore();
});

/**
 * Dequeuer: extractOrDiscard() incorrect json.
 */
test('Dequeuer: extractOrDiscard() should nack message with incorrect JSON payload', (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure nack() will be called.
  const nackStub = sinon.stub(queue, 'nack').returns(null);

  // Ensure Message.fromRabbitMessage throws MessageParsingBlinkError
  const blinkParsingErrorSpy = sinon.spy(queue.messageClass, 'parseIncomingPayload');

  // Create deliberaly incorrect JSON and feed it to extractOrDiscard.
  const rabbitMessage = MessageFactoryHelper.getFakeRabbitMessage('{incorrect-json}');
  const dequeuer = new Dequeuer(queue);
  const result = dequeuer.extractOrDiscard(rabbitMessage);
  result.should.be.false;

  // Ensure the message been nacked.
  nackStub.should.have.been.calledOnce;

  // Ensure MessageParsingBlinkError has been thrown.
  blinkParsingErrorSpy.should.have.thrown('MessageParsingBlinkError');

  // Cleanup.
  nackStub.restore();
  blinkParsingErrorSpy.restore();
});

/**
 * Dequeuer: extractOrDiscard() unknown error.
 */
test('Dequeuer: extractOrDiscard() should nack message on unknown unpack error', (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure nack() will be called.
  const nackStub = sinon.stub(queue, 'nack').returns(null);

  // Simulate unknown error in Message.fromRabbitMessage().
  // This method is static so we can stub it on Message constructor itself.
  const fromRabbitMessageStub = sinon.stub(queue.messageClass, 'fromRabbitMessage');
  fromRabbitMessageStub.throws(() => {
    // Fake unexpected error thrown from Message.fromRabbitMessage().
    const error = new Error('Testing unexpected exception from Message.fromRabbitMessage()');
    return error;
  });

  // Create random valid message.
  // It will be successfully unpacked from JSON,  but discarded anyways
  //  because we've overridden Message.fromRabbitMessage().
  const message = MessageFactoryHelper.getRandomMessage();
  const rabbitMessage = MessageFactoryHelper.getFakeRabbitMessage(message.toString());

  const dequeuer = new Dequeuer(queue);
  const result = dequeuer.extractOrDiscard(rabbitMessage);
  result.should.be.false;

  // Ensure the message been nacked.
  nackStub.should.have.been.calledOnce;

  // Cleanup.
  nackStub.restore();
  fromRabbitMessageStub.restore();
});

/**
 * Dequeuer: extractOrDiscard() nack invalid message.
 */
test('Dequeuer: extractOrDiscard() should nack invalid message', (t) => {
  const queue = t.context.queue;
  // Override queue method to ensure nack() will be called.
  const nackStub = sinon.stub(queue, 'nack').returns(null);

  // Create invalid message (data expected to be an object)
  // and ensure it has been rejected with MessageValidationBlinkError.
  const invalidMessage = new FreeFormMessage({
    data: [],
    meta: {},
  });
  const validateSpy = sinon.spy(invalidMessage, 'validate');

  // Feed invalid message to Dequeuer.
  const rabbitMessage = MessageFactoryHelper.getFakeRabbitMessage(invalidMessage.toString());
  const dequeuer = new Dequeuer(queue);

  // Stub Dequeuer.unpack() to make it return message we actually spy on.
  const unpackStub = sinon.stub(dequeuer, 'unpack');
  unpackStub.callsFake(() => invalidMessage);

  const result = dequeuer.extractOrDiscard(rabbitMessage);
  result.should.be.false;

  // Ensure the message been nacked.
  nackStub.should.have.been.calledOnce;

  // Ensure MessageValidationBlinkError has been thrown.
  validateSpy.should.have.thrown('MessageValidationBlinkError');

  // Cleanup.
  nackStub.restore();
  validateSpy.restore();
  unpackStub.restore();
});

// ------- End -----------------------------------------------------------------
<|endoftext|>


<commit_before>va<commit_msg>Updated the readme again<commit_after>var<|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<commit_msg>You feeling lucky punk?<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.<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var chance = require('./fake-extension'); // TODO: Can I just import chance and have this wired up differently
var moment = require('moment');
var glimpse = require('glimpse');

var rawRequestCache = {};
var detailsRetrievedCache = {};

var requestProcessor = {
    requests: {
        summary: function(rawRequests) {
            var requests = _.map(rawRequests, 'request');

            return {
                newRequests: requests,
                updatedRequests: [],
                affectedRequests: requests
            };
        },
        detail: function(rawRequest) {
            var requests = [ rawRequest.request ];

            return {
                newRequests: requests,
                updatedRequests: [],
                affectedRequests: requests
            };
        }
    },
    messages: {
        summary: function(rawRequests) {
            var messages = [];
            _.forEach(rawRequests, function(request) {
                _.forEach(request.messages, function(message) {
                    if (!_.isEmpty(message.index) || !_.isEmpty(message.abstract)) {
                        messages.push(message);
                    }
                });
            });

            return messages;
        },
        detail: function(rawRequest) {
            return rawRequest.messages;
        }
    }
};

// simulate summaries
var triggerGetLastestSummaries = (function () {
    var maxEvents = chance.integerRange(25, 35);
    var leftEvents = maxEvents;

    var batch = (function() {
        var calculateOffset = function(seconds) {
            var date = new Date();
            var value = seconds * 1000;

            return moment(date.setTime(date.getTime() + value)).toISOString();
        };

        var generateResults = function(count, offset) {
            var results = [];
            for (var i = 0; i < count; i++) {
                offset -= chance.integerRange(30, 300);

                var dateTime = calculateOffset(offset);
                var result = chance.mvcRequest(dateTime);

                results.push(result);
            }

            return results;
        };
        var cacheResults = function(rawResults) {
            _.forEach(rawResults, function(rawResult) {
                rawRequestCache[rawResult.id] = rawResult;
            });
        };
        var publishResults = function(rawResults, publishAction, messageType, messageSource) {
            var results = publishAction(rawResults);

            glimpse.emit('data.' + messageType + '.summary.found.' + messageSource, results);
        };

        return function(count, messageType, messageSource, offset, publishAction) {
            leftEvents -= parseInt(count);

            console.log('[fake] ' + messageType + ':' + messageSource + ' - ' + (maxEvents - leftEvents) + ' of ' + maxEvents + ' (' + leftEvents + ' left, ' + parseInt(count) + ' just rendered)');

            var rawResults = generateResults(count, offset);
            cacheResults(rawResults);
            publishResults(rawResults, publishAction, messageType, messageSource);
        };
    })();

    var generate = {
        local: function () {
            // simulate requests happening more than a day ago
            batch(maxEvents * 0.25, 'request', 'local', 25 * 60 * 60 * -1, requestProcessor.requests.summary);
        },
        remote: function () {
            // simulate messages happening more than 10 seconds ago
            batch(maxEvents * 0.3, 'message', 'remote', 10 * -1, requestProcessor.messages.summary);
        },
        stream: function (position) {
            // simulate message happening now and possibly coming in at the same time
            var count = chance.integerRange(0, 100) > 75 ? 2 : 1;
            batch(count, 'message', 'stream', 0, requestProcessor.messages.summary);

            // lets make more happen
            setTimeout(function () {
                if (position < leftEvents) {
                    generate.stream(position + count);
                }
            }, chance.integerRange(500, 15000));
        }
    };

    return function () {
        // simulate requests from local store
        setTimeout(function () {
            generate.local();
        }, chance.integerRange(50, 100));

        // simulate messages from remote
        setTimeout(function () {
            generate.remote();
        }, chance.integerRange(2000, 2500));

        // simulate messages from stream
        setTimeout(function () {
            generate.stream(0);
        }, chance.integerRange(4000, 6000));
    };
})();

// simulate details
var triggerGetDetailsFor = (function () {
    var requestsFound = function(messageType, messageSource, results) {
        glimpse.emit('data.' + messageType + '.detail.found.' + messageSource, results);
    }

    var modifyForSummaryRequest = function(request) {

    }

    var generate = {
        local: function (id) {
            var rawRequest = detailsRetrievedCache[id];

            if (!rawRequest) {
                // simulate returning the summary of the request object that we have
                // in reality we would always have this, but its good to make the
                // system more pesimistic than not
                if (chance.integerRange(1, 2) > 1) {
                    rawRequest = _.clone(rawRequestCache[id], true);
                    rawRequest.request.tabs = undefined;

                }
            }

            if (rawRequest) {
                requestsFound('request', 'local', requestProcessor.requests.detail(rawRequest));
            }
        },
        remote: function (id) {
            // TODO: Should probably throw an exeption if record not found
            var rawRequest = rawRequestCache[id];
            if (rawRequest) {
                // store it for next time to help simulate local storeage caching
                detailsRetrievedCache[id] = rawRequest;

                requestsFound('message', 'remote', requestProcessor.messages.detail(rawRequest));
            }
            else {
                throw new TypeError('Shouldnt be trying to find a detail that we dont have a summary for');
            }
        }
    };

    return function (id) {
        // simulate messages from local store
        setTimeout(function () {
            generate.local(id);
        }, chance.integerRange(10, 50));

        // simulate messages from remote
        setTimeout(function () {
            generate.remote(id);
        }, chance.integerRange(2000, 3000));
    };
})();

// hook up listeners
(function () {
    function requestReady() {
        triggerGetLastestSummaries();
    }

    glimpse.on('shell.request.ready', requestReady);
})();

(function () {
    function detailRequested(payload) {
        triggerGetDetailsFor(payload.requestId);
    }

    glimpse.on('data.request.detail.requested', detailRequested);
})();
<commit_msg>Fix bug around how many fake stream requests are generated<commit_after>'use strict';

var _ = require('lodash');
var chance = require('./fake-extension'); // TODO: Can I just import chance and have this wired up differently
var moment = require('moment');
var glimpse = require('glimpse');

var rawRequestCache = {};
var detailsRetrievedCache = {};

var requestProcessor = {
    requests: {
        summary: function(rawRequests) {
            var requests = _.map(rawRequests, 'request');

            return {
                newRequests: requests,
                updatedRequests: [],
                affectedRequests: requests
            };
        },
        detail: function(rawRequest) {
            var requests = [ rawRequest.request ];

            return {
                newRequests: requests,
                updatedRequests: [],
                affectedRequests: requests
            };
        }
    },
    messages: {
        summary: function(rawRequests) {
            var messages = [];
            _.forEach(rawRequests, function(request) {
                _.forEach(request.messages, function(message) {
                    if (!_.isEmpty(message.index) || !_.isEmpty(message.abstract)) {
                        messages.push(message);
                    }
                });
            });

            return messages;
        },
        detail: function(rawRequest) {
            return rawRequest.messages;
        }
    }
};

// simulate summaries
var triggerGetLastestSummaries = (function () {
    var maxEvents = chance.integerRange(25, 35);
    var leftEvents = maxEvents;

    var batch = (function() {
        var calculateOffset = function(seconds) {
            var date = new Date();
            var value = seconds * 1000;

            return moment(date.setTime(date.getTime() + value)).toISOString();
        };

        var generateResults = function(count, offset) {
            var results = [];
            for (var i = 0; i < count; i++) {
                offset -= chance.integerRange(30, 300);

                var dateTime = calculateOffset(offset);
                var result = chance.mvcRequest(dateTime);

                results.push(result);
            }

            return results;
        };
        var cacheResults = function(rawResults) {
            _.forEach(rawResults, function(rawResult) {
                rawRequestCache[rawResult.id] = rawResult;
            });
        };
        var publishResults = function(rawResults, publishAction, messageType, messageSource) {
            var results = publishAction(rawResults);

            glimpse.emit('data.' + messageType + '.summary.found.' + messageSource, results);
        };

        return function(count, messageType, messageSource, offset, publishAction) {
            leftEvents -= parseInt(count);

            console.log('[fake] ' + messageType + ':' + messageSource + ' - ' + (maxEvents - leftEvents) + ' of ' + maxEvents + ' (' + leftEvents + ' left, ' + parseInt(count) + ' just rendered)');

            var rawResults = generateResults(count, offset);
            cacheResults(rawResults);
            publishResults(rawResults, publishAction, messageType, messageSource);
        };
    })();

    var generate = {
        local: function () {
            // simulate requests happening more than a day ago
            batch(maxEvents * 0.25, 'request', 'local', 25 * 60 * 60 * -1, requestProcessor.requests.summary);
        },
        remote: function () {
            // simulate messages happening more than 10 seconds ago
            batch(maxEvents * 0.3, 'message', 'remote', 10 * -1, requestProcessor.messages.summary);
        },
        stream: function (position) {
            // simulate message happening now and possibly coming in at the same time
            var count = chance.integerRange(0, 100) > 75 ? 2 : 1;
            batch(count, 'message', 'stream', 0, requestProcessor.messages.summary);

            // lets make more happen
            setTimeout(function () {
                if (leftEvents > 0) {
                    generate.stream(position + count);
                }
            }, chance.integerRange(500, 15000));
        }
    };

    return function () {
        // simulate requests from local store
        setTimeout(function () {
            generate.local();
        }, chance.integerRange(50, 100));

        // simulate messages from remote
        setTimeout(function () {
            generate.remote();
        }, chance.integerRange(2000, 2500));

        // simulate messages from stream
        setTimeout(function () {
            generate.stream(0);
        }, chance.integerRange(4000, 6000));
    };
})();

// simulate details
var triggerGetDetailsFor = (function () {
    var requestsFound = function(messageType, messageSource, results) {
        glimpse.emit('data.' + messageType + '.detail.found.' + messageSource, results);
    }

    var modifyForSummaryRequest = function(request) {

    }

    var generate = {
        local: function (id) {
            var rawRequest = detailsRetrievedCache[id];

            if (!rawRequest) {
                // simulate returning the summary of the request object that we have
                // in reality we would always have this, but its good to make the
                // system more pesimistic than not
                if (chance.integerRange(1, 2) > 1) {
                    rawRequest = _.clone(rawRequestCache[id], true);
                    rawRequest.request.tabs = undefined;

                }
            }

            if (rawRequest) {
                requestsFound('request', 'local', requestProcessor.requests.detail(rawRequest));
            }
        },
        remote: function (id) {
            // TODO: Should probably throw an exeption if record not found
            var rawRequest = rawRequestCache[id];
            if (rawRequest) {
                // store it for next time to help simulate local storeage caching
                detailsRetrievedCache[id] = rawRequest;

                requestsFound('message', 'remote', requestProcessor.messages.detail(rawRequest));
            }
            else {
                throw new TypeError('Shouldnt be trying to find a detail that we dont have a summary for');
            }
        }
    };

    return function (id) {
        // simulate messages from local store
        setTimeout(function () {
            generate.local(id);
        }, chance.integerRange(10, 50));

        // simulate messages from remote
        setTimeout(function () {
            generate.remote(id);
        }, chance.integerRange(2000, 3000));
    };
})();

// hook up listeners
(function () {
    function requestReady() {
        triggerGetLastestSummaries();
    }

    glimpse.on('shell.request.ready', requestReady);
})();

(function () {
    function detailRequested(payload) {
        triggerGetDetailsFor(payload.requestId);
    }

    glimpse.on('data.request.detail.requested', detailRequested);
})();
<|endoftext|>


<commit_before>export default {
  isoName: 'cs',
  nativeName: 'Čeština',
  label: {
    clear: 'Smazat',
    ok: 'OK',
    cancel: 'Zrušit',
    close: 'Zavřít',
    set: 'Hotovo',
    select: 'Vybrat',
    reset: 'Reset',
    remove: 'Odebrat',
    update: 'Hotovo',
    create: 'Vytvořit',
    search: 'Hledat',
    filter: 'Filtrovat',
    refresh: 'Obnovit'
  },
  date: {
    days: 'Neděle_Pondělí_Úterý_Středa_Čtvrtek_Pátek_Sobota'.split('_'),
    daysShort: 'Ne_Po_Út_St_Čt_Pá_So'.split('_'),
    months: 'Leden_Únor_Březen_Duben_Květen_Červen_Červenec_Srpen_Září_Říjen_Listopad_Prosinec'.split(
      '_'),
    monthsShort: 'Led_Úno_Bře_Dub_Kvě_Čvn_Čvc_Srp_Zář_Říj_Lis_Pro'.split('_'),
    firstDayOfWeek: 1, // 0-6, 0 - Sunday, 1 Monday, ...
    format24h: true
  },
  table: {
    noData: 'Žádná data k dispozici',
    noResults: 'Nebyly nalezeny žádné odpovídající záznamy',
    loading: 'Načítá se...',
    selectedRecords: function (rows) {
      switch (rows) {
        case 0:
          return 'Nejsou vybrány žádné řádky.'
        case 1:
          return 'Vybrán 1 řádek.'
        case 2:
          return 'Vybrány 2 řádky.'
        case 3:
          return 'Vybrány 3 řádky.'
        case 4:
          return 'Vybrány 4 řádky.'
      }
      return ('Vybráno ' + rows + ' řádků.')
    },
    recordsPerPage: 'Počet řádků na stránku:',
    allRows: 'Všechny',
    pagination: function (start, end, total) {
      return start + '-' + end + ' z ' + total
    },
    columns: 'Sloupce'
  },
  editor: {
    url: 'URL',
    bold: 'Tučně',
    italic: 'Kurzíva',
    strikethrough: 'Přeškrtnuté',
    underline: 'Podtržené',
    unorderedList: 'Odrážkový seznam',
    orderedList: 'Číslovaný seznam',
    subscript: 'Dolní index',
    superscript: 'Horní index',
    hyperlink: 'Odkaz',
    toggleFullscreen: 'Přepnout zobrazení na celou obrazovku',
    quote: 'Bloková citace',
    left: 'Zarovnat vlevo',
    center: 'Zarovnat na střed',
    right: 'Zarovnat vpravo',
    justify: 'Zarovnat do bloku',
    print: 'Tisk',
    outdent: 'Zmenšit odsazení',
    indent: 'Zvětšit odsazení',
    removeFormat: 'Vymazat formátování',
    formatting: 'Styl',
    fontSize: 'Velikost písma',
    align: 'Zarovnání',
    hr: 'Vložit oddělovač',
    undo: 'Zpět',
    redo: 'Znovu',
    heading1: 'Nadpis 1',
    heading2: 'Nadpis 2',
    heading3: 'Nadpis 3',
    heading4: 'Nadpis 4',
    heading5: 'Nadpis 5',
    heading6: 'Nadpis 6',
    paragraph: 'Odstavec',
    code: 'Kód',
    size1: 'Velmi malé',
    size2: 'Malé',
    size3: 'Normální',
    size4: 'Středně velké',
    size5: 'Velké',
    size6: 'Velmi velké',
    size7: 'Maximum',
    defaultFont: 'Výchozí písmo',
    viewSource: 'Zobrazit zdroj'
  },
  tree: {
    noNodes: 'Žádné uzly',
    noResults: 'Žádné odpovídající uzly nenalezeny'
  }
}
<commit_msg>[ui]Chzech translation updated (#5653)<commit_after>export default {
  isoName: 'cs',
  nativeName: 'Čeština',
  label: {
    clear: 'Smazat',
    ok: 'OK',
    cancel: 'Zrušit',
    close: 'Zavřít',
    set: 'Nastavit',
    select: 'Vybrat',
    reset: 'Reset',
    remove: 'Odebrat',
    update: 'Opravit',
    create: 'Vytvořit',
    search: 'Hledat',
    filter: 'Filtrovat',
    refresh: 'Obnovit'
  },
  date: {
    days: 'Neděle_Pondělí_Úterý_Středa_Čtvrtek_Pátek_Sobota'.split('_'),
    daysShort: 'Ne_Po_Út_St_Čt_Pá_So'.split('_'),
    months: 'Leden_Únor_Březen_Duben_Květen_Červen_Červenec_Srpen_Září_Říjen_Listopad_Prosinec'.split(
      '_'),
    monthsShort: 'Led_Úno_Bře_Dub_Kvě_Čvn_Čvc_Srp_Zář_Říj_Lis_Pro'.split('_'),
    firstDayOfWeek: 1, // 0-6, 0 - Sunday, 1 Monday, ...
    format24h: true
  },
  table: {
    noData: 'Žádná data k dispozici',
    noResults: 'Nebyly nalezeny žádné odpovídající záznamy',
    loading: 'Načítá se...',
    selectedRecords: function (rows) {
      switch (rows) {
        case 0:
          return 'Nejsou vybrány žádné řádky.'
        case 1:
          return 'Vybrán 1 řádek.'
        case 2:
          return 'Vybrány 2 řádky.'
        case 3:
          return 'Vybrány 3 řádky.'
        case 4:
          return 'Vybrány 4 řádky.'
      }
      return ('Vybráno ' + rows + ' řádků.')
    },
    recordsPerPage: 'Počet řádků na stránku:',
    allRows: 'Všechny',
    pagination: function (start, end, total) {
      return start + '-' + end + ' z ' + total
    },
    columns: 'Sloupce'
  },
  editor: {
    url: 'URL',
    bold: 'Tučně',
    italic: 'Kurzíva',
    strikethrough: 'Přeškrtnuté',
    underline: 'Podtržené',
    unorderedList: 'Odrážkový seznam',
    orderedList: 'Číslovaný seznam',
    subscript: 'Dolní index',
    superscript: 'Horní index',
    hyperlink: 'Odkaz',
    toggleFullscreen: 'Přepnout zobrazení na celou obrazovku',
    quote: 'Bloková citace',
    left: 'Zarovnat vlevo',
    center: 'Zarovnat na střed',
    right: 'Zarovnat vpravo',
    justify: 'Zarovnat do bloku',
    print: 'Tisk',
    outdent: 'Zmenšit odsazení',
    indent: 'Zvětšit odsazení',
    removeFormat: 'Vymazat formátování',
    formatting: 'Styl',
    fontSize: 'Velikost písma',
    align: 'Zarovnání',
    hr: 'Vložit oddělovač',
    undo: 'Zpět',
    redo: 'Znovu',
    heading1: 'Nadpis 1',
    heading2: 'Nadpis 2',
    heading3: 'Nadpis 3',
    heading4: 'Nadpis 4',
    heading5: 'Nadpis 5',
    heading6: 'Nadpis 6',
    paragraph: 'Odstavec',
    code: 'Kód',
    size1: 'Velmi malé',
    size2: 'Malé',
    size3: 'Normální',
    size4: 'Středně velké',
    size5: 'Velké',
    size6: 'Velmi velké',
    size7: 'Maximum',
    defaultFont: 'Výchozí písmo',
    viewSource: 'Zobrazit zdroj'
  },
  tree: {
    noNodes: 'Žádné uzly',
    noResults: 'Žádné odpovídající uzly nenalezeny'
  }
}
<|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]")<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",
  "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]")
<|endoftext|>


<commit_before>
Object.defineConstant = function defineConstant(obj, prop, value, enumerable) {
	return Object.defineProperty(obj, prop, { value:value, enumerable:enumerable===true, writable:false, configurable:false });
};

var monkeyscript = {
	version: '0.0.0.0a',
	hooks: {},
	rc: [],
	included: []
};

(function(_native) {
	delete global._native;

	// Arguments
	var args = Array.slice(_native.arguments);
	if ( args[0] === '-h' ) {
		args.shift();
		monkeyscript.hookName = args.shift();
	} else {
		monkeyscript.scriptName = args.shift();
	}

	Object.seal(args);
	monkeyscript.arguments = args;
	global.arguments = Array.slice(args);

	global.Kernel = _native.Kernel;
	Object.seal(Kernel);

	monkeyscript.rc.push(
		Kernel.configDir + Kernel.os.fileSeparator + 'monkeyscriptrc.js',
		Kernel.configDir + Kernel.os.fileSeparator + 'monkeyscriptrc'
	);
	var baseNames = ['.monkeyscriptrc.js', '.monkeyscriptrc'];
	[
		Kernel.home,
		Kernel.currentWorkingDirectory
	].forEach(function(basePath) {
		baseNames.forEach(function(baseName) {
			monkeyscript.rc.push( basePath + Kernel.os.fileSeparator + baseName );
		});
	});
	Object.seal(monkeyscript.rc);

})(_native);

// Setup global Error objects
var IOError = Kernel.newError("IOError");

for each( let rc in monkeyscript.rc ) {
	try { include.ifExists(rc); }
	// Other errors will be printed, but still not affect running the script
	catch( e ) { print(e); }
}

if ( monkeyscript.hookName ) {
	monkeyscript.scriptName = monkeyscript.hooks[monkeyscript.hookName];
	if ( !monkeyscript.scriptName )
		Kernel.die("The hook "+monkeyscript.hookName+" does not exist");
}
if ( monkeyscript.scriptName ) {
	if ( monkeyscript.scriptName.startsWith('javascript:') )
		eval(monkeyscript.scriptName.substr('javascript:'.length));
	else
		include(monkeyscript.scriptName);
} else
	Kernel.die("No script specified");

<commit_msg>Improve handling of command line arguments<commit_after>
Object.defineConstant = function defineConstant(obj, prop, value, enumerable) {
	return Object.defineProperty(obj, prop, { value:value, enumerable:enumerable===true, writable:false, configurable:false });
};

var monkeyscript = {
	version: '0.0.0.0a',
	hooks: {},
	rc: [],
	included: []
};

(function(_native) {
	delete global._native;

	// RC Scripts
	monkeyscript.rc.push(
		Kernel.configDir + Kernel.os.fileSeparator + 'monkeyscriptrc.js',
		Kernel.configDir + Kernel.os.fileSeparator + 'monkeyscriptrc'
	);
	var baseNames = ['.monkeyscriptrc.js', '.monkeyscriptrc'];
	[
		Kernel.home,
		Kernel.currentWorkingDirectory
	].forEach(function(basePath) {
		baseNames.forEach(function(baseName) {
			monkeyscript.rc.push( basePath + Kernel.os.fileSeparator + baseName );
		});
	});

	// Arguments
	var args = Array.slice(_native.arguments);

	function handleArg(name) {
		switch(name) {
		case 'l':
		case 'lint':
			// Lint a file
			Kernel.die("MonkeyScript lint support has not been implemented yet");
			break;
		case 'i':
		case 'a': // php uses -a sortof abnormally, support it for the hell of it
		case 'interactive':
		case 'repl':
			// Run a hook
			monkeyscript.hookName = "interactive";
			handleArg.needScript = false;
			break;
		case 'h':
		case 'hook':
			// Run a hook
			monkeyscript.hookName = args.shift();
			handleArg.needScript = false;
			break;
		case 'no-rc':
			// Empty out the list of rc files
			monkeyscript.rc.clear();
			break;
		case 'rc':
			// Add a new rc file to run
			monkeyscript.rc.push(args.shift());
			break;
		default:
			Kernel.die('Unknown argument "'+name+'".');
		}
	}
	handleArg.needScript = true;
	argsloop: for(var arg;args.length;) {
		arg = args.shift();
		if ( arg === "--" ) {
			monkeyscript.scriptName = args.shift();
			break;
		} else if ( arg.length > 2 && arg.startsWith("--") ) {
			handleArg(arg.substr(2));
		} else if ( arg.length > 1 && arg.startsWith("-") ) {
			arg.substr(1).split('').forEach(handleArg);
		} else {
			if ( handleArg.needScript )
				monkeyscript.scriptName = arg;
			else
				args.unshift(arg);
			break;
		}
	}

	Object.defineProperty(monkeyscript, "arguments", { value: args, writable: false, configurable: false });
	global.arguments = Array.slice(args);

	global.Kernel = _native.Kernel;

	// Seal things
	Object.seal(args);
	Object.seal(Kernel);
	Object.seal(monkeyscript.rc);

})(_native);

// Setup global Error objects
var IOError = Kernel.newError("IOError");

for each( let rc in monkeyscript.rc ) {
	try {
		if ( rc.startsWith('javascript:') )
			eval(rc.substr('javascript:'.length));
		else
			include.ifExists(rc);
	}
	// Other errors will be printed, but still not affect running the script
	catch( e ) { print(e); }
}

if ( monkeyscript.hookName ) {
	monkeyscript.scriptName = monkeyscript.hooks[monkeyscript.hookName];
	if ( !monkeyscript.scriptName )
		Kernel.die("The hook "+monkeyscript.hookName+" does not exist");
}
if ( monkeyscript.scriptName ) {
	if ( isFunction(monkeyscript.scriptName) )
		monkeyscript.scriptName.apply(undefined, arguments);
	else if ( monkeyscript.scriptName.startsWith('javascript:') )
		eval(monkeyscript.scriptName.substr('javascript:'.length));
	else {
		if ( !Kernel.fs.exists(monkeyscript.scriptName) )
			Kernel.die("The script "+monkeyscript.scriptName+" does not exist");
		include(monkeyscript.scriptName);
	}
} else
	Kernel.die("No script specified");

<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
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

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",
  "AAAAAAAAAA<commit_msg>Found an issue with the letter 'a', so I fixed it.<commit_after>var fs = require('fs');
var child_process = require('child_process')
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

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 t<|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 require<commit_msg>Not quite working<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<|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>AAAAAAAAAAARGH!<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 = [
  "F<|endoftext|>


<commit_before>var App, container, originalTemplates;
var compile = Ember.Handlebars.compile;

module("Application Lifecycle - Component Registration", {
  setup: function() {
    originalTemplates = Ember.$.extend({}, Ember.TEMPLATES);
    Ember.TEMPLATES["components/expand-it"] = compile("
hello {{yield}}
");
    Ember.TEMPLATES.application = compile("Hello world {{#expand-it}}world{{/expand-it}}");
  },

  teardown: function() {
    Ember.run(function() {
      App.destroy();
      App = null;
      Ember.TEMPLATES = originalTemplates;
    });
  }
});

function boot(callback) {
  Ember.run(function() {
    App = Ember.Application.create({
      name: 'App',
      rootElement: '#qunit-fixture'
    });

    App.deferReadiness();

    App.Router = Ember.Router.extend({
      location: 'none'
    });

    container = App.__container__;

    if (callback) { callback(); }
  });

  var router = container.lookup('router:main');

  Ember.run(App, 'advanceReadiness');
  Ember.run(function() {
    router.handleURL('/');
  });
}

test("A helper is registered for templates under the controls/ directory", function() {
  boot();
  ok(Ember.Handlebars.helpers['expand-it'], "The helper is registered");
});

test("The helper becomes the body of the control", function() {
  boot();
  equal(Ember.$('div.ember-view > div.ember-view', '#qunit-fixture').text(), "hello world", "The control is composed correctly");
});

test("If a control is registered, it is used", function() {
  boot(function() {
    container.register('component:expand-it', Ember.Component.extend({
      classNames: 'testing123'
    }));
  });

  equal(Ember.$('div.testing123', '#qunit-fixture').text(), "hello world", "The control is composed correctly");
});
<commit_msg>Update component_registration_test.js to use component vs. control<commit_after>var App, container, originalTemplates;
var compile = Ember.Handlebars.compile;

module("Application Lifecycle - Component Registration", {
  setup: function() {
    originalTemplates = Ember.$.extend({}, Ember.TEMPLATES);
    Ember.TEMPLATES["components/expand-it"] = compile("
hello {{yield}}
");
    Ember.TEMPLATES.application = compile("Hello world {{#expand-it}}world{{/expand-it}}");
  },

  teardown: function() {
    Ember.run(function() {
      App.destroy();
      App = null;
      Ember.TEMPLATES = originalTemplates;
    });
  }
});

function boot(callback) {
  Ember.run(function() {
    App = Ember.Application.create({
      name: 'App',
      rootElement: '#qunit-fixture'
    });

    App.deferReadiness();

    App.Router = Ember.Router.extend({
      location: 'none'
    });

    container = App.__container__;

    if (callback) { callback(); }
  });

  var router = container.lookup('router:main');

  Ember.run(App, 'advanceReadiness');
  Ember.run(function() {
    router.handleURL('/');
  });
}

test("A helper is registered for templates under the components/ directory", function() {
  boot();
  ok(Ember.Handlebars.helpers['expand-it'], "The helper is registered");
});

test("The helper becomes the body of the component", function() {
  boot();
  equal(Ember.$('div.ember-view > div.ember-view', '#qunit-fixture').text(), "hello world", "The component is composed correctly");
});

test("If a component is registered, it is used", function() {
  boot(function() {
    container.register('component:expand-it', Ember.Component.extend({
      classNames: 'testing123'
    }));
  });

  equal(Ember.$('div.testing123', '#qunit-fixture').text(), "hello world", "The component is composed correctly");
});
<|endoftext|>