<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 = randomIntFromInterva<commit_msg>Grammar fix<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", 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<|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', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr<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', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/<|endoftext|>


<commit_before>#!/usr/bin/env node
// Copyright (c) 2013 Tom Steele
// See the file license.txt for copying permission

var fs = require('fs');
var async = require('async');
var webshot = require('webshot');
var Progress = require('progress');
var request = require('request');
var color = require('colors');

var argv = require('optimist')
  .demand(1)
  .describe('c', 'Amount of concurrent requests')
  .options('c', {
           alias: 'concurrency',
           default: 1000
           })
  .describe('u', 'User-Agent string')
  .options('u', {
           alias: 'useragent',
           default: 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17'
  })
  .describe('h', 'Screenshot height')
  .options('h', {
           alias: 'height',
           default: 400
  })
  .describe('w', 'Screenshot width')
  .options('w', {
           alias: 'width',
           default: 400
  })
  .describe('p', 'phantomjs path')
  .options('p', {
           alias: 'phantom',
           default: 'phantomjs'
  })
  .describe('t', 'Timeout in milliseconds')
  .options('t', {
           alias: 'timeout',
           default: 10000
  })
  .describe('j', 'Output JSON object')
  .alias('j', 'json')
  .describe('o', 'Output file')
  .options('o', {
    alias: 'out',
    default: 'index.html'
  })
  .describe('a', 'Append to file')
  .alias('a', 'append')
  .check(checkArgs)
  .usage("$0 [options] <url file>").argv;

// really should never do this, but there is some wonkyness in the webshot callback with errors.
// it can callback with an error, and then still emit events.
process.on('uncaughtException', function(err) {});

// phantomjs webshot options
var options = {
  screenSize: {
    width: argv.w,
    height: argv.h,
  },
  phantomConfig: {
    'ignore-ssl-errors': 'true'
  },
  userAgent: argv.u,
  phantomPath: argv.p,
  timeout: argv.t
};

// read file in and create list of urls
var urls = fs.readFileSync(argv._[0], {encoding: 'utf8'}).trim().split("\n");
var results = [];

// async queue
var q = async.queue(getScreenShot, argv.c);
q.push(urls);
q.drain = complete;

// progress bar
var bar = new Progress('requests [:bar] :percent :etas'.green, { complete: '=', width: 20, total: urls.length });
function getScreenShot(url, cb) {
  var img = '';
  // request the page once first to get around phantomjs 401 bug
  var ropts = {'url': url, 'strictSSL': false};
  request(ropts, function(err, res) {
    // if response was not 401 grab a screenshot
    if (!err && res.statusCode !== 401) {
      webshot(url, options, function(err, rs) {
        if (err) {
          bar.tick();
          cb();
        }
        else {
          rs.on('data', function(data) {
            var string = data.toString('base64');
            if (!string.match(/Error/)) {
              img += data.toString('base64');
            }
          });
          rs.on('error', function(err) {
            bar.tick();
            cb();
          });
          rs.on('end', function() {
            bar.tick();
            results.push({"url": url, "img": img});
            cb();
          });
        }
      });
    }
    // else if error or a 401 just skip it
    else {
      bar.tick();
      cb();
    }
  });
 }

// append or write to file
function complete() {
  console.log('\n');
  if (argv.a) {
    console.log('appending to file', argv.a);
  }
  else {
    console.log('saving results to file', argv.o);
  }

  if (argv.j) {
    jsonOut(results);
  }
  else {
    htmlOut(results);
  }
  process.exit(0);
}

// output the results object as json
function jsonOut(results) {
  var string = JSON.stringify(results, null, " ");
  if (argv.o) {
    fs.writeFileSync(argv.o, string);
  }
  else if (argv.a) {
    fs.appendFileSync(argv.a, string);
    process.exit(0);
  }
  else {
    console.log(string);
  }
}

// create a html file with the results
function htmlOut(results) {
  // gentle css for styling
  var css = ".outline {border: 1px solid black;} html,body {padding: 10px;}"

  if (!argv.a) {
    var string = ''
  }

  results.forEach(function(r) {
    string += '
' + r.url + "
";
    string += '
';
  });

  if (!argv.a) {
    string += '';
  }
  if (argv.a) {
    fs.appendFileSync(argv.a, string);
  }
  else {
    fs.writeFileSync(argv.o, string);
  }
}

// check argv arguments for errors
function checkArgs(argv) {
  if (!fs.existsSync(argv._[0])) {
    throw 'url file does not exist'.red;
  }
  if (isNaN(argv.c) || argv.c < 0) {
    throw 'invalid concurrency amount given'.red;
  }
  if (argv.a && !fs.existsSync(argv.a)) {
    throw 'append file does not exist'.red;
  }
}
<commit_msg>passing redirected url to phantomjs<commit_after>#!/usr/bin/env node
// Copyright (c) 2013 Tom Steele
// See the file license.txt for copying permission

var fs = require('fs');
var async = require('async');
var webshot = require('webshot');
var Progress = require('progress');
var request = require('request');
var color = require('colors');

var argv = require('optimist')
  .demand(1)
  .describe('c', 'Amount of concurrent requests')
  .options('c', {
           alias: 'concurrency',
           default: 1000
           })
  .describe('u', 'User-Agent string')
  .options('u', {
           alias: 'useragent',
           default: 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17'
  })
  .describe('h', 'Screenshot height')
  .options('h', {
           alias: 'height',
           default: 400
  })
  .describe('w', 'Screenshot width')
  .options('w', {
           alias: 'width',
           default: 400
  })
  .describe('p', 'phantomjs path')
  .options('p', {
           alias: 'phantom',
           default: 'phantomjs'
  })
  .describe('t', 'Timeout in milliseconds')
  .options('t', {
           alias: 'timeout',
           default: 10000
  })
  .describe('j', 'Output JSON object')
  .alias('j', 'json')
  .describe('o', 'Output file')
  .options('o', {
    alias: 'out',
    default: 'index.html'
  })
  .describe('a', 'Append to file')
  .alias('a', 'append')
  .check(checkArgs)
  .usage("$0 [options] <url file>").argv;

// really should never do this, but there is some wonkyness in the webshot callback with errors.
// it can callback with an error, and then still emit events.
process.on('uncaughtException', function(err) {});

// phantomjs webshot options
var options = {
  screenSize: {
    width: argv.w,
    height: argv.h,
  },
  phantomConfig: {
    'ignore-ssl-errors': 'true'
  },
  userAgent: argv.u,
  phantomPath: argv.p,
  timeout: argv.t
};

// read file in and create list of urls
var urls = fs.readFileSync(argv._[0], {encoding: 'utf8'}).trim().split("\n");
var results = [];

// async queue
var q = async.queue(getScreenShot, argv.c);
q.push(urls);
q.drain = complete;

// progress bar
var bar = new Progress('requests [:bar] :percent :etas'.green, { complete: '=', width: 20, total: urls.length });
function getScreenShot(url, cb) {
  var img = '';
  // request the page once first to get around phantomjs 401 bug
  var ropts = {'url': url, 'strictSSL': false, headers:{'User-Agent': argv.u}};
  request(ropts, function(err, res) {
    // if response was not 401 grab a screenshot
    if (!err && res.statusCode !== 401) {
      var href = res.request['uri'].href;
      webshot(href, options, function(err, rs) {
        if (err) {
          bar.tick();
          cb();
        }
        else {
          rs.on('data', function(data) {
            var string = data.toString('base64');
            if (!string.match(/Error/)) {
              img += data.toString('base64');
            }
          });
          rs.on('error', function(err) {
            bar.tick();
            cb();
          });
          rs.on('end', function() {
            bar.tick();
            results.push({"url": url, "href": href, "img": img});
            cb();
          });
        }
      });
    }
    // else if error or a 401 just skip it
    else {
      bar.tick();
      cb();
    }
  });
 }

// append or write to file
function complete() {
  console.log('\n');
  if (argv.a) {
    console.log('appending to file', argv.a);
  }
  else {
    console.log('saving results to file', argv.o);
  }

  if (argv.j) {
    jsonOut(results);
  }
  else {
    htmlOut(results);
  }
  process.exit(0);
}

// output the results object as json
function jsonOut(results) {
  var string = JSON.stringify(results, null, " ");
  if (argv.o) {
    fs.writeFileSync(argv.o, string);
  }
  else if (argv.a) {
    fs.appendFileSync(argv.a, string);
    process.exit(0);
  }
  else {
    console.log(string);
  }
}

// create a html file with the results
function htmlOut(results) {
  // gentle css for styling
  var css = ".outline {border: 1px solid black;} html,body {padding: 10px;}"

  if (!argv.a) {
    var string = ''
  }

  results.forEach(function(r) {
    string += '
' + r.url + "
";
    if (r.href) { string += '
=> ' + r.href + "
"; }
    string += '
';
  });

  if (!argv.a) {
    string += '';
  }
  if (argv.a) {
    fs.appendFileSync(argv.a, string);
  }
  else {
    fs.writeFileSync(argv.o, string);
  }
}

// check argv arguments for errors
function checkArgs(argv) {
  if (!fs.existsSync(argv._[0])) {
    throw 'url file does not exist'.red;
  }
  if (isNaN(argv.c) || argv.c < 0) {
    throw 'invalid concurrency amount given'.red;
  }
  if (argv.a && !fs.existsSync(argv.a)) {
    throw 'append file does not exist'.red;
  }
}
<|endoftext|>


<commit_before>/**
 * @class SceneJS
 * SceneJS name space
 * @singleton
 */
var SceneJS = {

    /** Version of this release
     */
    VERSION: '0.8',

    /** Names of supported WebGL canvas contexts
     */
    SUPPORTED_WEBGL_CONTEXT_NAMES:["webgl", "experimental-webgl", "webkit-3d", "moz-webgl", "moz-glweb20"],

    /** Extension point to create a new node type.
     *
     * @param {string} type Name of new subtype
     * @param {string} superType Optional name of super-type - {@link SceneJS.Node} by default
     * @return {class} New node class
     */
    createNodeType : function(type, superType) {
        if (!type) {
            throw "createNodeType param 'type' is null or undefined";
        }
        if (typeof type != "string") {
            throw "createNodeType param 'type' should be a string";
        }
        var supa = this._nodeTypes[superType || "node"];
        if (!supa) {
            throw "undefined superType: '" + superType + "'";
        }
        var nodeType = function() {                  // Create class
            supa.nodeClass.apply(this, arguments);
            this._attr.nodeType = type;
        };
        SceneJS._inherit(nodeType, supa.nodeClass);

        var nodeFunc = function() {                // Create factory function
            var n = new nodeType();
            nodeType.prototype.constructor.apply(n, arguments);
            n._attr.nodeType = type;
            return n;
        };
        this._registerNode(type, nodeType, nodeFunc);
        SceneJS[type] = nodeFunc;
        return nodeType;
    },

    _registerNode : function(type, nodeClass, nodeFunc) {
        this._nodeTypes[type] = {
            nodeClass : nodeClass,
            nodeFunc: nodeFunc
        };
    },

    /**
     * Factory function to create a scene (sub)graph from JSON
     * @param json
     * @return {SceneJS.Node} Root of (sub)graph
     */
    createNode : function(json) {
        if (!json) {
            throw "createNode param 'json' is null or undefined";
        }
        var newNode = this._parseNodeJSON(json);
        SceneJS._eventModule.fireEvent(SceneJS._eventModule.NODE_CREATED, { nodeId : newNode.getID(), json: json });
        return SceneJS.withNode(newNode);
    },

    /**
     * Parses JSON into a subgraph of nodes using iterative depth-first search
     */
    _parseNodeJSON : function(v) {
        v.__visited = true;
        v.__node = this._createNode(v);
        var s = [];
        var i, len;
        if (v.nodes) {
            for (i = 0,len = v.nodes.length; i < len; i++) {
                var child = v.nodes[i];
                child.__node = this._createNode(child);
                child.__parent = v;
                s.push(child);
            }
        }
        var w;
        var u;
        while (s.length > 0) {
            w = s.pop();
            w.__parent.__node.insertNode(w.__node, 0);

            if (w.nodes) {
                for (i = 0,len = w.nodes.length; i < len; i++) {
                    u = w.nodes[i];
                    if (!u.__parent) {
                        u.__node = this._createNode(u);
                        u.__parent = w;
                        s.push(u);
                    }
                }
            }
        }
        return v.__node;
    },

    _createNode : function(json) {
        json.type = json.type || "node";
        var nodeType = this._nodeTypes[json.type];
        if (!nodeType) {
            throw "Failed to parse JSON node definition - unknown node type: '" + json.type + "'";
        }
        return new nodeType.nodeClass(this._copyCfg(json));   // Faster to instantiate class directly
    },

    /** Returns true if the {@link SceneJS.Node} with the given ID exists
     *
     * @param id ID of {@link SceneJS.Node} to find
     * @returns {Boolean} True if node exists else false
     */
    nodeExists : function(id) {
        if (!id) {
            throw "nodeExists param 'id' null or undefined";
        }
        if (typeof id != "string") {
            throw "nodeExists param 'id' not a string";
        }
        var node = SceneJS._nodeIDMap[id];
        return (node != undefined && node != null);
    },

    /**
     * Shallow copy of JSON node configs, filters out JSON-specific properties like "nodes"
     * @private
     */
    _copyCfg : function (cfg) {
        var cfg2 = {};
        for (var key in cfg) {
            if (cfg.hasOwnProperty(key) && key != "nodes") {
                cfg2[key] = cfg[key];
            }
        }
        return cfg2;
    },

    /** Schedule the destruction of a node
     * @private
     */
    _scheduleNodeDestroy : function(node) {
        this._destroyedNodes.push(node);
    },

    /** Nodes that are scheduled to be destroyed. When a node is destroyed it is added here, then at the end of each
     * render traversal, each node in here is popped and has {@link SceneJS.Node#destroy} called.
     *  @private
     */
    _destroyedNodes : [],

    /** Action the scheduled destruction of nodes
     * @private
     */
    _actionNodeDestroys : function() {
        var node;
        for (var i = this._destroyedNodes.length - 1; i >= 0; i--) {
            node = this._destroyedNodes[i];
            node._doDestroy();
            SceneJS._eventModule.fireEvent(SceneJS._eventModule.NODE_CREATED, { nodeId : node.getID() });
        }
        this._destroyedNodes = [];
    },

    /**
     * Node factory funcs mapped to type
     * @private
     */
    _nodeTypes: {},

    /**
     * ID map of all existing nodes.
     * Referenced by {@link SceneJS.Node}.
     * @private
     */
    _nodeIDMap : {},

    /**
     * Links each node that is an instance target back to
     * it's instance- for each target node a map of the
     * {@link SceneJS.Instance} nodes pointing to it
     */
    _nodeInstanceMap : {},

    /*----------------------------------------------------------------------------------------------------------------
     * Messaging System
     *
     *
     *--------------------------------------------------------------------------------------------------------------*/

    Message : new (function() {

        /** Sends a message to SceneJS - docs at http://scenejs.wikispaces.com/SceneJS+Messaging+System
         *
         * @param message
         */
        this.sendMessage = function (message) {
            if (!message) {
                throw "sendMessage param 'message' null or undefined";
            }
            var commandId = message.command;
            if (!commandId) {
                throw "Message element expected: 'command'";
            }
            var commandService = SceneJS.Services.getService(SceneJS.Services.COMMAND_SERVICE_ID);
            var command = commandService.getCommand(commandId);

            if (!command) {
                throw "Message command not supported: '" + commandId + "' - perhaps this command needs to be added to the SceneJS Command Service?";
            }
            command.execute(message);
        };
    })(),

    /**
     * @private
     */
    _inherit : function(DerivedClassName, BaseClassName) {
        DerivedClassName.prototype = new BaseClassName();
        DerivedClassName.prototype.constructor = DerivedClassName;
    },

    /** Creates a namespace
     * @private
     */
    _namespace : function() {
        var a = arguments, o = null, i, j, d, rt;
        for (i = 0; i < a.length; ++i) {
            d = a[i].split(".");
            rt = d[0];
            eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
            for (j = 1; j < d.length; ++j) {
                o[d[j]] = o[d[j]] || {};
                o = o[d[j]];
            }
        }
    },

    /**
     * Returns a key for a vacant slot in the given map
     * @private
     */
    _createKeyForMap : function(keyMap, prefix) {
        var i = 0;
        while (true) {
            var key = prefix + i++;
            if (!keyMap[key]) {
                return key;
            }
        }
    },

    _getBaseURL : function(url) {
        var i = url.lastIndexOf("/");
        if (i == 0 || i == -1) {
            return "";
        }
        return url.substr(0, i + 1);
    },

    /**
     * Returns true if object is an array
     * @private
     */
    _isArray : function(testObject) {
        return testObject && !(testObject.propertyIsEnumerable('length'))
                && typeof testObject === 'object' && typeof testObject.length === 'number';
    },

    _shallowClone : function(o) {
        var o2 = {};
        for (var name in o) {
            if (o.hasOwnProperty(name)) {
                o2[name] = o[name]
            }
        }
        return o2;
    } ,

    /** Add properties of o to o2 where undefined or null on o2
     */
    _applyIf : function(o, o2) {
        for (var name in o) {
            if (o.hasOwnProperty(name)) {
                if (o2[name] == undefined || o2[name] == null) {
                    o2[name] = o[name];
                }
            }
        }
        return o2;
    },

    /** Add properties of o to o2, overwriting them on o2 if already there
     */
    _apply : function(o, o2) {
        for (var name in o) {
            if (o.hasOwnProperty(name)) {
                o2[name] = o[name];
            }
        }
        return o2;
    }
};

SceneJS._namespace("SceneJS");

window["SceneJS"] = SceneJS;

<commit_msg>Augusto's optimisation for unique ID generation<commit_after>/**
 * @class SceneJS
 * SceneJS name space
 * @singleton
 */
var SceneJS = {

    /** Version of this release
     */
    VERSION: '0.8',

    /** Names of supported WebGL canvas contexts
     */
    SUPPORTED_WEBGL_CONTEXT_NAMES:["webgl", "experimental-webgl", "webkit-3d", "moz-webgl", "moz-glweb20"],

    /** Extension point to create a new node type.
     *
     * @param {string} type Name of new subtype
     * @param {string} superType Optional name of super-type - {@link SceneJS.Node} by default
     * @return {class} New node class
     */
    createNodeType : function(type, superType) {
        if (!type) {
            throw "createNodeType param 'type' is null or undefined";
        }
        if (typeof type != "string") {
            throw "createNodeType param 'type' should be a string";
        }
        var supa = this._nodeTypes[superType || "node"];
        if (!supa) {
            throw "undefined superType: '" + superType + "'";
        }
        var nodeType = function() {                  // Create class
            supa.nodeClass.apply(this, arguments);
            this._attr.nodeType = type;
        };
        SceneJS._inherit(nodeType, supa.nodeClass);

        var nodeFunc = function() {                // Create factory function
            var n = new nodeType();
            nodeType.prototype.constructor.apply(n, arguments);
            n._attr.nodeType = type;
            return n;
        };
        this._registerNode(type, nodeType, nodeFunc);
        SceneJS[type] = nodeFunc;
        return nodeType;
    },

    _registerNode : function(type, nodeClass, nodeFunc) {
        this._nodeTypes[type] = {
            nodeClass : nodeClass,
            nodeFunc: nodeFunc
        };
    },

    /**
     * Factory function to create a scene (sub)graph from JSON
     * @param json
     * @return {SceneJS.Node} Root of (sub)graph
     */
    createNode : function(json) {
        if (!json) {
            throw "createNode param 'json' is null or undefined";
        }
        var newNode = this._parseNodeJSON(json);
        SceneJS._eventModule.fireEvent(SceneJS._eventModule.NODE_CREATED, { nodeId : newNode.getID(), json: json });
        return SceneJS.withNode(newNode);
    },

    /**
     * Parses JSON into a subgraph of nodes using iterative depth-first search
     */
    _parseNodeJSON : function(v) {
        v.__visited = true;
        v.__node = this._createNode(v);
        var s = [];
        var i, len;
        if (v.nodes) {
            for (i = 0,len = v.nodes.length; i < len; i++) {
                var child = v.nodes[i];
                child.__node = this._createNode(child);
                child.__parent = v;
                s.push(child);
            }
        }
        var w;
        var u;
        while (s.length > 0) {
            w = s.pop();
            w.__parent.__node.insertNode(w.__node, 0);

            if (w.nodes) {
                for (i = 0,len = w.nodes.length; i < len; i++) {
                    u = w.nodes[i];
                    if (!u.__parent) {
                        u.__node = this._createNode(u);
                        u.__parent = w;
                        s.push(u);
                    }
                }
            }
        }
        return v.__node;
    },

    _createNode : function(json) {
        json.type = json.type || "node";
        var nodeType = this._nodeTypes[json.type];
        if (!nodeType) {
            throw "Failed to parse JSON node definition - unknown node type: '" + json.type + "'";
        }
        return new nodeType.nodeClass(this._copyCfg(json));   // Faster to instantiate class directly
    },

    /** Returns true if the {@link SceneJS.Node} with the given ID exists
     *
     * @param id ID of {@link SceneJS.Node} to find
     * @returns {Boolean} True if node exists else false
     */
    nodeExists : function(id) {
        if (!id) {
            throw "nodeExists param 'id' null or undefined";
        }
        if (typeof id != "string") {
            throw "nodeExists param 'id' not a string";
        }
        var node = SceneJS._nodeIDMap[id];
        return (node != undefined && node != null);
    },

    /**
     * Shallow copy of JSON node configs, filters out JSON-specific properties like "nodes"
     * @private
     */
    _copyCfg : function (cfg) {
        var cfg2 = {};
        for (var key in cfg) {
            if (cfg.hasOwnProperty(key) && key != "nodes") {
                cfg2[key] = cfg[key];
            }
        }
        return cfg2;
    },

    /** Schedule the destruction of a node
     * @private
     */
    _scheduleNodeDestroy : function(node) {
        this._destroyedNodes.push(node);
    },

    /** Nodes that are scheduled to be destroyed. When a node is destroyed it is added here, then at the end of each
     * render traversal, each node in here is popped and has {@link SceneJS.Node#destroy} called.
     *  @private
     */
    _destroyedNodes : [],

    /** Action the scheduled destruction of nodes
     * @private
     */
    _actionNodeDestroys : function() {
        var node;
        for (var i = this._destroyedNodes.length - 1; i >= 0; i--) {
            node = this._destroyedNodes[i];
            node._doDestroy();
            SceneJS._eventModule.fireEvent(SceneJS._eventModule.NODE_CREATED, { nodeId : node.getID() });
        }
        this._destroyedNodes = [];
    },

    /**
     * Node factory funcs mapped to type
     * @private
     */
    _nodeTypes: {},

    /**
     * ID map of all existing nodes.
     * Referenced by {@link SceneJS.Node}.
     * @private
     */
    _nodeIDMap : {},

    /**
     * Links each node that is an instance target back to
     * it's instance- for each target node a map of the
     * {@link SceneJS.Instance} nodes pointing to it
     */
    _nodeInstanceMap : {},

    /*----------------------------------------------------------------------------------------------------------------
     * Messaging System
     *
     *
     *--------------------------------------------------------------------------------------------------------------*/

    Message : new (function() {

        /** Sends a message to SceneJS - docs at http://scenejs.wikispaces.com/SceneJS+Messaging+System
         *
         * @param message
         */
        this.sendMessage = function (message) {
            if (!message) {
                throw "sendMessage param 'message' null or undefined";
            }
            var commandId = message.command;
            if (!commandId) {
                throw "Message element expected: 'command'";
            }
            var commandService = SceneJS.Services.getService(SceneJS.Services.COMMAND_SERVICE_ID);
            var command = commandService.getCommand(commandId);

            if (!command) {
                throw "Message command not supported: '" + commandId + "' - perhaps this command needs to be added to the SceneJS Command Service?";
            }
            command.execute(message);
        };
    })(),

    /**
     * @private
     */
    _inherit : function(DerivedClassName, BaseClassName) {
        DerivedClassName.prototype = new BaseClassName();
        DerivedClassName.prototype.constructor = DerivedClassName;
    },

    /** Creates a namespace
     * @private
     */
    _namespace : function() {
        var a = arguments, o = null, i, j, d, rt;
        for (i = 0; i < a.length; ++i) {
            d = a[i].split(".");
            rt = d[0];
            eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
            for (j = 1; j < d.length; ++j) {
                o[d[j]] = o[d[j]] || {};
                o = o[d[j]];
            }
        }
    },

    /**
     * Returns a key for a vacant slot in the given map
     * @private
     */
    // Add a new function that returns a unique map key.
    _last_unique_id: 0,
    _createKeyForMap : function(keyMap, prefix) {
        while (true) {
            var key = prefix + SceneJS._last_unique_id++;
            if (!keyMap[key]) {
                return key;
            }
        }
    },

    _getBaseURL : function(url) {
        var i = url.lastIndexOf("/");
        if (i == 0 || i == -1) {
            return "";
        }
        return url.substr(0, i + 1);
    },

    /**
     * Returns true if object is an array
     * @private
     */
    _isArray : function(testObject) {
        return testObject && !(testObject.propertyIsEnumerable('length'))
                && typeof testObject === 'object' && typeof testObject.length === 'number';
    },

    _shallowClone : function(o) {
        var o2 = {};
        for (var name in o) {
            if (o.hasOwnProperty(name)) {
                o2[name] = o[name]
            }
        }
        return o2;
    } ,

    /** Add properties of o to o2 where undefined or null on o2
     */
    _applyIf : function(o, o2) {
        for (var name in o) {
            if (o.hasOwnProperty(name)) {
                if (o2[name] == undefined || o2[name] == null) {
                    o2[name] = o[name];
                }
            }
        }
        return o2;
    },

    /** Add properties of o to o2, overwriting them on o2 if already there
     */
    _apply : function(o, o2) {
        for (var name in o) {
            if (o.hasOwnProperty(name)) {
                o2[name] = o[name];
            }
        }
        return o2;
    }
};

SceneJS._namespace("SceneJS");

window["SceneJS"] = SceneJS;

<|endoftext|>


<commit_before>/* globals ServiceConfiguration: 1 */
import { Meteor } from 'meteor/meteor'
/*
  Set up oAuth for Google, Facebook and Twitter
*/

var settings = Meteor.settings[process.env.NODE_ENV]
if (settings !== undefined) {
  // Google
  ServiceConfiguration.configurations.upsert(
    { service: 'google' },
    {
      $set: {
        'loginStyle': 'popup',
        'clientId': settings.google.oauth_key,
        'secret': settings.google.oauth_secret
      }
    }
  )

  // Facebook
  ServiceConfiguration.configurations.upsert(
    {'service': 'facebook'},
    {
      $set: {
        'appId': settings.facebook.oauth_key,
        'secret': settings.facebook.oauth_secret,
        'loginStyle': 'popup'
      }
    }
  )
}

Accounts.onCreateUser(function (options, user) {
  if (options.profile) user.profile = options.profile

  if (!options.email) {
    const details = getDetailsFromService(user.services)
    user.profile = details
  } else {
    user.profile = {'name': options.email}
  }

  // Set defaults
  user.attendance = []

  return user
})

function getDetailsFromService (services) {
  const serviceName = services.google ? 'google' : 'facebook'
  const service = services[serviceName]

  return {
    name: service.name,
    picture: service.picture
  }
}
<commit_msg>Remove facebook login<commit_after>/* globals ServiceConfiguration: 1 */
import { Meteor } from 'meteor/meteor'
/*
  Set up oAuth for Google (others except Facebook are TODO)
*/

var settings = Meteor.settings[process.env.NODE_ENV]
if (settings !== undefined) {
  // Google
  ServiceConfiguration.configurations.upsert(
    { service: 'google' },
    {
      $set: {
        'loginStyle': 'popup',
        'clientId': settings.google.oauth_key,
        'secret': settings.google.oauth_secret
      }
    }
  )

Accounts.onCreateUser(function (options, user) {
  if (options.profile) user.profile = options.profile

  if (!options.email) {
    const details = getDetailsFromService(user.services)
    user.profile = details
  } else {
    user.profile = {'name': options.email}
  }

  // Set defaults
  user.attendance = []

  return user
})

function getDetailsFromService (services) {
  const serviceName = 'google'
  const service = services[serviceName]

  return {
    name: service.name,
    picture: service.picture
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var minimist = require('minimist');
var level = require('level');
var strftime = require('strftime');
var sprintf = require('sprintf');
var through = require('through');
var editor = require('editor');
var stringify = require('json-stable-stringify');
var os = require('os');
var tmpdir = (os.tmpdir || os.tmpDir)();

var argv = minimist(process.argv.slice(2), {
    alias: { m: 'message', v: 'verbose', a: 'archive', t: 'type' }
});
var HOME = process.env.HOME || process.env.USERPROFILE;
var datadir = argv.d || path.join(HOME, '.clocker');
mkdirp.sync(datadir);

var db = level(path.join(datadir, 'db'), { encoding: 'json' });

if (argv.h) usage(0)
else if (argv._[0] === 'start') {
    var d = argv.date ? new Date(argv.date) : new Date;
    var message = argv.message;
    var type = argv.type;
    start(d, message, type, error);
}
else if (argv._[0] === 'stop') {
    var d = argv.date ? new Date(argv.date) : new Date;
    var k = argv.key || argv._[1];
    if (k) {
        var key = getKey(k);
        db.get(key, function (err, value) {
            if (err) error(err)
            else onrowstop({ key: key, value: value })
        });
    }
    else {
        db.createReadStream({
            gt: 'time!', lt: 'time!~',
            limit: 1, reverse: true
        }).once('data', onrowstop);
    }
    function onrowstop (row) {
        var m = argv.message;
        if (m) {
            if (row.value.message) m = row.value.message + '\n' + m;
            row.value.message = m;
        }
        row.value.end = strftime('%F %T', d);
        db.put(row.key, row.value, error);
    }
}
else if (argv._[0] === 'restart') {
    var k = argv.key || argv._[1];
    if (k) {
        db.get(getKey(k), function (err, value) {
            if (err) error(err);
            else onrowrestart({ value: value });
        });
    }
    else {
        getLastRow(onrowrestart);
    }

    function onrowrestart (row) {
        start(new Date, row.value.message, row.value.type, error);
    }
}
else if (argv._[0] === 'add' && argv._.length === 3) {
    var start = strftime('%F %T', new Date(argv._[1]));
    var end = strftime('%F %T', new Date(argv._[2]));
    var message = argv.message;
    var type = argv.type;

    var value = { type: type, message: message, end: end };
    var pkey = 'time!' + start;
    var tkey = 'time-type!' + type + '!' + start;

    db.batch([
        { type: 'put', key: pkey, value: value },
        { type: 'put', key: tkey, value: 0 }
    ], error);
}
else if (argv._[0] === 'status') {
    var s = db.createReadStream({
        gt: 'time!', lt: 'time!~',
        limit: 1, reverse: true
    });
    s.once('data', function (row) {
        var started = new Date(row.key.split('!')[1]);
        if (!row.value.end) {
            var elapsed = (new Date) - started;
            console.log('elapsed time: ' + fmt(elapsed));
        }
        else {
            console.log('stopped');
        }
    });
}
else if (argv._[0] === 'data') {
    var type = argv.type || argv._[1];
    var typeIsRegExp = isRegExp(type);
    var rate = argv.rate || argv.r || argv._[2];
    var title = argv.title || 'consulting';

    var s = db.createReadStream({
        gt: 'time!' + (argv.gt || ''),
        lt: 'time!' + (argv.lt || '~')
    });
    var rows = [];
    var write = function (row) {
        if (row.value.archive && !argv.archive) return;
        if (!type) rows.push(row);
        if (row.value.type === type) rows.push(row)
        if (typeIsRegExp && testRegExp(type, row.value.type)) rows.push(row)
    };
    s.pipe(through(write, function () {
        var hours = rows.reduce(function reducer (acc, row) {
            var start = new Date(row.key.split('!')[1]);
            var end = row.value.end ? new Date(row.value.end) : new Date;
            var key = strftime('%F', start);
            if (key !== strftime('%F', end)) {
                var nextDay = new Date(start);
                nextDay.setDate(start.getDate() + 1);
                nextDay.setHours(0);
                nextDay.setMinutes(0);
                nextDay.setSeconds(0);
                nextDay.setMilliseconds(0);

                acc = reducer(acc, {
                    key: 'time!' + strftime('%F %T', nextDay),
                    value: row.value
                });
                end = nextDay;
            }
            var hours = (end - start) / 1000 / 60 / 60;
            if (!acc[key]) {
                acc[key] = {
                    date: strftime('%F', start),
                    hours: 0
                };
            }
            acc[key].hours += hours;
            return acc;
        }, {});

        console.log(stringify([ {
            title: title,
            rate: rate,
            hours: Object.keys(hours).map(function (key) {
                var h = hours[key];
                return {
                    date: h.date,
                    hours: Number(sprintf('%.2f', h.hours))
                };
            })
        } ], { space: 2 }));
    }));
}
else if (argv._[0] === 'csv') {
    // print header
    console.log('Key,Date,Start,End,Duration,Archived,Type,Message');

    var s = db.createReadStream({
        gt: 'time!' + (argv.gt || ''),
        lt: 'time!' + (argv.lt || '~')
    });
    s.on('error', error);
    s.pipe(through(function (row) {
        if (row.value.archive && !argv.archive) return;
        if (argv.type && row.value.type !== argv.type) return;

        var start = new Date(row.key.split('!')[1]);
        var end = row.value.end && new Date(row.value.end);
        var elapsed = (end ? end : new Date) - start;

        console.log('%s,%s,%s,%s,%s,%s,"%s","%s"',
            toStamp(row.key),
            strftime('%F', start),
            strftime('%T', start),
            end ? strftime('%T', end) : 'NOW',
            fmt(elapsed),
            (row.value.archive ? 'A' : ''),
            (row.value.type || '').replace('"', '""'),
            (row.value.message || '').replace('"', '""')
        );
    }));
}
else if (argv._[0] === 'list') {
    var s = db.createReadStream({
        gt: 'time!' + (argv.gt || ''),
        lt: 'time!' + (argv.lt || '~')
    });
    s.on('error', error);
    s.pipe(through(function (row) {
        if (argv.raw) return console.log(stringify(row));
        if (row.value.archive && !argv.archive) return;
        if (argv.type && !isRegExp(argv.type) && row.value.type !== argv.type) return;
        if (argv.type && isRegExp(argv.type) && !testRegExp(argv.type, row.value.type)) return;

        var start = new Date(row.key.split('!')[1]);
        var end = row.value.end && new Date(row.value.end);
        var elapsed = (end ? end : new Date) - start;

        console.log(
            '%s  %s  [ %s - %s ]  (%s)%s%s',
            toStamp(row.key),
            strftime('%F', start),
            strftime('%T', start),
            end ? strftime('%T', end) : 'NOW',
            fmt(elapsed),
            (row.value.type ? '  [' + row.value.type + ']' : ''),
            (row.value.archive ? ' A' : '')
        );
        if (argv.verbose && row.value.message) {
            var lines = row.value.message.split('\n');
            console.log();
            lines.forEach(function (line) {
                console.log('    ' + line);
            });
            console.log();
        }
    }));
}
else if (argv._[0] === 'get') {
    var key = getKey(argv._[1]);
    db.get(key, function (err, row) {
        if (err) return error(err);
        console.log(row);
    });
}
else if (argv._[0] === 'rm') {
    argv._.slice(1).forEach(function (k) {
        var key = getKey(k);
        db.del(key, error);
    });
}
else if (argv._[0] === 'set') {
    var stamp;
    var prop;
    var value;

    if (argv._.length < 3) {
        return error('clocker set [STAMP] KEY VALUE');
    }
    else if (argv._.length === 3) {
        getLastRow(function (row) {
            stamp = row.key.split('!')[1];
            prop = argv._[1];
            value = argv._.slice(2).join(' ');
            set(stamp, prop, value);
        });
    }
    else {
        stamp = argv._[1];
        prop = argv._[2];
        value = argv._.slice(3).join(' ');
        set(stamp, prop, value);
    }
}
else if (argv._[0] === 'edit') {
    var stamp = argv._[1];
    var key = getKey(stamp);
    var prop = argv._[2];

    db.get(key, function (err, row) {
        if (err) return error(err);
        var src = stringify(prop ? row[prop] : row, { space: 2 });
        edit(src, function (err, src_) {
            if (err) return error(err);
            if (prop) {
                row[prop] = src_;
                return set(stamp, prop, row);
            }
            row = JSON.parse(src_);
            try { var x = JSON.parse(src_) }
            catch (err) {
                return error('error parsing json');
            }
            db.put(key, x, function (err) {
                if (err) return error(err);
                if (!x || typeof x !== 'object') {
                    return error('not an object: ' + x);
                }
                if (x.type !== row.type) {
                    set(stamp, 'type', x.type, row.type);
                }
            });
        });
    });
}
else if (argv._[0] === 'insert') {
    var key = getKey(argv._[1]);
    db.put(key, {}, function (err) {
        if (err) return error(err);
    });
}
else if (argv._[0] === 'archive' || argv._[0] === 'unarchive') {
    var value = argv._[0] === 'archive';
    if (argv._.length > 1) {
        return argv._.slice(1).forEach(function (stamp) {
            set(stamp, 'archive', value);
        });
    }
    var s = db.createReadStream({
        gt: 'time!' + (argv.gt || ''),
        lt: 'time!' + (argv.lt || '~')
    });
    s.on('error', error);
    s.pipe(through(function (row) {
        if (row.value.archive) return;
        if (argv.type && row.value.type !== argv.type) return;

        row.value.archive = value;
        db.put(row.key, row.value, error);
    }));
}
else usage(1)

function start (date, message, type, cb) {
    var pkey = strftime('time!%F %T', d);
    var tkey = 'time-type!' + type + '!' + strftime('%F %T', d);
    db.batch([
        { type: 'put', key: pkey, value: { type: type, message: message } },
        { type: 'put', key: tkey, value: 0 }
    ], cb);
}

function edit (src, cb) {
    var file = path.join(tmpdir, 'clocker-' + Math.random());
    fs.writeFile(file, src || '', function (err) {
        if (err) error(err)
        else editor(file, function (code, sig) {
            if (code !== 0) {
                return error('non-zero exit code from $EDITOR');
            }
            fs.readFile(file, function (err, src) {
                if (err) error(err)
                else cb(null, src)
            });
        });
    });
}

function usage (code) {
    var rs = fs.createReadStream(__dirname + '/usage.txt');
    rs.pipe(process.stdout);
    rs.on('close', function () {
        if (code) process.exit(code);
    });
}

function pad (s, len) {
    return Array(Math.max(0, len - String(s).length + 1)).join('0') + s;
}

function fmt (elapsed) {
    var n = elapsed / 1000;
    var hh = pad(Math.floor(n / 60 / 60), 2);
    var mm = pad(Math.floor(n / 60 % 60), 2);
    var ss = pad(Math.floor(n % 60), 2);
    return [ hh, mm, ss ].join(':');
}

function set (stamp, prop, value, originalValue) {
    var key = getKey(stamp);

    if (prop === 'stop') {
        // Use 'stop' as synonym for 'end'
        prop = 'end';
    }

    if (prop === 'end') {
        db.get(key, function (err, row) {
            if (err) return error(err);
            row[prop] = updateDate(key, value, originalValue || row[prop]);
            db.put(key, row, error);
        });
    }
    else if (prop === 'start') {
        db.get(key, function (err, row) {
            if (err) return error(err);
            var newKey = 'time!' + updateDate(key, value, key.split('!')[1]);

            db.batch([
                { type: 'put', key: newKey, value: row },
                { type: 'del', key: key }
            ], error);
        });
    }
    else if (prop === 'type') {
        db.get(key, function (err, row) {
            if (err) return error(err);
            var prevType = originalValue || row.type;
            row.type = value;
            db.batch([
                prevType && { type: 'del', key: prevType },
                { type: 'put', key: key, value: row }
            ].filter(Boolean), error);
        });
    }
    else {
        db.get(key, function (err, row) {
            if (err) return error(err);
            if (value === '') delete row[prop];
            else row[prop] = value;
            db.put(key, row, error);
        });
    }
}

function error (err) {
    if (!err) return;
    console.error(String(err));
    process.exit(1);
}

function toStamp (s) {
    return Math.floor(new Date(s.split('!')[1]).valueOf() / 1000);
}

function getKey (x) {
    if (!/^\d+$/.test(x)) return 'time!' + x;
    return strftime('time!%F %T', new Date(x * 1000));
}

function getLastRow (callback) {
    db.createReadStream({
        gt: 'time!', lt: 'time!~',
        limit: 1, reverse: true
    }).once('data', callback);
}

function updateDate (key, value, old) {
    var d = new Date(value);
    if (isNaN(d.valueOf())) {
        if (!old || isNaN(old)) {
            old = key.split('!')[1];
        }
        d = new Date(old.split(' ')[0] + ' ' + value);
    }
    return strftime('%F %T', d);
}

function isRegExp (str) {
    return /^\/.*\/$/.test(str);
}

function testRegExp (re, str) {
    return RegExp(re.slice(1,-1)).test(str);
}
<commit_msg>Use RegExp for csv output too<commit_after>#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var minimist = require('minimist');
var level = require('level');
var strftime = require('strftime');
var sprintf = require('sprintf');
var through = require('through');
var editor = require('editor');
var stringify = require('json-stable-stringify');
var os = require('os');
var tmpdir = (os.tmpdir || os.tmpDir)();

var argv = minimist(process.argv.slice(2), {
    alias: { m: 'message', v: 'verbose', a: 'archive', t: 'type' }
});
var HOME = process.env.HOME || process.env.USERPROFILE;
var datadir = argv.d || path.join(HOME, '.clocker');
mkdirp.sync(datadir);

var db = level(path.join(datadir, 'db'), { encoding: 'json' });

if (argv.h) usage(0)
else if (argv._[0] === 'start') {
    var d = argv.date ? new Date(argv.date) : new Date;
    var message = argv.message;
    var type = argv.type;
    start(d, message, type, error);
}
else if (argv._[0] === 'stop') {
    var d = argv.date ? new Date(argv.date) : new Date;
    var k = argv.key || argv._[1];
    if (k) {
        var key = getKey(k);
        db.get(key, function (err, value) {
            if (err) error(err)
            else onrowstop({ key: key, value: value })
        });
    }
    else {
        db.createReadStream({
            gt: 'time!', lt: 'time!~',
            limit: 1, reverse: true
        }).once('data', onrowstop);
    }
    function onrowstop (row) {
        var m = argv.message;
        if (m) {
            if (row.value.message) m = row.value.message + '\n' + m;
            row.value.message = m;
        }
        row.value.end = strftime('%F %T', d);
        db.put(row.key, row.value, error);
    }
}
else if (argv._[0] === 'restart') {
    var k = argv.key || argv._[1];
    if (k) {
        db.get(getKey(k), function (err, value) {
            if (err) error(err);
            else onrowrestart({ value: value });
        });
    }
    else {
        getLastRow(onrowrestart);
    }

    function onrowrestart (row) {
        start(new Date, row.value.message, row.value.type, error);
    }
}
else if (argv._[0] === 'add' && argv._.length === 3) {
    var start = strftime('%F %T', new Date(argv._[1]));
    var end = strftime('%F %T', new Date(argv._[2]));
    var message = argv.message;
    var type = argv.type;

    var value = { type: type, message: message, end: end };
    var pkey = 'time!' + start;
    var tkey = 'time-type!' + type + '!' + start;

    db.batch([
        { type: 'put', key: pkey, value: value },
        { type: 'put', key: tkey, value: 0 }
    ], error);
}
else if (argv._[0] === 'status') {
    var s = db.createReadStream({
        gt: 'time!', lt: 'time!~',
        limit: 1, reverse: true
    });
    s.once('data', function (row) {
        var started = new Date(row.key.split('!')[1]);
        if (!row.value.end) {
            var elapsed = (new Date) - started;
            console.log('elapsed time: ' + fmt(elapsed));
        }
        else {
            console.log('stopped');
        }
    });
}
else if (argv._[0] === 'data') {
    var type = argv.type || argv._[1];
    var typeIsRegExp = isRegExp(type);
    var rate = argv.rate || argv.r || argv._[2];
    var title = argv.title || 'consulting';

    var s = db.createReadStream({
        gt: 'time!' + (argv.gt || ''),
        lt: 'time!' + (argv.lt || '~')
    });
    var rows = [];
    var write = function (row) {
        if (row.value.archive && !argv.archive) return;
        if (!type) rows.push(row);
        if (row.value.type === type) rows.push(row)
        if (typeIsRegExp && testRegExp(type, row.value.type)) rows.push(row)
    };
    s.pipe(through(write, function () {
        var hours = rows.reduce(function reducer (acc, row) {
            var start = new Date(row.key.split('!')[1]);
            var end = row.value.end ? new Date(row.value.end) : new Date;
            var key = strftime('%F', start);
            if (key !== strftime('%F', end)) {
                var nextDay = new Date(start);
                nextDay.setDate(start.getDate() + 1);
                nextDay.setHours(0);
                nextDay.setMinutes(0);
                nextDay.setSeconds(0);
                nextDay.setMilliseconds(0);

                acc = reducer(acc, {
                    key: 'time!' + strftime('%F %T', nextDay),
                    value: row.value
                });
                end = nextDay;
            }
            var hours = (end - start) / 1000 / 60 / 60;
            if (!acc[key]) {
                acc[key] = {
                    date: strftime('%F', start),
                    hours: 0
                };
            }
            acc[key].hours += hours;
            return acc;
        }, {});

        console.log(stringify([ {
            title: title,
            rate: rate,
            hours: Object.keys(hours).map(function (key) {
                var h = hours[key];
                return {
                    date: h.date,
                    hours: Number(sprintf('%.2f', h.hours))
                };
            })
        } ], { space: 2 }));
    }));
}
else if (argv._[0] === 'csv') {
    // print header
    console.log('Key,Date,Start,End,Duration,Archived,Type,Message');

    var s = db.createReadStream({
        gt: 'time!' + (argv.gt || ''),
        lt: 'time!' + (argv.lt || '~')
    });
    s.on('error', error);
    s.pipe(through(function (row) {
        if (row.value.archive && !argv.archive) return;
        if (argv.type && !isRegExp(argv.type) && row.value.type !== argv.type) return;
        if (argv.type && isRegExp(argv.type) && !testRegExp(argv.type, row.value.type)) return;

        var start = new Date(row.key.split('!')[1]);
        var end = row.value.end && new Date(row.value.end);
        var elapsed = (end ? end : new Date) - start;

        console.log('%s,%s,%s,%s,%s,%s,"%s","%s"',
            toStamp(row.key),
            strftime('%F', start),
            strftime('%T', start),
            end ? strftime('%T', end) : 'NOW',
            fmt(elapsed),
            (row.value.archive ? 'A' : ''),
            (row.value.type || '').replace('"', '""'),
            (row.value.message || '').replace('"', '""')
        );
    }));
}
else if (argv._[0] === 'list') {
    var s = db.createReadStream({
        gt: 'time!' + (argv.gt || ''),
        lt: 'time!' + (argv.lt || '~')
    });
    s.on('error', error);
    s.pipe(through(function (row) {
        if (argv.raw) return console.log(stringify(row));
        if (row.value.archive && !argv.archive) return;
        if (argv.type && !isRegExp(argv.type) && row.value.type !== argv.type) return;
        if (argv.type && isRegExp(argv.type) && !testRegExp(argv.type, row.value.type)) return;

        var start = new Date(row.key.split('!')[1]);
        var end = row.value.end && new Date(row.value.end);
        var elapsed = (end ? end : new Date) - start;

        console.log(
            '%s  %s  [ %s - %s ]  (%s)%s%s',
            toStamp(row.key),
            strftime('%F', start),
            strftime('%T', start),
            end ? strftime('%T', end) : 'NOW',
            fmt(elapsed),
            (row.value.type ? '  [' + row.value.type + ']' : ''),
            (row.value.archive ? ' A' : '')
        );
        if (argv.verbose && row.value.message) {
            var lines = row.value.message.split('\n');
            console.log();
            lines.forEach(function (line) {
                console.log('    ' + line);
            });
            console.log();
        }
    }));
}
else if (argv._[0] === 'get') {
    var key = getKey(argv._[1]);
    db.get(key, function (err, row) {
        if (err) return error(err);
        console.log(row);
    });
}
else if (argv._[0] === 'rm') {
    argv._.slice(1).forEach(function (k) {
        var key = getKey(k);
        db.del(key, error);
    });
}
else if (argv._[0] === 'set') {
    var stamp;
    var prop;
    var value;

    if (argv._.length < 3) {
        return error('clocker set [STAMP] KEY VALUE');
    }
    else if (argv._.length === 3) {
        getLastRow(function (row) {
            stamp = row.key.split('!')[1];
            prop = argv._[1];
            value = argv._.slice(2).join(' ');
            set(stamp, prop, value);
        });
    }
    else {
        stamp = argv._[1];
        prop = argv._[2];
        value = argv._.slice(3).join(' ');
        set(stamp, prop, value);
    }
}
else if (argv._[0] === 'edit') {
    var stamp = argv._[1];
    var key = getKey(stamp);
    var prop = argv._[2];

    db.get(key, function (err, row) {
        if (err) return error(err);
        var src = stringify(prop ? row[prop] : row, { space: 2 });
        edit(src, function (err, src_) {
            if (err) return error(err);
            if (prop) {
                row[prop] = src_;
                return set(stamp, prop, row);
            }
            row = JSON.parse(src_);
            try { var x = JSON.parse(src_) }
            catch (err) {
                return error('error parsing json');
            }
            db.put(key, x, function (err) {
                if (err) return error(err);
                if (!x || typeof x !== 'object') {
                    return error('not an object: ' + x);
                }
                if (x.type !== row.type) {
                    set(stamp, 'type', x.type, row.type);
                }
            });
        });
    });
}
else if (argv._[0] === 'insert') {
    var key = getKey(argv._[1]);
    db.put(key, {}, function (err) {
        if (err) return error(err);
    });
}
else if (argv._[0] === 'archive' || argv._[0] === 'unarchive') {
    var value = argv._[0] === 'archive';
    if (argv._.length > 1) {
        return argv._.slice(1).forEach(function (stamp) {
            set(stamp, 'archive', value);
        });
    }
    var s = db.createReadStream({
        gt: 'time!' + (argv.gt || ''),
        lt: 'time!' + (argv.lt || '~')
    });
    s.on('error', error);
    s.pipe(through(function (row) {
        if (row.value.archive) return;
        if (argv.type && row.value.type !== argv.type) return;

        row.value.archive = value;
        db.put(row.key, row.value, error);
    }));
}
else usage(1)

function start (date, message, type, cb) {
    var pkey = strftime('time!%F %T', d);
    var tkey = 'time-type!' + type + '!' + strftime('%F %T', d);
    db.batch([
        { type: 'put', key: pkey, value: { type: type, message: message } },
        { type: 'put', key: tkey, value: 0 }
    ], cb);
}

function edit (src, cb) {
    var file = path.join(tmpdir, 'clocker-' + Math.random());
    fs.writeFile(file, src || '', function (err) {
        if (err) error(err)
        else editor(file, function (code, sig) {
            if (code !== 0) {
                return error('non-zero exit code from $EDITOR');
            }
            fs.readFile(file, function (err, src) {
                if (err) error(err)
                else cb(null, src)
            });
        });
    });
}

function usage (code) {
    var rs = fs.createReadStream(__dirname + '/usage.txt');
    rs.pipe(process.stdout);
    rs.on('close', function () {
        if (code) process.exit(code);
    });
}

function pad (s, len) {
    return Array(Math.max(0, len - String(s).length + 1)).join('0') + s;
}

function fmt (elapsed) {
    var n = elapsed / 1000;
    var hh = pad(Math.floor(n / 60 / 60), 2);
    var mm = pad(Math.floor(n / 60 % 60), 2);
    var ss = pad(Math.floor(n % 60), 2);
    return [ hh, mm, ss ].join(':');
}

function set (stamp, prop, value, originalValue) {
    var key = getKey(stamp);

    if (prop === 'stop') {
        // Use 'stop' as synonym for 'end'
        prop = 'end';
    }

    if (prop === 'end') {
        db.get(key, function (err, row) {
            if (err) return error(err);
            row[prop] = updateDate(key, value, originalValue || row[prop]);
            db.put(key, row, error);
        });
    }
    else if (prop === 'start') {
        db.get(key, function (err, row) {
            if (err) return error(err);
            var newKey = 'time!' + updateDate(key, value, key.split('!')[1]);

            db.batch([
                { type: 'put', key: newKey, value: row },
                { type: 'del', key: key }
            ], error);
        });
    }
    else if (prop === 'type') {
        db.get(key, function (err, row) {
            if (err) return error(err);
            var prevType = originalValue || row.type;
            row.type = value;
            db.batch([
                prevType && { type: 'del', key: prevType },
                { type: 'put', key: key, value: row }
            ].filter(Boolean), error);
        });
    }
    else {
        db.get(key, function (err, row) {
            if (err) return error(err);
            if (value === '') delete row[prop];
            else row[prop] = value;
            db.put(key, row, error);
        });
    }
}

function error (err) {
    if (!err) return;
    console.error(String(err));
    process.exit(1);
}

function toStamp (s) {
    return Math.floor(new Date(s.split('!')[1]).valueOf() / 1000);
}

function getKey (x) {
    if (!/^\d+$/.test(x)) return 'time!' + x;
    return strftime('time!%F %T', new Date(x * 1000));
}

function getLastRow (callback) {
    db.createReadStream({
        gt: 'time!', lt: 'time!~',
        limit: 1, reverse: true
    }).once('data', callback);
}

function updateDate (key, value, old) {
    var d = new Date(value);
    if (isNaN(d.valueOf())) {
        if (!old || isNaN(old)) {
            old = key.split('!')[1];
        }
        d = new Date(old.split(' ')[0] + ' ' + value);
    }
    return strftime('%F %T', d);
}

function isRegExp (str) {
    return /^\/.*\/$/.test(str);
}

function testRegExp (re, str) {
    return RegExp(re.slice(1,-1)).test(str);
}
<|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().g<commit_msg>GET A HAIRCUT!<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().ge<|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<commit_msg>Updated the readme again<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated <|endoftext|>


<commit_before>'use strict';
var assert = require('assert');
var escapeRegex = require('escape-string-regexp');
var path = require('path');
var slash = require('slash');
var sourceMapUrl = require('source-map-url');

function HtmlWebpackInlineSourcePlugin (options) {
  assert.equal(options, undefined, 'The HtmlWebpackInlineSourcePlugin does not accept any options');
}

HtmlWebpackInlineSourcePlugin.prototype.apply = function (compiler) {
  var self = this;

  // Hook into the html-webpack-plugin processing
  compiler.plugin('compilation', function (compilation) {
    compilation.plugin('html-webpack-plugin-alter-asset-tags', function (htmlPluginData, callback) {
      // Skip if the plugin configuration didn't set `inlineSource`
      if (!htmlPluginData.plugin.options.inlineSource) {
        return callback(null);
      }

      var regexStr = htmlPluginData.plugin.options.inlineSource;

      var result = self.processTags(compilation, regexStr, htmlPluginData);

      callback(null, result);
    });
  });
};

HtmlWebpackInlineSourcePlugin.prototype.processTags = function (compilation, regexStr, pluginData) {
  var self = this;

  var body = [];
  var head = [];

  var regex = new RegExp(regexStr);

  pluginData.head.forEach(function (tag) {
    head.push(self.processTag(compilation, regex, tag));
  });

  pluginData.body.forEach(function (tag) {
    body.push(self.processTag(compilation, regex, tag));
  });

  return { head: head, body: body };
};

HtmlWebpackInlineSourcePlugin.prototype.resolveSourceMaps = function (compilation, assetName, asset) {
  var source = asset.source();
  var out = compilation.outputOptions;
  // Get asset file absolute path
  var assetPath = path.join(out.path, assetName);
  // Extract original sourcemap URL from source string
  var mapUrlOriginal = sourceMapUrl.getFrom(source);
  // Return unmodified source if map is unspecified, URL-encoded, or already relative to site root
  if (!mapUrlOriginal || mapUrlOriginal.indexOf('data:') === 0 || mapUrlOriginal.indexOf('/') === 0) {
    return source;
  }
  // Figure out sourcemap file path *relative to the asset file path*
  var assetDir = path.dirname(assetPath);
  var mapPath = path.join(assetDir, mapUrlOriginal);
  var mapPathRelative = path.relative(out.path, mapPath);
  // Starting with Node 6, `path` module throws on `undefined`
  var publicPath = out.publicPath || '';
  // Prepend Webpack public URL path to source map relative path
  // Calling `slash` converts Windows backslashes to forward slashes
  var mapUrlCorrected = slash(path.join(publicPath, mapPathRelative));
  // Regex: exact original sourcemap URL, possibly '*/' (for CSS), then EOF, ignoring whitespace
  var regex = new RegExp(escapeRegex(mapUrlOriginal) + '(\\s*(?:\\*/)?\\s*$)');
  // Replace sourcemap URL and (if necessary) preserve closing '*/' and whitespace
  return source.replace(regex, function (match, group) {
    return mapUrlCorrected + group;
  });
};

HtmlWebpackInlineSourcePlugin.prototype.processTag = function (compilation, regex, tag) {
  var assetUrl;

  // inline js
  if (tag.tagName === 'script' && regex.test(tag.attributes.src)) {
    assetUrl = tag.attributes.src;
    tag = {
      tagName: 'script',
      closeTag: true,
      attributes: {
        type: 'text/javascript'
      }
    };

  // inline css
  } else if (tag.tagName === 'link' && regex.test(tag.attributes.href)) {
    assetUrl = tag.attributes.href;
    tag = {
      tagName: 'style',
      closeTag: true,
      attributes: {
        type: 'text/css'
      }
    };
  }

  if (assetUrl) {
    // Strip hash (i.e. for cache busting) from URL
    assetUrl = assetUrl.replace(/\?.*$/, '');
    // Strip public URL prefix from asset URL to get Webpack asset name
    var publicUrlPrefix = compilation.outputOptions.publicPath;
    var assetName = path.posix.relative(publicUrlPrefix, assetUrl);
    var asset = compilation.assets[assetName];
    var updatedSource = this.resolveSourceMaps(compilation, assetName, asset);
    tag.innerHTML = updatedSource;
  }

  return tag;
};

module.exports = HtmlWebpackInlineSourcePlugin;
<commit_msg>Correct terminology in comment<commit_after>'use strict';
var assert = require('assert');
var escapeRegex = require('escape-string-regexp');
var path = require('path');
var slash = require('slash');
var sourceMapUrl = require('source-map-url');

function HtmlWebpackInlineSourcePlugin (options) {
  assert.equal(options, undefined, 'The HtmlWebpackInlineSourcePlugin does not accept any options');
}

HtmlWebpackInlineSourcePlugin.prototype.apply = function (compiler) {
  var self = this;

  // Hook into the html-webpack-plugin processing
  compiler.plugin('compilation', function (compilation) {
    compilation.plugin('html-webpack-plugin-alter-asset-tags', function (htmlPluginData, callback) {
      // Skip if the plugin configuration didn't set `inlineSource`
      if (!htmlPluginData.plugin.options.inlineSource) {
        return callback(null);
      }

      var regexStr = htmlPluginData.plugin.options.inlineSource;

      var result = self.processTags(compilation, regexStr, htmlPluginData);

      callback(null, result);
    });
  });
};

HtmlWebpackInlineSourcePlugin.prototype.processTags = function (compilation, regexStr, pluginData) {
  var self = this;

  var body = [];
  var head = [];

  var regex = new RegExp(regexStr);

  pluginData.head.forEach(function (tag) {
    head.push(self.processTag(compilation, regex, tag));
  });

  pluginData.body.forEach(function (tag) {
    body.push(self.processTag(compilation, regex, tag));
  });

  return { head: head, body: body };
};

HtmlWebpackInlineSourcePlugin.prototype.resolveSourceMaps = function (compilation, assetName, asset) {
  var source = asset.source();
  var out = compilation.outputOptions;
  // Get asset file absolute path
  var assetPath = path.join(out.path, assetName);
  // Extract original sourcemap URL from source string
  var mapUrlOriginal = sourceMapUrl.getFrom(source);
  // Return unmodified source if map is unspecified, URL-encoded, or already relative to site root
  if (!mapUrlOriginal || mapUrlOriginal.indexOf('data:') === 0 || mapUrlOriginal.indexOf('/') === 0) {
    return source;
  }
  // Figure out sourcemap file path *relative to the asset file path*
  var assetDir = path.dirname(assetPath);
  var mapPath = path.join(assetDir, mapUrlOriginal);
  var mapPathRelative = path.relative(out.path, mapPath);
  // Starting with Node 6, `path` module throws on `undefined`
  var publicPath = out.publicPath || '';
  // Prepend Webpack public URL path to source map relative path
  // Calling `slash` converts Windows backslashes to forward slashes
  var mapUrlCorrected = slash(path.join(publicPath, mapPathRelative));
  // Regex: exact original sourcemap URL, possibly '*/' (for CSS), then EOF, ignoring whitespace
  var regex = new RegExp(escapeRegex(mapUrlOriginal) + '(\\s*(?:\\*/)?\\s*$)');
  // Replace sourcemap URL and (if necessary) preserve closing '*/' and whitespace
  return source.replace(regex, function (match, group) {
    return mapUrlCorrected + group;
  });
};

HtmlWebpackInlineSourcePlugin.prototype.processTag = function (compilation, regex, tag) {
  var assetUrl;

  // inline js
  if (tag.tagName === 'script' && regex.test(tag.attributes.src)) {
    assetUrl = tag.attributes.src;
    tag = {
      tagName: 'script',
      closeTag: true,
      attributes: {
        type: 'text/javascript'
      }
    };

  // inline css
  } else if (tag.tagName === 'link' && regex.test(tag.attributes.href)) {
    assetUrl = tag.attributes.href;
    tag = {
      tagName: 'style',
      closeTag: true,
      attributes: {
        type: 'text/css'
      }
    };
  }

  if (assetUrl) {
    // Strip query string (e.g. cache busting hash) from asset URL
    assetUrl = assetUrl.replace(/\?.*$/, '');
    // Strip public URL prefix from asset URL to get Webpack asset name
    var publicUrlPrefix = compilation.outputOptions.publicPath;
    var assetName = path.posix.relative(publicUrlPrefix, assetUrl);
    var asset = compilation.assets[assetName];
    var updatedSource = this.resolveSourceMaps(compilation, assetName, asset);
    tag.innerHTML = updatedSource;
  }

  return tag;
};

module.exports = HtmlWebpackInlineSourcePlugin;
<|endoftext|>


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

var h           = require('highland')
  , _           = require('lodash')
  , program     = require('commander')
  , XLSX        = require('xlsx')
  , request     = require('superagent')
  , through2    = require('through2')
  , mappedColumns;

var exceltoJSONStream = function(file){
  var workbook = XLSX.readFile(file);
  var ws = workbook.Sheets[workbook.SheetNames[0]];
  var json = XLSX.utils.sheet_to_json(ws);
  return h(json);
};

var lowerCasedKeys = function(row){
  const result = {};
  _.keys(row).forEach(key => result[key.toLowerCase()] = row[key]);
  return result;
};

var mapColumns = function(row){
  const result = _.assign({}, row);
  const inverted = _.invert(mappedColumns);

  _.values(mappedColumns).forEach( val => {
    result[inverted[val]] = row[val];
    delete result[val]
  });

  return result;
};

function parseMapCols(val){
  var result = {};
  var val = val.replace(/\s|\"|\{|\}|\[|\]/g, '');
  val.split(',').forEach(function(e){
    var parts = e.split(':');
    result[parts[0]] = parts[1] === 'null' ? null : parts[1];
  });
  return result;
}

program
.usage('[options] <file>')
.arguments('<file>')
.option('-u, --url <http request target>', 'URL to work with.')
.option('-c, --mapcols [override1:original1, ...]', 'Optional column headers to override originals in xls/csv.', parseMapCols)
.action(function(file) {
  mappedColumns = program.mapcols;

  exceltoJSONStream(file)
  .map(lowerCasedKeys)
  .map(mapColumns)
  .map(JSON.stringify)
  .pipe(through2.obj(function(payload, h, next){
    request
    .post(program.url)
    .send(payload)
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json')
    .end(function(err, res){
      next(err, JSON.stringify(res));
    });
  }))
  .pipe(process.stdout);
})
.parse(process.argv);<commit_msg>Updated CLI to use lib.<commit_after>#! /usr/bin/env node

'use strict';

const program     = require('commander')
    , slingg = require('../');

function parseOverrideCols(val){
  var result = {};
  var val = val.replace(/\s|\"|\{|\}|\[|\]/g, '');
  val.split(',').forEach(function(e){
    var parts = e.split(':');
    result[parts[0]] = parts[1] === 'null' ? null : parts[1];
  });
  return result;
}

function parseIgnoreCols(val){
  var result = {};
  var val = val.replace(/\s|\"|\{|\}|\[|\]/g, '');
  return val.split(',');
}

program
.usage('[options] <file>')
.arguments('<file>')
.option('-u, --url <http request target>', 'URL to work with.')
.option('-h, --override [override1:original1, ...]', 'Optional, headers to override originals in xls/csv.', parseOverrideCols)
.option('-i, --ignore [ignore1, ignore2, ...]', 'Optional, headers to ignore from xls/csv.', parseIgnoreCols)
.action(function(file) {
  const opts = {
    url: program.url,
    headers: {
      override: program.override,
      ignore: program.ignore
    }
  };
  const sl = slingg.fromPath(file, opts);
  sl.start().pipe(process.stdout);
})
.parse(process.argv);<|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, m<commit_msg>GET A HAIRCUT!<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, ma<|endoftext|>