<commit_before>vvavarvar var fvar fsvar fs var fs =var fs = var fs = rvar fs = revar fs = reqvar fs = requvar fs = requivar fs = requirvar fs = requirevar fs = require(var fs = require('var fs = require('fvar fs = require('fsvar fs = require('fs'var fs = require('fs')var fs = require('fs');var fs = require('fs');
var fs = require('fs');
vvar fs = require('fs');
vavar fs = require('fs');
varvar fs = require('fs');
var var fs = require('fs');
var cvar fs = require('fs');
var chvar fs = require('fs');
var chivar fs = require('fs');
var chilvar fs = require('fs');
var childvar fs = require('fs');
var child_var fs = require('fs');
var child_pvar fs = require('fs');
var child_prvar fs = require('fs');
var child_provar fs = require('fs');
var child_procvar fs = require('fs');
var child_procevar fs = require('fs');
var child_procesvar fs = require('fs');
var child_processvar fs = require('fs');
var child_process var fs = require('fs');
var child_process =var fs = require('fs');
var child_process = var fs = require('fs');
var child_process = rvar fs = require('fs');
var child_process = revar fs = require('fs');
var child_process = reqvar fs = require('fs');
var child_process = requvar fs = require('fs');
var child_process = requivar fs = require('fs');
var child_process = requirvar fs = require('fs');
var child_process = requirevar fs = require('fs');
var child_process = require(var fs = require('fs');
var child_process = require('var fs = require('fs');
var child_process = require('cvar fs = require('fs');
var child_process = require('chvar fs = require('fs');
var child_process = require('chivar fs = require('fs');
var child_process = require('chilvar fs = require('fs');
var child_process = require('childvar fs = require('fs');
var child_process = require('child_var fs = require('fs');
var child_process = require('child_pvar fs = require('fs');
var child_process = require('child_prvar fs = require('fs');
var child_process = require('child_provar fs = require('fs');
var child_process = require('child_procvar fs = require('fs');
var child_process = require('child_procevar fs = require('fs');
var child_process = require('child_procesvar fs = require('fs');
var child_process = require('child_processvar fs = require('fs');
var child_process = require('child_process'var fs = require('fs');
var child_process = require('child_process')var fs = require('fs');
var child_process = require('child_process')
var fs = require('fs');
var child_process = require('child_process')

var fs = require('fs');
var child_process = require('child_process')

ivar fs = require('fs');
var child_process = require('child_process')

ifvar fs = require('fs');
var child_process = require('child_process')

if var fs = require('fs');
var child_process = require('child_process')

if (var fs = require('fs');
var child_process = require('child_process')

if ( var fs = require('fs');
var child_process = require('child_process')

if ( pvar fs = require('fs');
var child_process = require('child_process')

if ( prvar fs = require('fs');
var child_process = require('child_process')

if ( provar fs = require('fs');
var child_process = require('child_process')

if ( procvar fs = require('fs');
var child_process = require('child_process')

if ( procevar fs = require('fs');
var child_process = require('child_process')

if ( procesvar fs = require('fs');
var child_process = require('child_process')

if ( processvar fs = require('fs');
var child_process = require('child_process')

if ( process.var fs = require('fs');
var child_process = require('child_process')

if ( process.avar fs = require('fs');
var child_process = require('child_process')

if ( process.arvar fs = require('fs');
var child_process = require('child_process')

if ( process.argvar fs = require('fs');
var child_process = require('child_process')

if ( process.argvvar fs = require('fs');
var child_process = require('child_process')

if ( process.argv[var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ]var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] &var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] &&var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] && var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] && pvar fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] && pr<commit_msg>Update character<commit_after>vvavarvar var fvar fsvar fs var fs =var fs = var fs = rvar fs = revar fs = reqvar fs = requvar fs = requivar fs = requirvar fs = requirevar fs = require(var fs = require('var fs = require('fvar fs = require('fsvar fs = require('fs'var fs = require('fs')var fs = require('fs');var fs = require('fs');
var fs = require('fs');
vvar fs = require('fs');
vavar fs = require('fs');
varvar fs = require('fs');
var var fs = require('fs');
var cvar fs = require('fs');
var chvar fs = require('fs');
var chivar fs = require('fs');
var chilvar fs = require('fs');
var childvar fs = require('fs');
var child_var fs = require('fs');
var child_pvar fs = require('fs');
var child_prvar fs = require('fs');
var child_provar fs = require('fs');
var child_procvar fs = require('fs');
var child_procevar fs = require('fs');
var child_procesvar fs = require('fs');
var child_processvar fs = require('fs');
var child_process var fs = require('fs');
var child_process =var fs = require('fs');
var child_process = var fs = require('fs');
var child_process = rvar fs = require('fs');
var child_process = revar fs = require('fs');
var child_process = reqvar fs = require('fs');
var child_process = requvar fs = require('fs');
var child_process = requivar fs = require('fs');
var child_process = requirvar fs = require('fs');
var child_process = requirevar fs = require('fs');
var child_process = require(var fs = require('fs');
var child_process = require('var fs = require('fs');
var child_process = require('cvar fs = require('fs');
var child_process = require('chvar fs = require('fs');
var child_process = require('chivar fs = require('fs');
var child_process = require('chilvar fs = require('fs');
var child_process = require('childvar fs = require('fs');
var child_process = require('child_var fs = require('fs');
var child_process = require('child_pvar fs = require('fs');
var child_process = require('child_prvar fs = require('fs');
var child_process = require('child_provar fs = require('fs');
var child_process = require('child_procvar fs = require('fs');
var child_process = require('child_procevar fs = require('fs');
var child_process = require('child_procesvar fs = require('fs');
var child_process = require('child_processvar fs = require('fs');
var child_process = require('child_process'var fs = require('fs');
var child_process = require('child_process')var fs = require('fs');
var child_process = require('child_process')
var fs = require('fs');
var child_process = require('child_process')

var fs = require('fs');
var child_process = require('child_process')

ivar fs = require('fs');
var child_process = require('child_process')

ifvar fs = require('fs');
var child_process = require('child_process')

if var fs = require('fs');
var child_process = require('child_process')

if (var fs = require('fs');
var child_process = require('child_process')

if ( var fs = require('fs');
var child_process = require('child_process')

if ( pvar fs = require('fs');
var child_process = require('child_process')

if ( prvar fs = require('fs');
var child_process = require('child_process')

if ( provar fs = require('fs');
var child_process = require('child_process')

if ( procvar fs = require('fs');
var child_process = require('child_process')

if ( procevar fs = require('fs');
var child_process = require('child_process')

if ( procesvar fs = require('fs');
var child_process = require('child_process')

if ( processvar fs = require('fs');
var child_process = require('child_process')

if ( process.var fs = require('fs');
var child_process = require('child_process')

if ( process.avar fs = require('fs');
var child_process = require('child_process')

if ( process.arvar fs = require('fs');
var child_process = require('child_process')

if ( process.argvar fs = require('fs');
var child_process = require('child_process')

if ( process.argvvar fs = require('fs');
var child_process = require('child_process')

if ( process.argv[var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ]var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] &var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] &&var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] && var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] && pvar fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] && prvar fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] && pro<|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(<commit_msg>Fast-forwarding changes<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 args = ['push']
    child_process.execFileSync('<|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 i<commit_msg>Re-commiting last<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 in<|endoftext|>


<commit_before>var child_<commit_msg>Cleaned out the intertubes<commit_after>var child_p<|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.inf<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<|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 <commit_msg>Five bullets or six?<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 e<|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",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo add<commit_msg>Correcting style<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 typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",<|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",
  "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 wi<commit_msg>Work in Progress<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 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 approxim<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var EventType = new Schema({
    name: {
        required: true,
        type: String,
        trim: true,
        unique: true
    },
    priority: Number,
    field_type: {
        type: String,
        trim: true,
        enum: ['PRACTICE', 'GAME', 'TOURNAMENT', 'TRAINING', 'ALL_PURPOSE']
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('EventType', EventType);<commit_msg>moved to hard coded event types so they can be programmatically handled<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var EventType = new Schema({
    name: {
        required: true,
        type: String,
        trim: true,
        enum: ['CLINIC_SESSION', 'CLUB_TRYOUT', 'LEAGUE_GAME', 'OPEN_TRAINING', 'PRACTICE', 'STATE_CUP_GAME', 'TEAM_TRAINING', 'TEAM_TRYOUT', 'TOURNAMENT_GAME', 'PRACTICE_BID', 'ADHOC_REQUEST']
    },
    priority: Number,
    field_type: {
        type: String,
        trim: true,
        enum: ['PRACTICE', 'GAME', 'TOURNAMENT', 'TRAINING', 'ALL_PURPOSE']
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('EventType', EventType);<|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])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', o<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 (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', ou<|endoftext|>


<commit_before>// Filter out tasks that don't need to be built. Determines which tasks need to be built based on the type of build.
// If its a CI build, all tasks whose package numbers have been bumped will be built.
// If its a PR build, all tasks that have been changed will be built.
// Any other type of build will build all tasks.
var fs = require('fs');
var path = require('path');
var semver = require('semver');
var restClient = require('typed-rest-client/RestClient');
var httpHandler = require('typed-rest-client/Handlers');
var run = require('./ci-util').run;

var makeOptionsPath = path.join(__dirname, '..', 'make-options.json');
var makeOptions = JSON.parse(fs.readFileSync(makeOptionsPath).toString());

var getTasksToBuildForCI = async function() {
    // Returns a list of tasks that have different version numbers than their current published version.
    var packageInfo;
    try {
        var packageToken = process.env['PACKAGE_TOKEN'];
        if (!token) {
            console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=24;]Failed to get info from package endpoint because no token was provided. Try setting the PACKAGE_TOKEN environment variable.`);
            return makeOptions.tasks;
        }
        var handler = new httpHandler.PersonalAccessTokenCredentialHandler(packageToken);
        var client = new restClient.RestClient('azure-pipelines-tasks-ci', '', [handler]);
        var packageEndpoint = process.env['PACKAGE_ENDPOINT'];
        if (!packageEndpoint) {
            console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=24;]Failed to get info from package endpoint because no endpoint was specified. Try setting the PACKAGE_ENDPOINT environment variable.`);
            return makeOptions.tasks;
        }
        packageInfo = await client.get(packageEndpoint);
        if (packageInfo.statusCode !== 200) {
            console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=24;]Failed to get info from package endpoint, returned with status code ${packageInfo.statusCode}`);
            return makeOptions.tasks;
        }
    }
    catch (err) {
        // If unable to reach rest client, build everything.
        console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=30;]Failed to get info from package endpoint, client failed with error ${err.message}`);
        return makeOptions.tasks;
    }
    var packageMap = {};
    if(!packageInfo.result || !packageInfo.result.value) {
        console.log('##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=34;]Failed to get info from package endpoint, returned no packages');
        return makeOptions.tasks;
    }
    packageInfo.result.value.forEach(package => {
        if (package.name && package.versions) {
            var packageName = package.name.slice('Mseng.MS.TF.DistributedTask.Tasks.'.length).toLowerCase();
            packageMap[packageName] = package.versions[0].version;
            package.versions.some(versionInfo => {
                if (versionInfo.isLatest) {
                    packageMap[packageName] = versionInfo.version;
                    return true;
                }
                return false;
            });
        }
    });

    return makeOptions.tasks.filter(function (taskName) {
        var lowerCaseName = taskName.toLowerCase();
        if (lowerCaseName in packageMap) {
            var packageVersion = packageMap[lowerCaseName]

            var taskJsonPath = path.join(__dirname, '..', 'Tasks' , taskName, 'task.json')
            var taskJson = JSON.parse(fs.readFileSync(taskJsonPath).toString());
            var localVersion = `${taskJson.version.Major}.${taskJson.version.Minor}.${taskJson.version.Patch}`;

            // Build if local version and package version are different.
            return semver.neq(localVersion, packageVersion);
        }
        else {
            console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=68;]${taskName} has not been published before`);
            return true;
        }
    });
}

var getTasksDependentOnChangedCommonFiles = function(commonFilePaths) {
    // Takes in an array of filepaths that have been changed in the Tasks/Common folder, returns any tasks that could be affected.
    if (commonFilePaths.length == 0) {
        return [];
    }
    changedTasks = [];
    makeOptions.tasks.forEach(taskName => {
        var makeJsonPath = path.join(__dirname, '..', 'Tasks' , taskName, 'make.json')
        if (fs.existsSync(makeJsonPath)){
            var makeJson = JSON.parse(fs.readFileSync(makeJsonPath).toString());
            if (makeJson.common) {
                makeJson.common.forEach(commonModule => {
                    if (commonFilePaths.includes(commonModule.module.toLowerCase()) && !changedTasks.includes(taskName)) {
                        changedTasks.push(taskName);
                    }
                });
            }
        }
    });
    return changedTasks;
}

var getTasksToBuildForPR = function() {
    // Takes in a git source branch, diffs it with master, and returns a list of tasks that could have been affected by the changes.
    var sourceBranch = process.env['SYSTEM_PULLREQUEST_SOURCEBRANCH'];
    var prId = process.env['SYSTEM_PULLREQUEST_PULLREQUESTNUMBER'];
    var commonChanges = [];
    var toBeBuilt = [];
    try {
        if (sourceBranch.includes(':')) {
            // We only care about the branch name, not the source repo
            sourceBranch = sourceBranch.split(':')[1];
        }
        run('git fetch origin pull/' + prId + '/head:' + sourceBranch);
        run ('git checkout ' + sourceBranch);
    }
    catch (err) {
        // If unable to reach github, build everything.
        console.log('##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=112;]Unable to reach github, building all tasks', err);
        return makeOptions.tasks;
    }
    run('git checkout master');
    run('git --no-pager diff --name-only ' + sourceBranch + ' $(git merge-base ' + sourceBranch + ' master)')
        .split('\n')
        .forEach(filePath => {
        if (filePath.slice(0, 5) == 'Tasks') {
            var taskPath = filePath.slice(6);
            if(taskPath.slice(0, 6) == 'Common') {
                var commonName = taskPath.slice(7);
                commonChanges.push('../common/' + commonName.slice(0, commonName.indexOf('/')).toLowerCase());
            }
            else {
                var taskName = taskPath.slice(0, taskPath.indexOf('/'));
                if (!toBeBuilt.includes(taskName)) {
                    toBeBuilt.push(taskName);
                }
            }
        }
    });
    var changedTasks = getTasksDependentOnChangedCommonFiles(commonChanges);
    var shouldBeBumped = [];
    changedTasks.forEach(task => {
        if (!toBeBuilt.includes(task)) {
            shouldBeBumped.push(task);
        }
    });
    // TODO: Add this back once diffing is working 100%
//     if (shouldBeBumped.length > 0) {
//         throw new Error('The following tasks should have their versions bumped due to changes in common: ' + shouldBeBumped);
//     }
    return toBeBuilt;
}

var setTaskVariables = function(tasks) {
    console.log('tasks: ' + JSON.stringify(tasks));
    console.log('##vso[task.setVariable variable=task_pattern]@(' + tasks.join('|') + ')');
    console.log('##vso[task.setVariable variable=numTasks]' + tasks.length);
}

var buildReason = 'pullrequest';//process.env['BUILD_REASON'].toLowerCase();
var tasks;
if (buildReason == 'individualci' || buildReason == 'batchedci') {
    // If CI, we will compare any tasks that have updated versions.
    getTasksToBuildForCI().then(tasks => {
        setTaskVariables(tasks)
    });
}
else {
    if (buildReason == 'pullrequest') {
        // If PR, we will compare any tasks that could have been affected based on the diff.
        tasks = getTasksToBuildForPR();
        setTaskVariables(tasks);
    }
    else {
        // If manual or other, build everything.
        setTaskVariables(makeOptions.tasks);
    }
}
<commit_msg>Split baseCommit step out so it works on Windows<commit_after>// Filter out tasks that don't need to be built. Determines which tasks need to be built based on the type of build.
// If its a CI build, all tasks whose package numbers have been bumped will be built.
// If its a PR build, all tasks that have been changed will be built.
// Any other type of build will build all tasks.
var fs = require('fs');
var path = require('path');
var semver = require('semver');
var restClient = require('typed-rest-client/RestClient');
var httpHandler = require('typed-rest-client/Handlers');
var run = require('./ci-util').run;

var makeOptionsPath = path.join(__dirname, '..', 'make-options.json');
var makeOptions = JSON.parse(fs.readFileSync(makeOptionsPath).toString());

var getTasksToBuildForCI = async function() {
    // Returns a list of tasks that have different version numbers than their current published version.
    var packageInfo;
    try {
        var packageToken = process.env['PACKAGE_TOKEN'];
        if (!token) {
            console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=24;]Failed to get info from package endpoint because no token was provided. Try setting the PACKAGE_TOKEN environment variable.`);
            return makeOptions.tasks;
        }
        var handler = new httpHandler.PersonalAccessTokenCredentialHandler(packageToken);
        var client = new restClient.RestClient('azure-pipelines-tasks-ci', '', [handler]);
        var packageEndpoint = process.env['PACKAGE_ENDPOINT'];
        if (!packageEndpoint) {
            console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=24;]Failed to get info from package endpoint because no endpoint was specified. Try setting the PACKAGE_ENDPOINT environment variable.`);
            return makeOptions.tasks;
        }
        packageInfo = await client.get(packageEndpoint);
        if (packageInfo.statusCode !== 200) {
            console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=24;]Failed to get info from package endpoint, returned with status code ${packageInfo.statusCode}`);
            return makeOptions.tasks;
        }
    }
    catch (err) {
        // If unable to reach rest client, build everything.
        console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=30;]Failed to get info from package endpoint, client failed with error ${err.message}`);
        return makeOptions.tasks;
    }
    var packageMap = {};
    if(!packageInfo.result || !packageInfo.result.value) {
        console.log('##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=34;]Failed to get info from package endpoint, returned no packages');
        return makeOptions.tasks;
    }
    packageInfo.result.value.forEach(package => {
        if (package.name && package.versions) {
            var packageName = package.name.slice('Mseng.MS.TF.DistributedTask.Tasks.'.length).toLowerCase();
            packageMap[packageName] = package.versions[0].version;
            package.versions.some(versionInfo => {
                if (versionInfo.isLatest) {
                    packageMap[packageName] = versionInfo.version;
                    return true;
                }
                return false;
            });
        }
    });

    return makeOptions.tasks.filter(function (taskName) {
        var lowerCaseName = taskName.toLowerCase();
        if (lowerCaseName in packageMap) {
            var packageVersion = packageMap[lowerCaseName]

            var taskJsonPath = path.join(__dirname, '..', 'Tasks' , taskName, 'task.json')
            var taskJson = JSON.parse(fs.readFileSync(taskJsonPath).toString());
            var localVersion = `${taskJson.version.Major}.${taskJson.version.Minor}.${taskJson.version.Patch}`;

            // Build if local version and package version are different.
            return semver.neq(localVersion, packageVersion);
        }
        else {
            console.log(`##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=68;]${taskName} has not been published before`);
            return true;
        }
    });
}

var getTasksDependentOnChangedCommonFiles = function(commonFilePaths) {
    // Takes in an array of filepaths that have been changed in the Tasks/Common folder, returns any tasks that could be affected.
    if (commonFilePaths.length == 0) {
        return [];
    }
    changedTasks = [];
    makeOptions.tasks.forEach(taskName => {
        var makeJsonPath = path.join(__dirname, '..', 'Tasks' , taskName, 'make.json')
        if (fs.existsSync(makeJsonPath)){
            var makeJson = JSON.parse(fs.readFileSync(makeJsonPath).toString());
            if (makeJson.common) {
                makeJson.common.forEach(commonModule => {
                    if (commonFilePaths.includes(commonModule.module.toLowerCase()) && !changedTasks.includes(taskName)) {
                        changedTasks.push(taskName);
                    }
                });
            }
        }
    });
    return changedTasks;
}

var getTasksToBuildForPR = function() {
    // Takes in a git source branch, diffs it with master, and returns a list of tasks that could have been affected by the changes.
    var sourceBranch = process.env['SYSTEM_PULLREQUEST_SOURCEBRANCH'];
    var prId = process.env['SYSTEM_PULLREQUEST_PULLREQUESTNUMBER'];
    var commonChanges = [];
    var toBeBuilt = [];
    try {
        if (sourceBranch.includes(':')) {
            // We only care about the branch name, not the source repo
            sourceBranch = sourceBranch.split(':')[1];
        }
        run('git fetch origin pull/' + prId + '/head:' + sourceBranch);
        run ('git checkout ' + sourceBranch);
    }
    catch (err) {
        // If unable to reach github, build everything.
        console.log('##vso[task.logissue type=warning;sourcepath=ci/filter-task.js;linenumber=112;]Unable to reach github, building all tasks', err);
        return makeOptions.tasks;
    }
    run('git checkout master');
    var baseCommit = run('git merge-base ' + sourceBranch + ' master');
    run('git --no-pager diff --name-only ' + sourceBranch + ' ' + baseCommit)
        .split('\n')
        .forEach(filePath => {
        if (filePath.slice(0, 5) == 'Tasks') {
            var taskPath = filePath.slice(6);
            if(taskPath.slice(0, 6) == 'Common') {
                var commonName = taskPath.slice(7);
                commonChanges.push('../common/' + commonName.slice(0, commonName.indexOf('/')).toLowerCase());
            }
            else {
                var taskName = taskPath.slice(0, taskPath.indexOf('/'));
                if (!toBeBuilt.includes(taskName)) {
                    toBeBuilt.push(taskName);
                }
            }
        }
    });
    var changedTasks = getTasksDependentOnChangedCommonFiles(commonChanges);
    var shouldBeBumped = [];
    changedTasks.forEach(task => {
        if (!toBeBuilt.includes(task)) {
            shouldBeBumped.push(task);
        }
    });
    // TODO: Add this back once diffing is working 100%
//     if (shouldBeBumped.length > 0) {
//         throw new Error('The following tasks should have their versions bumped due to changes in common: ' + shouldBeBumped);
//     }
    return toBeBuilt;
}

var setTaskVariables = function(tasks) {
    console.log('tasks: ' + JSON.stringify(tasks));
    console.log('##vso[task.setVariable variable=task_pattern]@(' + tasks.join('|') + ')');
    console.log('##vso[task.setVariable variable=numTasks]' + tasks.length);
}

var buildReason = 'pullrequest';//process.env['BUILD_REASON'].toLowerCase();
var tasks;
if (buildReason == 'individualci' || buildReason == 'batchedci') {
    // If CI, we will compare any tasks that have updated versions.
    getTasksToBuildForCI().then(tasks => {
        setTaskVariables(tasks)
    });
}
else {
    if (buildReason == 'pullrequest') {
        // If PR, we will compare any tasks that could have been affected based on the diff.
        tasks = getTasksToBuildForPR();
        setTaskVariables(tasks);
    }
    else {
        // If manual or other, build everything.
        setTaskVariables(makeOptions.tasks);
    }
}
<|endoftext|>


<commit_before>var CircuitBreaker = function(opts) {
  opts = opts || {};

  this.windowDuration  = opts.windowDuration  || 10000; // milliseconds
  this.numBuckets      = opts.numBuckets      || 10;    // number
  this.timeoutDuration = opts.timeoutDuration || 3000;  // milliseconds
  this.errorThreshold  = opts.errorThreshold  || 50;    // percentage
  this.volumeThreshold = opts.volumeThreshold || 5;     // number
  this.onCircuitOpen   = opts.onCircuitOpen   || function() {};
  this.onCircuitClose   = opts.onCircuitClose || function() {};

  this._buckets = [this._createBucket()];
  this._state = CircuitBreaker.CLOSED;

  this._startTicker();
};

CircuitBreaker.OPEN = 0;
CircuitBreaker.HALF_OPEN = 1;
CircuitBreaker.CLOSED = 2;

CircuitBreaker.prototype._startTicker = function() {
  var self = this;
  var bucketIndex = 0;
  var bucketDuration = this.windowDuration / this.numBuckets;

  var tick = function() {
    if (self._buckets.length > self.numBuckets) {
      self._buckets.shift();
    }

    bucketIndex++;

    if (bucketIndex > self.numBuckets) {
      bucketIndex = 0;
      self._state = CircuitBreaker.HALF_OPEN;
    }

    self._buckets.push(self._createBucket());
  };

  window.setInterval(tick, bucketDuration);
};

CircuitBreaker.prototype._createBucket = function() {
  return { failures: 0, successes: 0, timeouts: 0, shortCircuits: 0 };
};

CircuitBreaker.prototype._lastBucket = function() {
  return this._buckets[this._buckets.length - 1];
};

CircuitBreaker.prototype._executeCommand = function(command) {
  var self = this;
  var timeout;

  var increment = function(prop) {
    return function() {
      if (!timeout) { return; }

      var bucket = self._lastBucket();
      bucket[prop]++;

      if (!self._forced) {
        self._updateState();
      }

      window.clearTimeout(timeout);
      timeout = null;
    }
  };

  timeout = window.setTimeout(increment('timeouts'), this.timeoutDuration);

  command(increment('successes'), increment('failures'));
};

CircuitBreaker.prototype._executeFallback = function(fallback) {
  fallback();

  var bucket = this._lastBucket();
  bucket.shortCircuits++;
};

CircuitBreaker.prototype._calculateMetrics = function() {
  var totalCount = 0, errorCount = 0, errorPercentage = 0;

  for (var i = 0, l = this._buckets.length; i < l; i++) {
    var bucket = this._buckets[i];
    var errors = (bucket.failures + bucket.timeouts + bucket.shortCircuits);

    errorCount += errors;
    totalCount += (errors + bucket.successes);
  }

  errorPercentage = (errorCount / (totalCount > 0 ? totalCount : 1)) * 100;

  return { totalCount: totalCount, errorCount: errorCount, errorPercentage: errorPercentage };
}

CircuitBreaker.prototype._updateState = function() {
  var metrics = this._calculateMetrics();

  if (this._state == CircuitBreaker.HALF_OPEN) {
    var lastCommandFailed = !this._lastBucket().successes && metrics.errorCount > 0;

    if (lastCommandFailed) {
      this._state = CircuitBreaker.OPEN;
    }
    else {
      this._state = CircuitBreaker.CLOSED;
      this.onCircuitClose();
    }
  }
  else {
    var overErrorThreshold = metrics.errorPercentage > this.errorThreshold;
    var overVolumeThreshold = metrics.totalCount > this.volumeThreshold;
    var overThreshold = overVolumeThreshold && overErrorThreshold;

    if (overThreshold) {
      this._state = CircuitBreaker.OPEN;
      this.onCircuitOpen();
    }
  }
};

// PUBLIC

CircuitBreaker.prototype.run = function(command, fallback) {
  if (this.isOpen()) {
    this._executeFallback(fallback || function() {});
  }
  else {
    this._executeCommand(command);
  }
};

CircuitBreaker.prototype.forceClose = function() {
  this._state = CircuitBreaker.CLOSED;
  this._forced = true;
};

CircuitBreaker.prototype.forceOpen = function() {
  this._state = CircuitBreaker.OPEN;
  this._forced = true;
};

CircuitBreaker.prototype.isOpen = function() {
  return this._state == CircuitBreaker.OPEN;
};
<commit_msg>define private methods<commit_after>var CircuitBreaker = function(opts) {
  opts = opts || {};

  this.windowDuration  = opts.windowDuration  || 10000; // milliseconds
  this.numBuckets      = opts.numBuckets      || 10;    // number
  this.timeoutDuration = opts.timeoutDuration || 3000;  // milliseconds
  this.errorThreshold  = opts.errorThreshold  || 50;    // percentage
  this.volumeThreshold = opts.volumeThreshold || 5;     // number
  this.onCircuitOpen   = opts.onCircuitOpen   || function() {};
  this.onCircuitClose   = opts.onCircuitClose || function() {};

  this._buckets = [this._createBucket()];
  this._state = CircuitBreaker.CLOSED;

  this._startTicker();
};

CircuitBreaker.OPEN = 0;
CircuitBreaker.HALF_OPEN = 1;
CircuitBreaker.CLOSED = 2;

// PUBLIC

CircuitBreaker.prototype.run = function(command, fallback) {
  if (this.isOpen()) {
    this._executeFallback(fallback || function() {});
  }
  else {
    this._executeCommand(command);
  }
};

CircuitBreaker.prototype.forceClose = function() {
  this._state = CircuitBreaker.CLOSED;
  this._forced = true;
};

CircuitBreaker.prototype.forceOpen = function() {
  this._state = CircuitBreaker.OPEN;
  this._forced = true;
};

CircuitBreaker.prototype.isOpen = function() {
  return this._state == CircuitBreaker.OPEN;
};

// PRIVATE

CircuitBreaker.prototype._startTicker = function() {
  var self = this;
  var bucketIndex = 0;
  var bucketDuration = this.windowDuration / this.numBuckets;

  var tick = function() {
    if (self._buckets.length > self.numBuckets) {
      self._buckets.shift();
    }

    bucketIndex++;

    if (bucketIndex > self.numBuckets) {
      bucketIndex = 0;
      self._state = CircuitBreaker.HALF_OPEN;
    }

    self._buckets.push(self._createBucket());
  };

  window.setInterval(tick, bucketDuration);
};

CircuitBreaker.prototype._createBucket = function() {
  return { failures: 0, successes: 0, timeouts: 0, shortCircuits: 0 };
};

CircuitBreaker.prototype._lastBucket = function() {
  return this._buckets[this._buckets.length - 1];
};

CircuitBreaker.prototype._executeCommand = function(command) {
  var self = this;
  var timeout;

  var increment = function(prop) {
    return function() {
      if (!timeout) { return; }

      var bucket = self._lastBucket();
      bucket[prop]++;

      if (!self._forced) {
        self._updateState();
      }

      window.clearTimeout(timeout);
      timeout = null;
    }
  };

  timeout = window.setTimeout(increment('timeouts'), this.timeoutDuration);

  command(increment('successes'), increment('failures'));
};

CircuitBreaker.prototype._executeFallback = function(fallback) {
  fallback();

  var bucket = this._lastBucket();
  bucket.shortCircuits++;
};

CircuitBreaker.prototype._calculateMetrics = function() {
  var totalCount = 0, errorCount = 0, errorPercentage = 0;

  for (var i = 0, l = this._buckets.length; i < l; i++) {
    var bucket = this._buckets[i];
    var errors = (bucket.failures + bucket.timeouts + bucket.shortCircuits);

    errorCount += errors;
    totalCount += (errors + bucket.successes);
  }

  errorPercentage = (errorCount / (totalCount > 0 ? totalCount : 1)) * 100;

  return { totalCount: totalCount, errorCount: errorCount, errorPercentage: errorPercentage };
}

CircuitBreaker.prototype._updateState = function() {
  var metrics = this._calculateMetrics();

  if (this._state == CircuitBreaker.HALF_OPEN) {
    var lastCommandFailed = !this._lastBucket().successes && metrics.errorCount > 0;

    if (lastCommandFailed) {
      this._state = CircuitBreaker.OPEN;
    }
    else {
      this._state = CircuitBreaker.CLOSED;
      this.onCircuitClose();
    }
  }
  else {
    var overErrorThreshold = metrics.errorPercentage > this.errorThreshold;
    var overVolumeThreshold = metrics.totalCount > this.volumeThreshold;
    var overThreshold = overVolumeThreshold && overErrorThreshold;

    if (overThreshold) {
      this._state = CircuitBreaker.OPEN;
      this.onCircuitOpen();
    }
  }
};
<|endoftext|>


<commit_before>import Immutable from 'immutable';
import createResa from '../resa';

function myReducer(state = {}, _action) {
    return state;
}

const model = {
    namespace: 'model',
    reducer: 'model',
    effects: {
        * add(_app, action, { fulfilled, _reject }) {
            yield fulfilled(action.payload);
        },

        * minus(_app, action, { _fulfilled, reject }) {
            yield reject(action.payload);
        },
    },
};

const callSelfModel = {
    namespace: 'callSelfModel',
    reducer: 'callSelfModel',
    effects: {
        * add(_app, action, { _fulfilled, _reject }) {
            yield this.effects.minus(action.payload);
        },

        * minus(_app, action, { _fulfilled, reject }) {
            yield reject(action.payload);
        },
    },
};

describe('createResa', () => {
    test('createResa return success', () => {
        const app = createResa();
        expect(app).toEqual(expect.objectContaining({
            store: expect.anything(),
            runSaga: expect.anything(),
            model: expect.anything(),
            registerModel: expect.anything(),
        }));
    });

    test('createResa set initialState success', () => {
        const app = createResa({ initialState: { myReducer: 'a' }, reducers: { myReducer } });
        expect(app.store.getState()).toEqual({
            myReducer: 'a',
            resaReducer: {},
        });
    });
});

describe('registerModel', () => {
    test('register model success', () => {
        const app = createResa();
        app.registerModel(model);
        expect(app.model.model).toEqual(expect.objectContaining({
            namespace: 'model',
            reducer: 'model',
            effects: {
                add: expect.anything(),
                minus: expect.anything(),
            },
        }));
    });
});

describe('dispatch action success', () => {
    test('dispatch fulfilled success', () => {
        const app = createResa();
        app.registerModel(model);
        app.model.model.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                model: {
                    a: 'a',
                    loading: false,
                },
            });
        });
    });

    test('dispatch fulfilled success when immutable', () => {
        const app = createResa({ immutable: Immutable });
        app.registerModel(model);
        app.model.model.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual(Immutable.Map({
                resaReducer: {},
                model: Immutable.Map({
                    loading: false,
                    a: 'a',
                }),
            }));
        });
    });

    test('dispatch reject success', () => {
        const app = createResa();
        app.registerModel(model);
        app.model.model.effects.minus({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                model: {
                    a: 'a',
                    loading: false,
                },
            });
        });
    });

    test('dispatch action in saga', () => {
        const app = createResa();
        app.registerModel(callSelfModel);
        app.model.callSelfModel.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                callSelfModel: {
                    a: 'a',
                    loading: false,
                },
            });
        });
    });

    test('model getState success', () => {
        const app = createResa();
        app.registerModel(callSelfModel);
        app.model.callSelfModel.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.model.callSelfModel.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                a: 'a',
                loading: false,
            });
        });
    });

    test('model getState success when use immutable', () => {
        const app = createResa({ immutable: Immutable });
        app.registerModel(callSelfModel);
        app.model.callSelfModel.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.model.callSelfModel.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual(Immutable.Map({
                loading: false,
                a: 'a',
            }));
        });
    });
});

const model1 = {
    namespace: 'model1',
    reducer: 'model',
    effects: {
        * add(_app, action, { fulfilled, _reject }) {
            yield fulfilled(action.payload);
        },
    },
};

const model2 = {
    namespace: 'model2',
    reducer: 'model',
    effects: {
        * add(_app, action, { fulfilled, _reject }) {
            yield fulfilled(action.payload);
        },
    },
};

describe('tow model use same reducer', () => {
    test('reserve state after add new model in same reducer', () => {
        const app = createResa();
        app.registerModel(model1);
        app.model.model1.effects.add({ a: 'a' });
        app.registerModel(model2);
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                model: {
                    a: 'a',
                    loading: false,
                },
            });
        });
    });

    test('tow model use same reducer', () => {
        const app = createResa();
        app.registerModel(model1);
        app.registerModel(model2);
        app.model.model1.effects.add({ a: 'a' });
        app.model.model2.effects.add({ b: 'b' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                model: {
                    a: 'a',
                    b: 'b',
                    loading: false,
                },
            });
        });
    });
});
<commit_msg>update test, use call effect<commit_after>import Immutable from 'immutable';
import { call } from 'redux-saga/effects';
import createResa from '../resa';

function myReducer(state = {}, _action) {
    return state;
}

const model = {
    namespace: 'model',
    reducer: 'model',
    effects: {
        * add(_app, action, { fulfilled, _reject }) {
            yield call(fulfilled, action.payload);
        },

        * minus(_app, action, { _fulfilled, reject }) {
            yield call(reject, action.payload);
        },
    },
};

const callSelfModel = {
    namespace: 'callSelfModel',
    reducer: 'callSelfModel',
    effects: {
        * add(_app, action, { _fulfilled, _reject }) {
            yield call(this.effects.minus, action.payload);
        },

        * minus(_app, action, { _fulfilled, reject }) {
            yield call(reject, action.payload);
        },
    },
};

describe('createResa', () => {
    test('createResa return success', () => {
        const app = createResa();
        expect(app).toEqual(expect.objectContaining({
            store: expect.anything(),
            runSaga: expect.anything(),
            model: expect.anything(),
            registerModel: expect.anything(),
        }));
    });

    test('createResa set initialState success', () => {
        const app = createResa({ initialState: { myReducer: 'a' }, reducers: { myReducer } });
        expect(app.store.getState()).toEqual({
            myReducer: 'a',
            resaReducer: {},
        });
    });
});

describe('registerModel', () => {
    test('register model success', () => {
        const app = createResa();
        app.registerModel(model);
        expect(app.model.model).toEqual(expect.objectContaining({
            namespace: 'model',
            reducer: 'model',
            effects: {
                add: expect.anything(),
                minus: expect.anything(),
            },
        }));
    });
});

describe('dispatch action success', () => {
    test('dispatch fulfilled success', () => {
        const app = createResa();
        app.registerModel(model);
        app.model.model.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                model: {
                    a: 'a',
                    loading: false,
                },
            });
        });
    });

    test('dispatch fulfilled success when immutable', () => {
        const app = createResa({ immutable: Immutable });
        app.registerModel(model);
        app.model.model.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual(Immutable.Map({
                resaReducer: {},
                model: Immutable.Map({
                    loading: false,
                    a: 'a',
                }),
            }));
        });
    });

    test('dispatch reject success', () => {
        const app = createResa();
        app.registerModel(model);
        app.model.model.effects.minus({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                model: {
                    a: 'a',
                    loading: false,
                },
            });
        });
    });

    test('dispatch action in saga', () => {
        const app = createResa();
        app.registerModel(callSelfModel);
        app.model.callSelfModel.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                callSelfModel: {
                    a: 'a',
                    loading: false,
                },
            });
        });
    });

    test('model getState success', () => {
        const app = createResa();
        app.registerModel(callSelfModel);
        app.model.callSelfModel.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.model.callSelfModel.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                a: 'a',
                loading: false,
            });
        });
    });

    test('model getState success when use immutable', () => {
        const app = createResa({ immutable: Immutable });
        app.registerModel(callSelfModel);
        app.model.callSelfModel.effects.add({ a: 'a' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.model.callSelfModel.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual(Immutable.Map({
                loading: false,
                a: 'a',
            }));
        });
    });
});

const model1 = {
    namespace: 'model1',
    reducer: 'model',
    effects: {
        * add(_app, action, { fulfilled, _reject }) {
            yield fulfilled(action.payload);
        },
    },
};

const model2 = {
    namespace: 'model2',
    reducer: 'model',
    effects: {
        * add(_app, action, { fulfilled, _reject }) {
            yield fulfilled(action.payload);
        },
    },
};

describe('tow model use same reducer', () => {
    test('reserve state after add new model in same reducer', () => {
        const app = createResa();
        app.registerModel(model1);
        app.model.model1.effects.add({ a: 'a' });
        app.registerModel(model2);
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                model: {
                    a: 'a',
                    loading: false,
                },
            });
        });
    });

    test('tow model use same reducer', () => {
        const app = createResa();
        app.registerModel(model1);
        app.registerModel(model2);
        app.model.model1.effects.add({ a: 'a' });
        app.model.model2.effects.add({ b: 'b' });
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(app.store.getState());
            }, 5);
        }).then((data) => {
            expect(data).toEqual({
                resaReducer: {},
                model: {
                    a: 'a',
                    b: 'b',
                    loading: false,
                },
            });
        });
    });
});
<|endoftext|>


<commit_before>exports.BattleItems = {
        "nevermeltice": {
  	            id: "nevermeltice",
		            name: "NeverMeltIce",
		            spritenum: 305,
		            fling: {
			                  basePower: 30
		            },
		            onWeather: function(target, source, effect) {
			                  if (effect.id === 'hail') {
				                        this.heal(target.maxhp/16);
			                  }
		            },
		            onImmunity: function(type, pokemon) {
			                  if (type === 'hail') return false;
		            },
		            desc: "If Hail is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Hail.",
	      },
        "quickpowder": {
  	            id: "quickpowder",
		            name: "Quick Powder",
		            spritenum: 374,
		            fling: {
			                  basePower: 10
		            },
		            onModifySpe: function(spe) {
			                  return spe * 1.1;
		            },
		            desc: "Boosts Speed by 10%."
	      }
};
<commit_msg>Finish Items<commit_after>exports.BattleItems = {
	"silkscarf": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Normal')
				return basePower * 1.3;
		}
	},
	"flameplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Fire')
				return basePower * 1.3;
		}
	},
	"fistplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Fighting')
				return basePower * 1.3;
		}
	},
	"splashplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Water')
				return basePower * 1.3;
		}
	},
	"meadowplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Grass')
				return basePower * 1.3;
		}
	},
	"toxicplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Poison')
				return basePower * 1.3;
		}
	},
	"zapplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Electric')
				return basePower * 1.3;
		}
	},
	"earthplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Ground')
				return basePower * 1.3;
		}
	},
	"mindplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Psychic')
				return basePower * 1.3;
		}
	},
	"stoneplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Rock')
				return basePower * 1.3;
		}
	},
	"icicleplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Ice')
				return basePower * 1.3;
		}
	},
	"insectplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Bug')
				return basePower * 1.3;
		}
	},
	"dracoplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Dragon')
				return basePower * 1.3;
		}
	},
	"spookyplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Ghost')
				return basePower * 1.3;
		}
	},
	"dreadplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Dark')
				return basePower * 1.3;
		}
	},
	"ironplate": {
		inherit: true,
		onBasePower: function(basePower, user, target, move) {
			if (move && move.type === 'Steel')
				return basePower * 1.3;
		}
	},
	"expertbelt": {
		id: "expertbelt",
		name: "Expert Belt",
		spritenum: 132,
		fling: {
			basePower: 10
		},
		onBasePower: function(basePower, user, target, move) {
			if (move && this.getEffectiveness(move.type, target) > 0) {
				return basePower * 1.3;
			}
		},
		desc: "Super effective attacks are 30% stronger."
	},
	"quickpowder": {
		id: "quickpowder",
		name: "Quick Powder",
		spritenum: 374,
		fling: {
			basePower: 10
		},
		onModifySpe: function(spe) {
			return spe * 1.1;
		},
		desc: "Boosts Speed by 10%."
	},
	"metalpowder": {
		id: "metalpowder",
		name: "Metal Powder",
		fling: {
			basePower: 10
		},
		spritenum: 287,
		onModifyDef: function(def, pokemon) {
			return def * 1.2;
		},
		onModifySpD: function(spd, pokemon) {
			return spd * 1.2;
		},
		desc: "Raises holder's Defense and Special Defense by 20%."
	},
	"nevermeltice": {
		id: "nevermeltice",
		name: "NeverMeltIce",
		spritenum: 305,
		fling: {
			basePower: 30
		},
		onWeather: function(target, source, effect) {
			if (effect.id === 'hail') {
				this.heal(target.maxhp/16);
			}
		},
		onImmunity: function(type, pokemon) {
			if (type === 'hail') return false;
		},
		desc: "If Hail is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Hail.",
	},
	"softsand": {
		id: "softsand",
		name: "Soft Sand",
		spritenum: 456,
		fling: {
			basePower: 10
		},
		onWeather: function(target, source, effect) {
			if (effect.id === 'sandstorm') {
				this.heal(target.maxhp/16);
			}
		},
		onImmunity: function(type, pokemon) {
			if (type === 'sandstorm') return false;
		},
		desc: "If Sandstorm is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Sandstorm."
	},
	"blacksludge": {
		id: "blacksludge",
		name: "Black Sludge",
		spritenum: 34,
		fling: {
			basePower: 30
		},
		onResidualOrder: 5,
		onResidualSubOrder: 2,
		onResidual: function(pokemon) {
			if (pokemon.hasType('Poison')) {
				this.heal(pokemon.maxhp/12);
			} else {
				this.damage(pokemon.maxhp/12);
			}
		},
		desc: "Recovers 1\/12 HP each turn for Poison types. Damages all other types."
	},
	"twistedspoon": {
		id: "twistedspoon",
		name: "TwistedSpoon",
		spritenum: 520,
		fling: {
			basePower: 30
		},
		onModifyMove: function(move) {
			if (pokemon.template.species === 'Alakazam' && move.category === 'Physical') {
				move.category = 'Special';
				move.defensiveCategory = 'Physical';
			}
		},
		desc: "If holder is Alakazam, physical attacks deal damage based off of its Special Attack."
	},
	"widelens": {
		inherit: true,
		onModifyMove: function(move) {
			if (typeof move.accuracy === 'number') {
				move.accuracy *= 1.3;
			}
		},
		desc: "Raises accuracy 30%."
	},
	"zoomlens": {
		inherit: true,
		onModifyMove: function(move, user, target) {
			if (typeof move.accuracy === 'number' && !this.willMove(target)) {
				this.debug('Zoom Lens boosting accuracy');
				move.accuracy *= 1.5;
			}
		},
		desc: "Raises accuracy by 50% if the holder moves after the target."
	}
};
<|endoftext|>


<commit_before>E2.plugins["quad_mesh_generator"] = function(core, node) {
	var self = this;
	var gl = core.renderer.context;

	this.input_slots = [];
	this.output_slots = [ { name: 'mesh', dt: core.datatypes.MESH } ];
	this.mesh = null;

	this.reset = function()
	{
		self.updated = true;
	};

	this.update_output = function(slot)
	{
		return self.mesh;
	};

	this.state_changed = function(ui)
	{
		if(!ui)
		{
			msg('Quad: Generating mesh.');
			self.mesh = new Mesh(gl, gl.TRIANGLE_STRIP);

			var verts = self.mesh.vertex_buffers['VERTEX'] = new VertexBuffer(gl, VertexBuffer.vertex_type.VERTEX);

			verts.bind_data([
				 1.0,  1.0,  0.0,
				-1.0,  1.0,  0.0,
				 1.0, -1.0,  0.0,
				-1.0, -1.0,  0.0
			]);

			/*var norms = self.mesh.vertex_buffers['NORMAL'] = new VertexBuffer(gl, VertexBuffer.vertex_type.NORMAL);

			norms.bind_data([
				0.0,  0.0,  1.0,
				0.0,  0.0,  1.0,
				0.0,  0.0,  1.0,
				0.0,  0.0,  1.0
			]);*/

  			var uv0 = self.mesh.vertex_buffers['UV0'] = new VertexBuffer(gl, VertexBuffer.vertex_type.UV0);

			uv0.bind_data([
				 1.0,  1.0,
				 0.0,  1.0,
				 1.0,  0.0,
				 0.0,  0.0
			]);

			/*var indices = self.mesh.index_buffer = new IndexBuffer(gl);

			indices.bind_data([
				0,  1,  2, 0,  2,  3
			]);*/
		}
	};
};
<commit_msg>Fixed index buffer bug in the quad mesh generator.<commit_after>E2.plugins["quad_mesh_generator"] = function(core, node) {
	var self = this;
	var gl = core.renderer.context;

	this.input_slots = [];
	this.output_slots = [ { name: 'mesh', dt: core.datatypes.MESH } ];
	this.mesh = null;

	this.reset = function()
	{
		self.updated = true;
	};

	this.update_output = function(slot)
	{
		return self.mesh;
	};

	this.state_changed = function(ui)
	{
		if(!ui)
		{
			msg('Quad: Generating mesh.');
			self.mesh = new Mesh(gl, gl.TRIANGLE_STRIP);

			var verts = self.mesh.vertex_buffers['VERTEX'] = new VertexBuffer(gl, VertexBuffer.vertex_type.VERTEX);

			verts.bind_data([
				 1.0,  1.0,  0.0,
				-1.0,  1.0,  0.0,
				 1.0, -1.0,  0.0,
				-1.0, -1.0,  0.0
			]);

			var norms = self.mesh.vertex_buffers['NORMAL'] = new VertexBuffer(gl, VertexBuffer.vertex_type.NORMAL);

			norms.bind_data([
				0.0,  0.0,  1.0,
				0.0,  0.0,  1.0,
				0.0,  0.0,  1.0,
				0.0,  0.0,  1.0
			]);

  			var uv0 = self.mesh.vertex_buffers['UV0'] = new VertexBuffer(gl, VertexBuffer.vertex_type.UV0);

			uv0.bind_data([
				 1.0,  1.0,
				 0.0,  1.0,
				 1.0,  0.0,
				 0.0,  0.0
			]);

			var indices = self.mesh.index_buffer = new IndexBuffer(gl);

			indices.bind_data([ 3, 1, 0, 3, 2, 0 ]);
		}
	};
};
<|endoftext|>


<commit_before>/* exported createPaymentCredential */
/* exported onBuyClicked */
const textEncoder = new TextEncoder();
/**
 * Converts an ArrayBuffer into a string.
 */
function arrayBufferToString(input) {
  return String.fromCharCode(...new Uint8Array(input));
}
/**
 * Converts an ArrayBuffer into a base64 encoded string.
 */
function arrayBufferToBase64(input) {
  return btoa(arrayBufferToString(input));
}
/**
 * Converts a base64 encoded string into Unit8Array.
 */
function base64ToArray(input) {
  return Uint8Array.from(atob(input), c => c.charCodeAt(0))
}
/**
 * Converts a PaymentResponse or a PublicKeyCredential into an dictionary.
 */
function objectToDictionary(input) {
  let output = {};
  if (input.requestId) {
    output.requestId = input.requestId;
  }
  if (input.id) {
    output.id = input.id;
  }
  if (input.rawId && input.rawId.constructor === ArrayBuffer) {
    output.rawId = arrayBufferToBase64(input.rawId);
  }
  if (input.response && (input.response.constructor ===
      AuthenticatorAttestationResponse || input.response.constructor ===
      AuthenticatorAssertionResponse || input.response.constructor === Object
      )) {
    output.response = objectToDictionary(input.response);
  }
  if (input.attestationObject && input.attestationObject.constructor ===
    ArrayBuffer) {
    output.attestationObject = arrayBufferToBase64(input.attestationObject);
  }
  if (input.authenticatorData && input.authenticatorData.constructor ===
    ArrayBuffer) {
    output.authenticatorData = arrayBufferToBase64(input.authenticatorData);
  }
  if (input.authenticatorData && input.authenticatorData.constructor ===
    String) {
    output.authenticatorData = input.authenticatorData;
  }
  if (input.clientDataJSON && input.clientDataJSON.constructor ===
    ArrayBuffer) {
    output.clientDataJSON = arrayBufferToString(input.clientDataJSON);
  }
  if (input.clientDataJSON && input.clientDataJSON.constructor ===
    String) {
    output.clientDataJSON = atob(input.clientDataJSON);
  }
  if (input.info) {
    output.info = objectToDictionary(input.info);
  }
  if (input.signature && input.signature.constructor === ArrayBuffer) {
    output.signature = arrayBufferToBase64(input.signature);
  }
  if (input.signature && input.signature.constructor === String) {
    output.signature = input.signature;
  }
  if (input.userHandle && input.userHandle.constructor === ArrayBuffer) {
    output.userHandle = arrayBufferToBase64(input.userHandle);
  }
  if (input.userHandle && input.userHandle.constructor === String) {
    output.userHandle = input.userHandle;
  }
  if (input.type) {
    output.type = input.type;
  }
  if (input.methodName) {
    output.methodName = input.methodName;
  }
  if (input.details) {
    output.details = objectToDictionary(input.details);
  }
  if (input.appid_extension) {
    output.appid_extension = input.appid_extension;
  }
  if (input.challenge) {
    output.challenge = input.challenge;
  }
  if (input.echo_appid_extension) {
    output.echo_appid_extension = input.echo_appid_extension;
  }
  if (input.echo_prf) {
    output.echo_prf = input.echo_prf;
  }
  if (input.prf_not_evaluated) {
    output.prf_not_evaluated = input.prf_not_evaluated;
  }
  if (input.prf_results) {
    output.prf_results = objectToDictionary(input.prf_results);
  }
  if (input.user_handle) {
    output.user_handle = input.user_handle;
  }
  if (input.authenticator_data) {
    output.authenticator_data = input.authenticator_data;
  }
  if (input.client_data_json) {
    output.client_data_json = atob(input.client_data_json);
  }
  if (input.shippingAddress) {
    output.shippingAddress = input.shippingAddress;
  }
  if (input.shippingOption) {
    output.shippingOption = input.shippingOption;
  }
  if (input.payerName) {
    output.payerName = input.payerName;
  }
  if (input.payerEmail) {
    output.payerEmail = input.payerEmail;
  }
  if (input.payerPhone) {
    output.payerPhone = input.payerPhone;
  }
  return output;
}
/**
 * Converts a PaymentResponse or a PublicKeyCredential into a string.
 */
function objectToString(input) {
  return JSON.stringify(objectToDictionary(input), undefined, 2);
}

// Return whether or not SPC supports residentKey 'preferred' (instead of just
// 'required'). There is unfortunately no way to feature detect this, so we
// have to do a version check.
function spcSupportsPreferred() {
  // This will be true for not just Chrome but also Edge/etc, but that's fine.
  const match = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
  if (!match)
    return false;

  const version = parseInt(match[2], 10);
  // https://crrev.com/130fada41 landed in 106.0.5228.0, but we assume that any
  // 106 will do for simplicity.
  return version >= 106;
}

async function createCredentialCompat() {
  const rp = {
    id: window.location.hostname,
    name: 'Rouslan Solomakhin',
  };
  const pubKeyCredParams = [{
    type: 'public-key',
    alg: -7, // ECDSA, not supported on Windows.
  }, {
    type: 'public-key',
    alg: -257, // RSA, supported on Windows.
  }];
  const challenge = textEncoder.encode('Enrollment challenge');
  if (window.PaymentCredential) {
    const payment = {
      rp,
      instrument: {
        displayName: 'Troy ····',
        icon: 'https://rsolomakhin.github.io/pr/spc/troy.png',
      },
      challenge,
      pubKeyCredParams,
      authenticatorSelection: {
        userVerification: 'required',
      },
    };
    return await navigator.credentials.create({
      payment
    });
  } else {
    const publicKey = {
      rp,
      user: {
        name: 'user@domain',
        id: Uint8Array.from(String(Math.random()*999999999), c => c.charCodeAt(0)),
        displayName: 'User',
      },
      challenge,
      pubKeyCredParams,
      authenticatorSelection: {
        userVerification: 'required',
        residentKey: spcSupportsPreferred() ? 'preferred' : 'required',
        authenticatorAttachment: 'platform',
      },
      extensions: {
        payment: {
          isPayment: true,
        },
      }
    };
    return await navigator.credentials.create({
      publicKey
    });
  }
}

/**
 * Creates a payment credential.
 */
async function createPaymentCredential(windowLocalStorageItemKey) {
  try {
    const publicKeyCredential = await createCredentialCompat();
    console.log(publicKeyCredential);
    window.localStorage.setItem(windowLocalStorageItemKey,
      arrayBufferToBase64(publicKeyCredential.rawId));
    info(windowLocalStorageItemKey + ' enrolled: ' + objectToString(
      publicKeyCredential));
  } catch (err) {
    error(err);
  }
}
/**
 * Initializes the payment request object.
 * @return {PaymentRequest} The payment request object.
 */
async function buildPaymentRequest(autofillField, windowLocalStorageItemKey) {
  if (!window.PaymentRequest) {
    return null;
  }
  let request = null;
  try {
    const challenge = textEncoder.encode('network_data');
    const updatedInstrument = {
      displayName: 'My Troy Card',
      icon: 'https://rsolomakhin.github.io/pr/spc/troy-alt-logo.png',
    };
    const supportedInstruments = [{
      supportedMethods: 'secure-payment-confirmation',
      data: {
        credentialIds: [base64ToArray(window.localStorage.getItem(
          windowLocalStorageItemKey))],
        instrument: updatedInstrument,
        networkData: challenge,
        challenge,
        timeout: 60000,
        payeeOrigin: window.location.origin,
        rpId: window.location.hostname,
        autofillField,
      },
    }];
    const details = {
      total: {
        label: 'Total',
        amount: {
          currency: 'USD',
          value: '0.01',
        },
      },
    };
    request = new PaymentRequest(supportedInstruments, details);
  } catch (err) {
    error(err);
  }
  return request;
}
/**
 * Launches payment request for Android Pay.
 */
async function optionallyGetSpcFrom(autofillField, windowLocalStorageItemKey) {
  if (!window.PaymentRequest) {
    error('PaymentRequest API is not supported.');
    return;
  }
  if (!window.PaymentRequest.prototype.showInAutofillField) {
    error('SPC does not support autofill popups in your browser yet.');
    return;
  }
  const request = await buildPaymentRequest(
      autofillField, windowLocalStorageItemKey);
  if (!request) return;
  try {
    const instrumentResponse = await request.showInAutofillField();
    await instrumentResponse.complete('success')
    console.log(instrumentResponse);
    info(windowLocalStorageItemKey + ' payment response: ' +
      objectToString(instrumentResponse));
  } catch (err) {
    error(err);
  }
}

function pretendSubmitForm() {
  const phoneNumber = document.getElementById('phone-field').value;
  if (phoneNumber) {
    info('Pretend SMS sent to ' + phoneNumber + '.');
  } else {
    error('No phone number provided.');
  }
}

function init() {
  const verifyForm = document.getElementById('verify-form');
  verifyForm.addEventListener('submit', evt => {
    evt.preventDefault();
    pretendSubmitForm();
  });
}

init();
<commit_msg>Update comment<commit_after>/* exported createPaymentCredential */
/* exported onBuyClicked */
const textEncoder = new TextEncoder();
/**
 * Converts an ArrayBuffer into a string.
 */
function arrayBufferToString(input) {
  return String.fromCharCode(...new Uint8Array(input));
}
/**
 * Converts an ArrayBuffer into a base64 encoded string.
 */
function arrayBufferToBase64(input) {
  return btoa(arrayBufferToString(input));
}
/**
 * Converts a base64 encoded string into Unit8Array.
 */
function base64ToArray(input) {
  return Uint8Array.from(atob(input), c => c.charCodeAt(0))
}
/**
 * Converts a PaymentResponse or a PublicKeyCredential into an dictionary.
 */
function objectToDictionary(input) {
  let output = {};
  if (input.requestId) {
    output.requestId = input.requestId;
  }
  if (input.id) {
    output.id = input.id;
  }
  if (input.rawId && input.rawId.constructor === ArrayBuffer) {
    output.rawId = arrayBufferToBase64(input.rawId);
  }
  if (input.response && (input.response.constructor ===
      AuthenticatorAttestationResponse || input.response.constructor ===
      AuthenticatorAssertionResponse || input.response.constructor === Object
      )) {
    output.response = objectToDictionary(input.response);
  }
  if (input.attestationObject && input.attestationObject.constructor ===
    ArrayBuffer) {
    output.attestationObject = arrayBufferToBase64(input.attestationObject);
  }
  if (input.authenticatorData && input.authenticatorData.constructor ===
    ArrayBuffer) {
    output.authenticatorData = arrayBufferToBase64(input.authenticatorData);
  }
  if (input.authenticatorData && input.authenticatorData.constructor ===
    String) {
    output.authenticatorData = input.authenticatorData;
  }
  if (input.clientDataJSON && input.clientDataJSON.constructor ===
    ArrayBuffer) {
    output.clientDataJSON = arrayBufferToString(input.clientDataJSON);
  }
  if (input.clientDataJSON && input.clientDataJSON.constructor ===
    String) {
    output.clientDataJSON = atob(input.clientDataJSON);
  }
  if (input.info) {
    output.info = objectToDictionary(input.info);
  }
  if (input.signature && input.signature.constructor === ArrayBuffer) {
    output.signature = arrayBufferToBase64(input.signature);
  }
  if (input.signature && input.signature.constructor === String) {
    output.signature = input.signature;
  }
  if (input.userHandle && input.userHandle.constructor === ArrayBuffer) {
    output.userHandle = arrayBufferToBase64(input.userHandle);
  }
  if (input.userHandle && input.userHandle.constructor === String) {
    output.userHandle = input.userHandle;
  }
  if (input.type) {
    output.type = input.type;
  }
  if (input.methodName) {
    output.methodName = input.methodName;
  }
  if (input.details) {
    output.details = objectToDictionary(input.details);
  }
  if (input.appid_extension) {
    output.appid_extension = input.appid_extension;
  }
  if (input.challenge) {
    output.challenge = input.challenge;
  }
  if (input.echo_appid_extension) {
    output.echo_appid_extension = input.echo_appid_extension;
  }
  if (input.echo_prf) {
    output.echo_prf = input.echo_prf;
  }
  if (input.prf_not_evaluated) {
    output.prf_not_evaluated = input.prf_not_evaluated;
  }
  if (input.prf_results) {
    output.prf_results = objectToDictionary(input.prf_results);
  }
  if (input.user_handle) {
    output.user_handle = input.user_handle;
  }
  if (input.authenticator_data) {
    output.authenticator_data = input.authenticator_data;
  }
  if (input.client_data_json) {
    output.client_data_json = atob(input.client_data_json);
  }
  if (input.shippingAddress) {
    output.shippingAddress = input.shippingAddress;
  }
  if (input.shippingOption) {
    output.shippingOption = input.shippingOption;
  }
  if (input.payerName) {
    output.payerName = input.payerName;
  }
  if (input.payerEmail) {
    output.payerEmail = input.payerEmail;
  }
  if (input.payerPhone) {
    output.payerPhone = input.payerPhone;
  }
  return output;
}
/**
 * Converts a PaymentResponse or a PublicKeyCredential into a string.
 */
function objectToString(input) {
  return JSON.stringify(objectToDictionary(input), undefined, 2);
}

// Return whether or not SPC supports residentKey 'preferred' (instead of just
// 'required'). There is unfortunately no way to feature detect this, so we
// have to do a version check.
function spcSupportsPreferred() {
  // This will be true for not just Chrome but also Edge/etc, but that's fine.
  const match = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
  if (!match)
    return false;

  const version = parseInt(match[2], 10);
  // https://crrev.com/130fada41 landed in 106.0.5228.0, but we assume that any
  // 106 will do for simplicity.
  return version >= 106;
}

async function createCredentialCompat() {
  const rp = {
    id: window.location.hostname,
    name: 'Rouslan Solomakhin',
  };
  const pubKeyCredParams = [{
    type: 'public-key',
    alg: -7, // ECDSA, not supported on Windows.
  }, {
    type: 'public-key',
    alg: -257, // RSA, supported on Windows.
  }];
  const challenge = textEncoder.encode('Enrollment challenge');
  if (window.PaymentCredential) {
    const payment = {
      rp,
      instrument: {
        displayName: 'Troy ····',
        icon: 'https://rsolomakhin.github.io/pr/spc/troy.png',
      },
      challenge,
      pubKeyCredParams,
      authenticatorSelection: {
        userVerification: 'required',
      },
    };
    return await navigator.credentials.create({
      payment
    });
  } else {
    const publicKey = {
      rp,
      user: {
        name: 'user@domain',
        id: Uint8Array.from(String(Math.random()*999999999), c => c.charCodeAt(0)),
        displayName: 'User',
      },
      challenge,
      pubKeyCredParams,
      authenticatorSelection: {
        userVerification: 'required',
        residentKey: spcSupportsPreferred() ? 'preferred' : 'required',
        authenticatorAttachment: 'platform',
      },
      extensions: {
        payment: {
          isPayment: true,
        },
      }
    };
    return await navigator.credentials.create({
      publicKey
    });
  }
}

/**
 * Creates a payment credential.
 */
async function createPaymentCredential(windowLocalStorageItemKey) {
  try {
    const publicKeyCredential = await createCredentialCompat();
    console.log(publicKeyCredential);
    window.localStorage.setItem(windowLocalStorageItemKey,
      arrayBufferToBase64(publicKeyCredential.rawId));
    info(windowLocalStorageItemKey + ' enrolled: ' + objectToString(
      publicKeyCredential));
  } catch (err) {
    error(err);
  }
}
/**
 * Initializes the payment request object.
 * @return {PaymentRequest} The payment request object.
 */
async function buildPaymentRequest(autofillField, windowLocalStorageItemKey) {
  if (!window.PaymentRequest) {
    return null;
  }
  let request = null;
  try {
    const challenge = textEncoder.encode('network_data');
    const updatedInstrument = {
      displayName: 'My Troy Card',
      icon: 'https://rsolomakhin.github.io/pr/spc/troy-alt-logo.png',
    };
    const supportedInstruments = [{
      supportedMethods: 'secure-payment-confirmation',
      data: {
        credentialIds: [base64ToArray(window.localStorage.getItem(
          windowLocalStorageItemKey))],
        instrument: updatedInstrument,
        networkData: challenge,
        challenge,
        timeout: 60000,
        payeeOrigin: window.location.origin,
        rpId: window.location.hostname,
        autofillField,
      },
    }];
    const details = {
      total: {
        label: 'Total',
        amount: {
          currency: 'USD',
          value: '0.01',
        },
      },
    };
    request = new PaymentRequest(supportedInstruments, details);
  } catch (err) {
    error(err);
  }
  return request;
}
/**
 * Launches payment request for Android Pay.
 */
async function optionallyGetSpcFrom(autofillField, windowLocalStorageItemKey) {
  if (!window.PaymentRequest) {
    error('PaymentRequest API is not supported.');
    return;
  }
  if (!window.PaymentRequest.prototype.showInAutofillField) {
    error('Secure Payment Confirmation is not supported in autofill popups.');
    return;
  }
  const request = await buildPaymentRequest(
      autofillField, windowLocalStorageItemKey);
  if (!request) return;
  try {
    const instrumentResponse = await request.showInAutofillField();
    await instrumentResponse.complete('success')
    console.log(instrumentResponse);
    info(windowLocalStorageItemKey + ' payment response: ' +
      objectToString(instrumentResponse));
  } catch (err) {
    error(err);
  }
}

function pretendSubmitForm() {
  const phoneNumber = document.getElementById('phone-field').value;
  if (phoneNumber) {
    info('Pretend SMS sent to ' + phoneNumber + '.');
  } else {
    error('No phone number provided.');
  }
}

function init() {
  const verifyForm = document.getElementById('verify-form');
  verifyForm.addEventListener('submit', evt => {
    evt.preventDefault();
    pretendSubmitForm();
  });
}

init();
<|endoftext|>