<commit_before>'use strict'

var path = require('path')
var metalsmithConcat = require('metalsmith-concat')
var async = require('async')

module.exports = function (opts) {
  // Default configuration.
  opts = opts || {}
  opts.extname = opts.extname || '.concat'

  // Execute the plugin.
  return function (files, metalsmith, done) {
    /**
     * Check if the given file is a .concat file. Call done() with result.
     */
    function filterFile(file, done) {
      // Ensure it matches the extension.
      var correctExtention = path.extname(file) === opts.extname

      // Make sure it has defined files.
      var hasFiles = files[file].files
      done(null, correctExtention && hasFiles)
    }

    /**
     * Tell Metalsmith Concatenate to process on the given file config.
     */
    function concatenateFile(file, done) {
      // Append the concat file itself to the end of the concatenation.
      files[file].files.push(file)

      // Make sure the output is defined.
      if (!Object.prototype.hasOwnProperty.call(files[file], 'output')) {
        console.log(file)
        // Output the file to the destination, without the ".concat".
        var dir = path.dirname(file)
        var filename = path.basename(file, opts.extname)
        var final = path.join(dir, filename)
        files[file].output = final
      }

      // Tell Metalsmith Concat plugin to concatinate the files.
      metalsmithConcat(files[file])(files, metalsmith, done)
    }

    // Find all the .concat files.
    async.filter(Object.keys(files), filterFile, function (err, concats) {
      if (err) {
        done(err)
      } else {
        // Use async to process each concat object.
        async.each(concats, concatenateFile, done)
      }
    })
  }
}
<commit_msg>Remove console.log() debugging<commit_after>'use strict'

var path = require('path')
var metalsmithConcat = require('metalsmith-concat')
var async = require('async')

module.exports = function (opts) {
  // Default configuration.
  opts = opts || {}
  opts.extname = opts.extname || '.concat'

  // Execute the plugin.
  return function (files, metalsmith, done) {
    /**
     * Check if the given file is a .concat file. Call done() with result.
     */
    function filterFile(file, done) {
      // Ensure it matches the extension.
      var correctExtention = path.extname(file) === opts.extname

      // Make sure it has defined files.
      var hasFiles = files[file].files
      done(null, correctExtention && hasFiles)
    }

    /**
     * Tell Metalsmith Concatenate to process on the given file config.
     */
    function concatenateFile(file, done) {
      // Append the concat file itself to the end of the concatenation.
      files[file].files.push(file)

      // Make sure the output is defined.
      if (!Object.prototype.hasOwnProperty.call(files[file], 'output')) {
        // Output the file to the destination, without the ".concat".
        var dir = path.dirname(file)
        var filename = path.basename(file, opts.extname)
        var final = path.join(dir, filename)
        files[file].output = final
      }

      // Tell Metalsmith Concat plugin to concatinate the files.
      metalsmithConcat(files[file])(files, metalsmith, done)
    }

    // Find all the .concat files.
    async.filter(Object.keys(files), filterFile, function (err, concats) {
      if (err) {
        done(err)
      } else {
        // Use async to process each concat object.
        async.each(concats, concatenateFile, done)
      }
    })
  }
}
<|endoftext|>


<commit_before>'use strict';

var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var NanoTimer = require('nanotimer');

function StepSequencer(tempo, division, sequence) {
  this.tempo = tempo || 120;
  this.division = division || 4;
  this.sequence = sequence || [];
  this.step = 0;
  this.timer = new NanoTimer();
  this.timeout = Math.floor((60 / (tempo * division)) * 10e8) + 'n';
  this._playing = false;
  EventEmitter.call(this);
}

inherits(StepSequencer, EventEmitter);

StepSequencer.prototype._advance = function () {
  this.emit('' + this.step, this.sequence[this.step]);
  this.step = (this.step + 1);
  if (this.step === this.sequence.length) this.step = 0;
}

StepSequencer.prototype.play = function () {
  var self = this;
  if (self._playing) return;
  self.step = 0;
  self._playing = true;
  self.timer.setInterval(function () {
    self._advance.call(self);
  }, '', self.timeout);
};

StepSequencer.prototype.resume = function () {
  var self = this;
  if (self._playing) return;
  self._playing = true;
  self.timer.setInterval(function () {
    self._advance.call(self);
  }, '', self.timeout);
};

StepSequencer.prototype.stop = function () {
  this._playing = false;
  this.timer.clearInterval();
};

module.exports = StepSequencer;
<commit_msg>Return from stop is already stopped<commit_after>'use strict';

var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var NanoTimer = require('nanotimer');

function StepSequencer(tempo, division, sequence) {
  this.tempo = tempo || 120;
  this.division = division || 4;
  this.sequence = sequence || [];
  this.step = 0;
  this.timer = new NanoTimer();
  this.timeout = Math.floor((60 / (tempo * division)) * 10e8) + 'n';
  this._playing = false;
  EventEmitter.call(this);
}

inherits(StepSequencer, EventEmitter);

StepSequencer.prototype._advance = function () {
  this.emit('' + this.step, this.sequence[this.step]);
  this.step = (this.step + 1);
  if (this.step === this.sequence.length) this.step = 0;
}

StepSequencer.prototype.play = function () {
  var self = this;
  if (self._playing) return;
  self.step = 0;
  self._playing = true;
  self.timer.setInterval(function () {
    self._advance.call(self);
  }, '', self.timeout);
};

StepSequencer.prototype.resume = function () {
  var self = this;
  if (self._playing) return;
  self._playing = true;
  self.timer.setInterval(function () {
    self._advance.call(self);
  }, '', self.timeout);
};

StepSequencer.prototype.stop = function () {
  if (!this._playing) return;
  this._playing = false;
  this.timer.clearInterval();
};

module.exports = StepSequencer;
<|endoftext|>


<commit_before>var net = require('net');
var seaport = require('./lib/seaport');
var version = require('./package.json').version;

exports = module.exports = function () {
    return seaport.apply(this, arguments);
};

Object.keys(seaport).forEach(function (key) {
    exports[key] = seaport[key];
});

exports.connect = function () {
    var args = [].slice.call(arguments);
    var opts = {};
    for (var i = 0; i < args.length; i++) {
        if (typeof args[i] === 'object') {
            opts = args[i];
            args.splice(i, 1);
            break;
        }
    }
    var port = args[0] || opts.port;
    var host = args[1] || opts.host;

    if (typeof port === 'string' && typeof host === 'number') {
        host = args[0];
        port = args[1];
    }
    if (typeof port === 'string' && /:\d+$/.test(port)) {
        host = port.split(':')[0];
        port = port.split(':')[1];
    }
    if (typeof port === 'string' && /^\d+$/.test(port)) {
        port = Number(port);
    }

    var s = seaport(opts);
    var conIx = 0;

    var c = (function reconnect () {
        if (s.closed) return;

        var hubs = [ { port : port, host : host } ].concat(s.query('seaport'));
        var c = net.connect.call(null, hubs[conIx].port, hubs[conIx].host);
        conIx = (conIx + 1) % hubs.length;

        var active = true;

        c.on('connect', s.emit.bind(s, 'connect'));

        c.on('end', onend);
        c.on('error', onend);
        c.on('close', onend);

        var stream = s.createStream();

        c.pipe(stream).pipe(c);

        stream.on('synced', s.emit.bind(s, 'synced'));

        return c;

        function onend () {
            if (s.closed) return;
            if (!active) return;
            active = false;
            stream.destroy();
            s.emit('disconnect');
            setTimeout(reconnect, 1000);
        }
    })();

    s.on('close', function () {
        if (c) c.end();
    });

    return s;
};

exports.createServer = function (opts) {
    if (!opts) opts = {};
    opts.isServer = true;
    var s = seaport(opts);

    s.server = net.createServer(function (c) {
        c.on('error', function (error) {
            c.emit('end');
        });
        c.pipe(s.createStream(c.remoteAddress)).pipe(c);
    });
    s.listen = s.server.listen.bind(s.server);
    s.address = s.server.address.bind(s.server);

    s.peer = function () {
        if (!s.address()) {
            var args = arguments;
            s.once('listening', function () {
                s.peer.apply(s, args);
            });
            return;
        }
        var stream = s.createStream();
        var c = exports.connect.apply(this, arguments);
        s.on('close', c.close.bind(c));
        stream.pipe(c.createStream()).pipe(stream);

        c.register({
            role : 'seaport@' + version,
            port : s.address().port
        });
    };

    s.on('close', function () {
        s.server.close();
    });

    s.server.on('listening', s.emit.bind(s, 'listening'));
    s.server.on('connection', s.emit.bind(s, 'connection'));

    return s;
};
<commit_msg>Reconnecting sometimes picks a hub that doesn't exist.<commit_after>var net = require('net');
var seaport = require('./lib/seaport');
var version = require('./package.json').version;

exports = module.exports = function () {
    return seaport.apply(this, arguments);
};

Object.keys(seaport).forEach(function (key) {
    exports[key] = seaport[key];
});

exports.connect = function () {
    var args = [].slice.call(arguments);
    var opts = {};
    for (var i = 0; i < args.length; i++) {
        if (typeof args[i] === 'object') {
            opts = args[i];
            args.splice(i, 1);
            break;
        }
    }
    var port = args[0] || opts.port;
    var host = args[1] || opts.host;

    if (typeof port === 'string' && typeof host === 'number') {
        host = args[0];
        port = args[1];
    }
    if (typeof port === 'string' && /:\d+$/.test(port)) {
        host = port.split(':')[0];
        port = port.split(':')[1];
    }
    if (typeof port === 'string' && /^\d+$/.test(port)) {
        port = Number(port);
    }

    var s = seaport(opts);
    var conIx = 0;

    var c = (function reconnect () {
        if (s.closed) return;

        var hubs = [ { port : port, host : host } ].concat(s.query('seaport'));
        if (hubs.length <= conIx) conIx = hubs.length - 1;
        var c = net.connect.call(null, hubs[conIx].port, hubs[conIx].host);
        conIx = (conIx + 1) % hubs.length;

        var active = true;

        c.on('connect', s.emit.bind(s, 'connect'));

        c.on('end', onend);
        c.on('error', onend);
        c.on('close', onend);

        var stream = s.createStream();

        c.pipe(stream).pipe(c);

        stream.on('synced', s.emit.bind(s, 'synced'));

        return c;

        function onend () {
            if (s.closed) return;
            if (!active) return;
            active = false;
            stream.destroy();
            s.emit('disconnect');
            setTimeout(reconnect, 1000);
        }
    })();

    s.on('close', function () {
        if (c) c.end();
    });

    return s;
};

exports.createServer = function (opts) {
    if (!opts) opts = {};
    opts.isServer = true;
    var s = seaport(opts);

    s.server = net.createServer(function (c) {
        c.on('error', function (error) {
            c.emit('end');
        });
        c.pipe(s.createStream(c.remoteAddress)).pipe(c);
    });
    s.listen = s.server.listen.bind(s.server);
    s.address = s.server.address.bind(s.server);

    s.peer = function () {
        if (!s.address()) {
            var args = arguments;
            s.once('listening', function () {
                s.peer.apply(s, args);
            });
            return;
        }
        var stream = s.createStream();
        var c = exports.connect.apply(this, arguments);
        s.on('close', c.close.bind(c));
        stream.pipe(c.createStream()).pipe(stream);

        c.register({
            role : 'seaport@' + version,
            port : s.address().port
        });
    };

    s.on('close', function () {
        s.server.close();
    });

    s.server.on('listening', s.emit.bind(s, 'listening'));
    s.server.on('connection', s.emit.bind(s, 'connection'));

    return s;
};
<|endoftext|>


<commit_before>var englewood = {

    function getData(fromctx) {
        var w = fromctx.canvas.width,
            h = fromctx.canvas.height;

        return fromctx.getImageData(0, 0, w, h);
    }

    function fill(fromctx, toctx, n, options) {
        options = options || {};

        toctx = (fromctx === toctx) ? fromctx : toctx;

        var queue = [], w, h, data;

        if (fromctx instanceof ImageData) {
            w = fromctx.width;
            h = fromctx.height;
            data = fromctx.data;
        } else {
            w = fromctx.canvas.width;
            h = fromctx.canvas.height;
            data = fromctx.getImageData(0, 0, w, h).data;
        }

        for (var ix = 0, l = data.length; ix < l; ix += 4) {
            var r = data[ix + 0],
                g = data[ix + 1],
                b = data[ix + 2];
            if (!options.onto || (options.onto[0] == r &&
                options.onto[1] == g && options.onto[2] == b)) {
                queue.push(ix);
            }
        }

        toctx.fillStyle = options.fillStyle || '#f0f';
        toctx.globalAlpha = options.alpha || 1;

        if (n > queue.length && options.noOverlap) {
            throw new Error('not enough space for points');
        }

        for (var i = 0; i < n && queue.length; i++) {
            var place = Math.floor(Math.random() * queue.length),
                pos = queue.splice(place, 1),
                pos_w = ~~((pos % (w * 4)) / 4),
                pos_h = Math.floor(pos / (w * 4));
            toctx.rect(pos_w, pos_h, 1, 1);
        }

        toctx.fill();
        toctx.beginPath();
    }

    return {
        getData: getData,
        fill: fill
    };

};<commit_msg>better now.<commit_after>var englewood = {

    getData: function(fromctx) {
        var w = fromctx.canvas.width,
            h = fromctx.canvas.height;

        return fromctx.getImageData(0, 0, w, h);
    },

    fill: function(fromctx, toctx, n, options) {
        options = options || {};

        toctx = (fromctx === toctx) ? fromctx : toctx;

        var queue = [], w, h, data;

        if (fromctx instanceof ImageData) {
            w = fromctx.width;
            h = fromctx.height;
            data = fromctx.data;
        } else {
            w = fromctx.canvas.width;
            h = fromctx.canvas.height;
            data = fromctx.getImageData(0, 0, w, h).data;
        }

        for (var ix = 0, l = data.length; ix < l; ix += 4) {
            var r = data[ix + 0],
                g = data[ix + 1],
                b = data[ix + 2];
            if (!options.onto || (options.onto[0] == r &&
                options.onto[1] == g && options.onto[2] == b)) {
                queue.push(ix);
            }
        }

        toctx.fillStyle = options.fillStyle || '#f0f';
        toctx.globalAlpha = options.alpha || 1;

        if (n > queue.length && options.noOverlap) {
            throw new Error('not enough space for points');
        }

        for (var i = 0; i < n && queue.length; i++) {
            var place = Math.floor(Math.random() * queue.length),
                pos = queue.splice(place, 1),
                pos_w = ~~((pos % (w * 4)) / 4),
                pos_h = Math.floor(pos / (w * 4));
            toctx.rect(pos_w, pos_h, 1, 1);
        }

        toctx.fill();
        toctx.beginPath();
    }

};<|endoftext|>


<commit_before>'use strict';
/*
Copyright 2014 Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/

/*jslint nomen: true */
var util = require('util'),
    EventEmitter = require('events').EventEmitter,
    through = require('through'),
    stream = require('stream'),
    lastPid = 1;

function MockProcess(runner, signals) {
    var that = this,
        streamer = function () {
            /* istanbul ignore next - fallback */
            return stream.PassThrough ? new stream.PassThrough() : through();
        },
        emitted = false,
        emitter = function () {
            if (!emitted) {
                emitted = true;
                that.emit('close', that.exitCode, that.signal);
            }
        };
    EventEmitter.call(this);
    this.stdin = streamer();
    this.stdout = streamer();
    this.stderr = streamer();

    this.stderr.on('end', emitter);
    this.stderr.on('close', emitter);

    /* istanbul ignore next - polyfill */
    if (!this.stdout.setEncoding) {
        this.stdout.setEncoding = this.stderr.setEncoding = function (encoding) {
            this.encoding = encoding;
        };
    }
    this._runner = runner;
    this.signal = null;
    if(signals){
        this.signals = signals;
    }
}

util.inherits(MockProcess, EventEmitter);

MockProcess.prototype._start = function (command, args, opts) {
    var that = this,
        runner = this._runner;

    this.command = command;
    this.args = args;
    this.opts = opts;
    this.pid = lastPid;
    this.ended = false;
    lastPid += 1;

    if(runner.throws instanceof Error){
        throw runner.throws;
    }
    process.nextTick(function () {
        runner.call(that, function (exitCode) {
            if(!that.ended){
                that.ended = true;
                that.exitCode = exitCode;
                that.emit('exit', exitCode);
                that.stdout.end();
                that.stderr.end();
            }
        });
    });
    return this;
};

MockProcess.prototype.kill = function (signal) {
    var that = this;
    // if the signals object contains this signal and is *truthy*, and it is still running, exit
    if(this.signals[signal]){
        this.signal = signal;
        /* istanbul ignore else - no-op if ended */
        if(!this.ended){
            this.ended = true;
            process.nextTick(function(){
                that.emit('exit',null,signal);
                that.stdout.end();
                that.stderr.end();
            });
        }
    }
};

var ezRunner = function (exitCode, stdout, stderr) {
    var verbose,
        fn = function (cb) {
            if (verbose) {
                console.log('Run:' + this.command + ', with args');
                console.log(this.args);
                console.log('With stdout = ' + stdout);
                console.log('With stderr = ' + stderr);
                console.log('Exit code = ' + exitCode);
            }
            if (stdout) {
                this.stdout.write(stdout);
            }
            if (stderr) {
                this.stderr.write(stderr);
            }
            process.nextTick(function () {
                return cb(exitCode);
            });
        };
    fn.setVerbose = function (v) {
        verbose = !!v;
        return fn;
    };
    return fn;
};

function makeSeq(verbose) {
    var runners = [],
        fn = function (/* command, args, opts */) {
            var runner;
            if (runners.length) {
                if (verbose) {
                    console.log('Running first of ' + runners.length +
                        ' remaining functions');
                }
                runner = runners.shift();
            } else {
                console.log('No runners left, using default');
            }
            return runner;
        };

    fn.add = function (runner) {
        runners.push(runner);
    };
    return fn;
}

function ProcessList(verbose) {
    this.verbose = verbose;
    this.fns = [];
    this.defaultFn = ezRunner(0).setVerbose(verbose);
    this.strategy = null;
    this.calls = [];
}

ProcessList.prototype.setStrategy = function (strategy) {
    this.strategy = strategy;
};

ProcessList.prototype.setSignals = function (sigs) {
    this.signals = sigs;
};

ProcessList.prototype.next = function (command, args, opts) {
    var runner,
        mp;

    if (this.strategy) {
        runner = this.strategy(command, args, opts);
    }
    runner = runner || this.defaultFn;
    mp = new MockProcess(runner,this.signals);
    this.calls.push(mp);
    return mp._start(command, args, opts);
};

ProcessList.prototype.__defineGetter__('sequence', function () {
    if (!this.strategy) {
        this.strategy = makeSeq(this.verbose);
    }
    return this.strategy;
});

module.exports = function (verbose) {
    var pm = new ProcessList(verbose),
        main = function (command, args, opts) {
            return pm.next(command, args, opts);
        };

    main.__defineGetter__('sequence', function () { return pm.sequence; });
    main.__defineGetter__('calls', function () { return pm.calls.slice(); });
    main.setDefault = function (fn) { pm.defaultFn = fn; };
    main.setStrategy = function (s) { pm.setStrategy(s); };
    main.simple = function (exitCode, stdout, stderr) {
        return ezRunner(exitCode, stdout, stderr).setVerbose(verbose);
    };
    main.setSignals = function (sigs) { pm.setSignals(sigs); };

    return main;
};
<commit_msg>fix a missing verbose condition console.log<commit_after>'use strict';
/*
Copyright 2014 Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/

/*jslint nomen: true */
var util = require('util'),
    EventEmitter = require('events').EventEmitter,
    through = require('through'),
    stream = require('stream'),
    lastPid = 1;

function MockProcess(runner, signals) {
    var that = this,
        streamer = function () {
            /* istanbul ignore next - fallback */
            return stream.PassThrough ? new stream.PassThrough() : through();
        },
        emitted = false,
        emitter = function () {
            if (!emitted) {
                emitted = true;
                that.emit('close', that.exitCode, that.signal);
            }
        };
    EventEmitter.call(this);
    this.stdin = streamer();
    this.stdout = streamer();
    this.stderr = streamer();

    this.stderr.on('end', emitter);
    this.stderr.on('close', emitter);

    /* istanbul ignore next - polyfill */
    if (!this.stdout.setEncoding) {
        this.stdout.setEncoding = this.stderr.setEncoding = function (encoding) {
            this.encoding = encoding;
        };
    }
    this._runner = runner;
    this.signal = null;
    if(signals){
        this.signals = signals;
    }
}

util.inherits(MockProcess, EventEmitter);

MockProcess.prototype._start = function (command, args, opts) {
    var that = this,
        runner = this._runner;

    this.command = command;
    this.args = args;
    this.opts = opts;
    this.pid = lastPid;
    this.ended = false;
    lastPid += 1;

    if(runner.throws instanceof Error){
        throw runner.throws;
    }
    process.nextTick(function () {
        runner.call(that, function (exitCode) {
            if(!that.ended){
                that.ended = true;
                that.exitCode = exitCode;
                that.emit('exit', exitCode);
                that.stdout.end();
                that.stderr.end();
            }
        });
    });
    return this;
};

MockProcess.prototype.kill = function (signal) {
    var that = this;
    // if the signals object contains this signal and is *truthy*, and it is still running, exit
    if(this.signals[signal]){
        this.signal = signal;
        /* istanbul ignore else - no-op if ended */
        if(!this.ended){
            this.ended = true;
            process.nextTick(function(){
                that.emit('exit',null,signal);
                that.stdout.end();
                that.stderr.end();
            });
        }
    }
};

var ezRunner = function (exitCode, stdout, stderr) {
    var verbose,
        fn = function (cb) {
            if (verbose) {
                console.log('Run:' + this.command + ', with args');
                console.log(this.args);
                console.log('With stdout = ' + stdout);
                console.log('With stderr = ' + stderr);
                console.log('Exit code = ' + exitCode);
            }
            if (stdout) {
                this.stdout.write(stdout);
            }
            if (stderr) {
                this.stderr.write(stderr);
            }
            process.nextTick(function () {
                return cb(exitCode);
            });
        };
    fn.setVerbose = function (v) {
        verbose = !!v;
        return fn;
    };
    return fn;
};

function makeSeq(verbose) {
    var runners = [],
        fn = function (/* command, args, opts */) {
            var runner;
            if (runners.length) {
                if (verbose) {
                    console.log('Running first of ' + runners.length +
                        ' remaining functions');
                }
                runner = runners.shift();
            } else if (verbose) {
                console.log('No runners left, using default');
            }
            return runner;
        };

    fn.add = function (runner) {
        runners.push(runner);
    };
    return fn;
}

function ProcessList(verbose) {
    this.verbose = verbose;
    this.fns = [];
    this.defaultFn = ezRunner(0).setVerbose(verbose);
    this.strategy = null;
    this.calls = [];
}

ProcessList.prototype.setStrategy = function (strategy) {
    this.strategy = strategy;
};

ProcessList.prototype.setSignals = function (sigs) {
    this.signals = sigs;
};

ProcessList.prototype.next = function (command, args, opts) {
    var runner,
        mp;

    if (this.strategy) {
        runner = this.strategy(command, args, opts);
    }
    runner = runner || this.defaultFn;
    mp = new MockProcess(runner,this.signals);
    this.calls.push(mp);
    return mp._start(command, args, opts);
};

ProcessList.prototype.__defineGetter__('sequence', function () {
    if (!this.strategy) {
        this.strategy = makeSeq(this.verbose);
    }
    return this.strategy;
});

module.exports = function (verbose) {
    var pm = new ProcessList(verbose),
        main = function (command, args, opts) {
            return pm.next(command, args, opts);
        };

    main.__defineGetter__('sequence', function () { return pm.sequence; });
    main.__defineGetter__('calls', function () { return pm.calls.slice(); });
    main.setDefault = function (fn) { pm.defaultFn = fn; };
    main.setStrategy = function (s) { pm.setStrategy(s); };
    main.simple = function (exitCode, stdout, stderr) {
        return ezRunner(exitCode, stdout, stderr).setVerbose(verbose);
    };
    main.setSignals = function (sigs) { pm.setSignals(sigs); };

    return main;
};
<|endoftext|>


<commit_before>"use strict";

const Readable = require('stream').Readable;
const util = require('util');
const assert = require('assert');

function Chunk(inputStream, chunkSize, lastRemainder) {
	Readable.call(this);

	this._inputStream = inputStream;
	this._chunkSize = chunkSize;
	this._lastRemainder = lastRemainder;
	this._remainder = null;
	this._readBytes = 0;
	this._stop = false;
	this._waiting = false;
	this._inputExhausted = false;

	this._inputStream.once('end', function() {
		this._stop = true;
		this._inputExhausted = true;
		this.push(null);
	}.bind(this));

	// We need to listen for this, to wake up the stream
	// machinery's calls of our _read()
	this._inputStream.on('readable', function() {
		if(this._stop || !this._waiting) {
			return;
		}
		this._waiting = false;
		var buf = this._inputStream.read();
		if(buf === null) {
			return;
		}
		this._handleInputRead(buf);
	}.bind(this));
}
util.inherits(Chunk, Readable);

Chunk.prototype._handleInputRead = function(buf) {
	//console.log({buf});
	this._readBytes += buf.length;
	const overage = this._readBytes - this._chunkSize;
	if(overage >= 0) {
		this._stop = true;
		this._remainder = buf.slice(buf.length - overage);
		this.push(buf.slice(0, buf.length - overage));
		this.push(null);
	} else {
		this.push(buf);
	}
};

Chunk.prototype._read = function() {
	let buf;
	//console.log({date: new Date(), _lastRemainder: this._lastRemainder});
	if(this._lastRemainder !== null) {
		buf = this._lastRemainder;
		this._lastRemainder = null;
		this._handleInputRead(buf);
	} else {
		buf = this._inputStream.read();
		if(buf === null) {
			this._waiting = true;
		} else {
			this._handleInputRead(buf);
		}
	}
};

function* chunk(inputStream, chunkSize) {
	if(!Number.isInteger(chunkSize) || chunkSize < 1) {
		throw new Error("chunkSize must be an integer >= 1");
	}
	let lastChunk = null;
	while(true) {
		if(lastChunk && lastChunk._inputExhausted) {
			return;
		}
		lastChunk = new Chunk(inputStream, chunkSize, lastChunk && lastChunk._remainder);
		yield lastChunk;
	}
}

module.exports = {chunk, Chunk};
<commit_msg>Be a little more careful about _waiting = false<commit_after>"use strict";

const Readable = require('stream').Readable;
const util = require('util');
const assert = require('assert');

function Chunk(inputStream, chunkSize, lastRemainder) {
	Readable.call(this);

	this._inputStream = inputStream;
	this._chunkSize = chunkSize;
	this._lastRemainder = lastRemainder;
	this._remainder = null;
	this._readBytes = 0;
	this._stop = false;
	this._waiting = false;
	this._inputExhausted = false;

	this._inputStream.once('end', function() {
		this._stop = true;
		this._inputExhausted = true;
		this.push(null);
	}.bind(this));

	// We need to listen for this, to wake up the stream
	// machinery's calls of our _read()
	this._inputStream.on('readable', function() {
		if(this._stop || !this._waiting) {
			return;
		}
		var buf = this._inputStream.read();
		if(buf === null) {
			return;
		}
		this._waiting = false;
		this._handleInputRead(buf);
	}.bind(this));
}
util.inherits(Chunk, Readable);

Chunk.prototype._handleInputRead = function(buf) {
	//console.log({buf});
	this._readBytes += buf.length;
	const overage = this._readBytes - this._chunkSize;
	if(overage >= 0) {
		this._stop = true;
		this._remainder = buf.slice(buf.length - overage);
		this.push(buf.slice(0, buf.length - overage));
		this.push(null);
	} else {
		this.push(buf);
	}
};

Chunk.prototype._read = function() {
	let buf;
	//console.log({date: new Date(), _lastRemainder: this._lastRemainder});
	if(this._lastRemainder !== null) {
		buf = this._lastRemainder;
		this._lastRemainder = null;
		this._handleInputRead(buf);
	} else {
		buf = this._inputStream.read();
		if(buf === null) {
			this._waiting = true;
		} else {
			this._handleInputRead(buf);
		}
	}
};

function* chunk(inputStream, chunkSize) {
	if(!Number.isInteger(chunkSize) || chunkSize < 1) {
		throw new Error("chunkSize must be an integer >= 1");
	}
	let lastChunk = null;
	while(true) {
		if(lastChunk && lastChunk._inputExhausted) {
			return;
		}
		lastChunk = new Chunk(inputStream, chunkSize, lastChunk && lastChunk._remainder);
		yield lastChunk;
	}
}

module.exports = {chunk, Chunk};
<|endoftext|>


<commit_before>'use strict';

var Hapi = require('hapi');

var server = new Hapi.Server({debug: {request: ['info', 'error']}});

// Create server
server.connection({host: 'localhost', port: 8001});

// Add plugins
var plugins = [
	{
		register: require('hapi-mongodb'),
		options: {
			"url": "mongodb://localhost:27017/ncdevcon",
			"settings": {
				"db": {
					"native_parser": false
				}
			}
		}
	},
	{
		register: require('good'),
		options: {
			opsInterval: 1000,
			reporters: [{
				reporter: require('good-console'),
				events: { log: '*', response: '*' }
			}]
		}
	},
	{register: require('./routes/beer.js')},
	{register: require('./routes/user.js')}
];

server.register(plugins, function (err) {
	if (err) { throw err; }

	if (!module.parent) {
		server.start(function(err) {
			if (err) { throw err; }

			server.log('info', 'Server running at: ' + server.info.uri);
		});
	}
});

module.exports = server;<commit_msg>Enabled CORS<commit_after>'use strict';

var Hapi = require('hapi');

var server = new Hapi.Server({debug: {request: ['info', 'error']}});

// Create server
server.connection({host: 'localhost', port: 8001, routes: {cors: true}});

// Add plugins
var plugins = [
	{
		register: require('hapi-mongodb'),
		options: {
			"url": "mongodb://localhost:27017/ncdevcon",
			"settings": {
				"db": {
					"native_parser": false
				}
			}
		}
	},
	{
		register: require('good'),
		options: {
			opsInterval: 1000,
			reporters: [{
				reporter: require('good-console'),
				events: { log: '*', response: '*' }
			}]
		}
	},
	{register: require('./routes/beer.js')},
	{register: require('./routes/user.js')}
];

server.register(plugins, function (err) {
	if (err) { throw err; }

	if (!module.parent) {
		server.start(function(err) {
			if (err) { throw err; }

			server.log('info', 'Server running at: ' + server.info.uri);
		});
	}
});

module.exports = server;
<|endoftext|>


<commit_before>;(function iife() {
  var m = angular.module('ps.warm-toggle', []);

  m.directive('psWarmToggle', function psWarmToggle() {
    return {
      restrict: 'A',
      transclude: true,
      scope: {
        // expression controling when children are shown
        psWarmToggle: '&',
        // expression that evals to how long children can be hidden before
        // considered cool and destroyed
        psCoolDownMillis: '&'
      },
      controller: ['$scope', '$timeout', function($scope, $timeout) {
        // how long children can stay hidden until they're destroyed
        var coolDownMillis = Number($scope.psCoolDownMillis());

        // when set that means cool down timer is running
        var coolDownPromise;

        $scope.$watch('psWarmToggle()', function(value) {
          $scope.show = value;

          if (value) {
            warmed();
            cancelCoolDownTimer();
          } else {
            startCoolDownTimer(coolDownMillis);
          }
        });

        // clean up timer when this directive's scope goes away
        $scope.$on('$destroy', cancelCoolDownTimer);

        function startCoolDownTimer(time) {
          coolDownPromise = $timeout(cooled, time);
        }

        function warmed() {
          $scope.useNgShow = true;
        }

        function cooled() {
          $scope.useNgShow = false;
        }

        function cancelCoolDownTimer() {
          if (coolDownPromise) {
            $timeout.cancel(coolDownPromise);
            coolDownPromise = null;
          }
        }
      }],
      template:
      '
' +
        '
' +
          '<ng-transclude></ng-transclude>' +
        '
' +
      '
'
    }
  });
})(angular);
<commit_msg>actually use the angular coming in<commit_after>;(function iife(angular) {
  var m = angular.module('ps.warm-toggle', []);

  m.directive('psWarmToggle', function psWarmToggle() {
    return {
      restrict: 'A',
      transclude: true,
      scope: {
        // expression controling when children are shown
        psWarmToggle: '&',
        // expression that evals to how long children can be hidden before
        // considered cool and destroyed
        psCoolDownMillis: '&'
      },
      controller: ['$scope', '$timeout', function($scope, $timeout) {
        // how long children can stay hidden until they're destroyed
        var coolDownMillis = Number($scope.psCoolDownMillis());

        // when set that means cool down timer is running
        var coolDownPromise;

        $scope.$watch('psWarmToggle()', function(value) {
          $scope.show = value;

          if (value) {
            warmed();
            cancelCoolDownTimer();
          } else {
            startCoolDownTimer(coolDownMillis);
          }
        });

        // clean up timer when this directive's scope goes away
        $scope.$on('$destroy', cancelCoolDownTimer);

        function startCoolDownTimer(time) {
          coolDownPromise = $timeout(cooled, time);
        }

        function warmed() {
          $scope.useNgShow = true;
        }

        function cooled() {
          $scope.useNgShow = false;
        }

        function cancelCoolDownTimer() {
          if (coolDownPromise) {
            $timeout.cancel(coolDownPromise);
            coolDownPromise = null;
          }
        }
      }],
      template:
      '
' +
        '
' +
          '<ng-transclude></ng-transclude>' +
        '
' +
      '
'
    }
  });
})(angular);
<|endoftext|>


<commit_before>'use strict';
var os = require('os');

var nameMap = {
	'14': 'Yosemite',
	'13': 'Mavericks',
	'12': 'Mountain Lion',
	'11': 'Lion',
	'10': 'Snow Leopard',
	'9': 'Leopard',
	'8': 'Tiger',
	'7': 'Panther',
	'6': 'Jaguar',
	'5': 'Puma'
};

module.exports = function (release) {
	release = (release || os.release()).split('.')[0];
	return {
		name: nameMap[release],
		version: '10.' + (Number(release) - 4)
	};
};
<commit_msg>add OS X 10.11<commit_after>'use strict';
var os = require('os');

var nameMap = {
	'15': 'El Capitan',
	'14': 'Yosemite',
	'13': 'Mavericks',
	'12': 'Mountain Lion',
	'11': 'Lion',
	'10': 'Snow Leopard',
	'9': 'Leopard',
	'8': 'Tiger',
	'7': 'Panther',
	'6': 'Jaguar',
	'5': 'Puma'
};

module.exports = function (release) {
	release = (release || os.release()).split('.')[0];
	return {
		name: nameMap[release],
		version: '10.' + (Number(release) - 4)
	};
};
<|endoftext|>


<commit_before>var ElasticSearchClient = require('elasticsearchclient');
var db                  = new ElasticSearchClient({
    host: 'localhost',
    port: '9200'
});
var debug       = require('debug')('raabbajam:priceInserter:base');
var moment      = require('moment');
var airlines    = {"airasia": 1, "citilink": 2, "garuda": 3, "lion": 4, "sriwijaya": 5, "xpress": 6};
var dateFormats = ['DD+MM+YYYY', 'DD+MMM+YYYY', 'DD MM YYYY', 'DD MMM YYYY'];
function priceInserter (airline) {
	_kode    = airlines[airline] || 0;
	_airline = airline;
	return function (dt, price) {
		debug('running priceInserter')
		if(!!dt.rute && (dt.rute.toLowerCase() === 'rt' || dt.rute.toLowerCase() !== 'ow')){
			debug('Return route. Not cached!');
			return true;
		}
		debug('start inserting')
		insertCache(dt, price);
		insertCalendar(dt, price);
	}
}
function insertCache (dt, price) {
	debug('running insertCache')
	var _price = parseInt(price, 10) + _kode;
	var data = {
		price      : _price,
		class      : dt.class || '',
		flight     : dt.ftid || '',
		origin     : dt.ori,
		airline    : _airline,
		destination: dt.dst,
	};
	data.id = data.origin + data.destination + data.airline + data.flight + data.class;
	db.index('pluto', 'price', data, function (err, res) {
		if (err){
			debug('error insert cache', err);
			return false;
		}
		debug('insert cache', data, res)
	});
}
function insertCalendar (dt, price) {
	debug('running insertCalendar')
	var _price = parseInt(price, 10) + _kode;
	var _date  = moment(dt.dep_date, dateFormats).unix() * 1000;
	var data   = {
		date       : _date,
		price      : _price,
		origin     : dt.ori,
		airline    : _airline,
		destination: dt.dst,
	};
	data.id = data.origin + data.destination + Math.round(data.date/1000);

	getByDate(data.id, function (res) {
		var oldPrice = 0
		if(res.found){
			oldPrice = res._source && res._source.price || 0;
			debug('found oldPrice', oldPrice)
		}

		if ( oldPrice !== 0 && _price > oldPrice ){
			debug('not saved, not fit. oldPrice:', oldPrice, '. _price:', _price)
			return false;
		}

		data.price = _price;
		db.index('pluto', 'calendar', data, function (err, res) {
			if (err){
				debug('error insert calendar', err);
				return false;
			}
			debug('insert calendar', data, res)
		});
	});
}
function getByDate (_id, cb) {
	db.get('pluto', 'calendar', _id, function (err, res) {
		if (err){
			debug('error getByDate', err);
			return false;
		}
		cb(JSON.parse(res));
	});
}
module.exports = priceInserter;<commit_msg>debug<commit_after>var ElasticSearchClient = require('elasticsearchclient');
var db                  = new ElasticSearchClient({
    host: 'localhost',
    port: '9200'
});
var debug       = require('debug')('raabbajam:priceInserter:base');
var moment      = require('moment');
var airlines    = {"airasia": 1, "citilink": 2, "garuda": 3, "lion": 4, "sriwijaya": 5, "xpress": 6};
var dateFormats = ['DD+MM+YYYY', 'DD+MMM+YYYY', 'DD MM YYYY', 'DD MMM YYYY'];
<<<<<<< HEAD
=======
var moment      = require('moment');
var airlines    = {"airasia": 1, "citilink": 2, "garuda": 3, "lion": 4, "sriwijaya": 5, "xpress": 6};
var debug       = require('debug')('raabbajam:priceInserter:base');
>>>>>>> 6ebcbbc585c27c67a4c7e9e750ada7f8a7ca30b3
function priceInserter (airline) {
	_kode    = airlines[airline] || 0;
	_airline = airline;
	return function (dt, price) {
<<<<<<< HEAD
		debug('running priceInserter')
		if(!!dt.rute && (dt.rute.toLowerCase() === 'rt' || dt.rute.toLowerCase() !== 'ow')){
			debug('Return route. Not cached!');
			return true;
		}
		debug('start inserting')
=======
		if(!!dt.rute && dt.rute.toLowerCase() === 'rt'){
			console.log('Return route. Not cached!');
		}
>>>>>>> 6ebcbbc585c27c67a4c7e9e750ada7f8a7ca30b3
		insertCache(dt, price);
		insertCalendar(dt, price);
	}
}
function insertCache (dt, price) {
	debug('running insertCache')
	var _price = parseInt(price, 10) + _kode;
	var data = {
		price      : _price,
		class      : dt.class || '',
		flight     : dt.ftid || '',
		origin     : dt.ori,
		airline    : _airline,
		destination: dt.dst,
	};
	data.id = data.origin + data.destination + data.airline + data.flight + data.class;
	db.index('pluto', 'price', data, function (err, res) {
		if (err){
			debug('error insert cache', err);
			return false;
		}
		debug('insert cache', data, res)
	});
}
function insertCalendar (dt, price) {
	debug('running insertCalendar')
	var _price = parseInt(price, 10) + _kode;
	var _date  = moment(dt.dep_date, dateFormats).unix() * 1000;
	var data   = {
		date       : _date,
		price      : _price,
		origin     : dt.ori,
		airline    : _airline,
		destination: dt.dst,
	};
	data.id = data.origin + data.destination + Math.round(data.date/1000);

	getByDate(data.id, function (res) {
		var oldPrice = 0
		if(res.found){
			oldPrice = res._source && res._source.price || 0;
			debug('found oldPrice', oldPrice)
		}

		if ( oldPrice !== 0 && _price > oldPrice ){
			debug('not saved, not fit. oldPrice:', oldPrice, '. _price:', _price)
			return false;
		}

		data.price = _price;
		db.index('pluto', 'calendar', data, function (err, res) {
			if (err){
				debug('error insert calendar', err);
				return false;
			}
			debug('insert calendar', data, res)
		});
	});
}
function getByDate (_id, cb) {
	db.get('pluto', 'calendar', _id, function (err, res) {
		if (err){
			debug('error getByDate', err);
			return false;
		}
		cb(JSON.parse(res));
	});
}
module.exports = priceInserter;<|endoftext|>


<commit_before>const path = require('path')
const { readFile, readFileSync } = require('fs')
const { execFile, execFileSync } = require('child_process')
const { getOptions } = require('loader-utils')

let bsb
try {
  bsb = require.resolve('bs-platform/bin/bsb')
} catch (e) {
  throw new Error('"bs-platform" must be installed locally.\nTry running "npm i -D bs-platform"')
}

const outputDir = 'lib'

const getJsFile = (moduleDir, resourcePath) => {
  const mlFileName = resourcePath.replace(process.cwd(), '')
  const jsFileName = mlFileName.replace(/\.(ml|re)$/, '.js')
  return path.join(process.cwd(), outputDir, moduleDir, jsFileName)
}

const transformSrc = (moduleDir, src) =>
  moduleDir === 'es6' ?
  src.replace(/(from\ "\.\.?\/.*)(\.js)("\;)/g, '$1$3') :
  src.replace(/(require\("\.\.?\/.*)(\.js)("\);)/g, '$1$3')

const runBsb = callback => {
  execFile(bsb, ['-make-world'], { maxBuffer: Infinity }, callback)
}

const runBsbSync = () => {
  execFileSync(bsb, ['-make-world'], { stdio: 'pipe' })
}

const getBsbErrorMessages = err => err.match(/File [\s\S]*?:\nError: [\s\S]*?\n/g)

const getCompiledFile = (moduleDir, path, callback) => {
  runBsb((err, res) => {
    if (err) return callback(res, null)

    readFile(path, (err, res) => {
      if (err) {
        callback(err, err)
      } else {
        const src = transformSrc(moduleDir, res.toString())
        callback(null, src)
      }
    })
  })
}

const getCompiledFileSync = (moduleDir, path) => {
  try {
    runBsbSync()
  } catch (e) {
    throw e.output.toString()
  }

  const res = readFileSync(path)
  return transformSrc(moduleDir, res.toString())
}

module.exports = function loader () {
  const options = getOptions(this) || {}
  const moduleDir = options.module || 'js'

  this.addContextDependency(this.context)
  const callback = this.async()
  const compiledFilePath = getJsFile(moduleDir, this.resourcePath)

  getCompiledFile(moduleDir, compiledFilePath, (err, res) => {
    if (err) {
      const errorMessages = getBsbErrorMessages(err)

      if (!errorMessages) {
        if (!(err instanceof Error)) err = new Error(err)
        this.emitError(err)
        return callback(err, null)
      }

      errorMessages.slice(0, -1).forEach(msg => this.emitError(new Error(msg)))

      callback(new Error(errorMessages[0]), null)
    } else {
      callback(null, res)
    }
  })
}

module.exports.process = (src, filename) => {
  const moduleDir = 'js'
  const compiledFilePath = getJsFile(moduleDir, filename)

  try {
    return getCompiledFileSync(moduleDir, compiledFilePath)
  } catch (err) {
    const bsbErrorMessages = getBsbErrorMessages(err)

    if (bsbErrorMessages && bsbErrorMessages.length > 0) {
      throw new Error(bsbErrorMessages[0])
    } else {
      throw err
    }
  }
}
<commit_msg>Read bsb stderr only to avoid emit stdout as error<commit_after>const path = require('path')
const { readFile, readFileSync } = require('fs')
const { execFile, execFileSync } = require('child_process')
const { getOptions } = require('loader-utils')

let bsb
try {
  bsb = require.resolve('bs-platform/bin/bsb')
} catch (e) {
  throw new Error('"bs-platform" must be installed locally.\nTry running "npm i -D bs-platform"')
}

const outputDir = 'lib'

const getJsFile = (moduleDir, resourcePath) => {
  const mlFileName = resourcePath.replace(process.cwd(), '')
  const jsFileName = mlFileName.replace(/\.(ml|re)$/, '.js')
  return path.join(process.cwd(), outputDir, moduleDir, jsFileName)
}

const transformSrc = (moduleDir, src) =>
  moduleDir === 'es6' ?
  src.replace(/(from\ "\.\.?\/.*)(\.js)("\;)/g, '$1$3') :
  src.replace(/(require\("\.\.?\/.*)(\.js)("\);)/g, '$1$3')

const runBsb = callback => {
  execFile(bsb, ['-make-world'], { maxBuffer: Infinity }, callback)
}

const runBsbSync = () => {
  execFileSync(bsb, ['-make-world'], { stdio: 'pipe' })
}

const getBsbErrorMessages = err => err.match(/File [\s\S]*?:\nError: [\s\S]*?\n/g)

const getCompiledFile = (moduleDir, path, callback) => {
  runBsb((err, _, res) => {
    if (err) return callback(res, null)

    readFile(path, (err, res) => {
      if (err) {
        callback(err, err)
      } else {
        const src = transformSrc(moduleDir, res.toString())
        callback(null, src)
      }
    })
  })
}

const getCompiledFileSync = (moduleDir, path) => {
  try {
    runBsbSync()
  } catch (e) {
    throw e.output.toString()
  }

  const res = readFileSync(path)
  return transformSrc(moduleDir, res.toString())
}

module.exports = function loader () {
  const options = getOptions(this) || {}
  const moduleDir = options.module || 'js'

  this.addContextDependency(this.context)
  const callback = this.async()
  const compiledFilePath = getJsFile(moduleDir, this.resourcePath)

  getCompiledFile(moduleDir, compiledFilePath, (err, res) => {
    if (err) {
      const errorMessages = getBsbErrorMessages(err)

      if (!errorMessages) {
        if (!(err instanceof Error)) err = new Error(err)
        this.emitError(err)
        return callback(err, null)
      }

      errorMessages.slice(0, -1).forEach(msg => this.emitError(new Error(msg)))

      callback(new Error(errorMessages[0]), null)
    } else {
      callback(null, res)
    }
  })
}

module.exports.process = (src, filename) => {
  const moduleDir = 'js'
  const compiledFilePath = getJsFile(moduleDir, filename)

  try {
    return getCompiledFileSync(moduleDir, compiledFilePath)
  } catch (err) {
    const bsbErrorMessages = getBsbErrorMessages(err)

    if (bsbErrorMessages && bsbErrorMessages.length > 0) {
      throw new Error(bsbErrorMessages[0])
    } else {
      throw err
    }
  }
}
<|endoftext|>


<commit_before>var http = require("http");
var fetch = require('node-fetch');

function getContributions() {
  var username = "scripttease";
  fetch("https://github.com/users/" + username + "/contributions")
    .then(function(response) {
      return response.text();
    }).then(handleData);
}

getContributions();

function handleData(data) {
  var stringData = data.toString();
  var lines = stringData.split("\n");
  var pattern = /data-count="(\d+)".+data-date="(\d\d\d\d-\d\d-\d\d)"/;
  var days = lines.map(function(string) {
    return pattern.exec(string);
  }).filter(function(x) {
    return x !== null;
  }).map(function(array) {
    return {
      commits: parseInt(array[1]),
      date: array[2],
    };
  });

  console.log(days);
}
<commit_msg>Calculate longest commit streak<commit_after>var http = require("http");
var fetch = require('node-fetch');

function getContributions() {
  var username = "scripttease";
  fetch("https://github.com/users/" + username + "/contributions")
    .then(function(response) {
      return response.text();
    }).then(handleData);
}

getContributions();

function handleData(data) {
  var stringData = data.toString();
  var lines = stringData.split("\n");
  var pattern = /data-count="(\d+)".+data-date="(\d\d\d\d-\d\d-\d\d)"/;
  var days = lines.map(function(string) {
    return pattern.exec(string);
  }).filter(function(x) {
    return x !== null;
  }).map(function(array) {
    return {
      commits: parseInt(array[1]),
      date: array[2],
    };
  });

  var allStreaksArray = [];
  var streakObj;
  var streakLength = 0;
  var streaks = days.forEach(function(obj) {
    if (obj.commits !== 0) {
      streakObj =  {
        streak: streakLength += 1,
        date: obj.date,
      };
      allStreaksArray.push(streakObj);
      var longestStreakAcc = 0;
    } else {
      streakLength = 0;
    };
  });

  console.log(days);
  console.log(allStreaksArray);

  var longestStreakObj;
  var longestStreakAcc = 0;
  var longestStreak = allStreaksArray.forEach(function(obj) {
    if (obj.streak > longestStreakAcc) {
      longestStreakObj = {
        streakLength: obj.streak,
        startDate: new Date((Date.parse(new Date(obj.date))) - ((obj.streak -1)*1000*60*60*24)),
        endDate: new Date(obj.date),
      };
      longestStreakAcc = obj.streak;
    };
  });
  console.log(longestStreakObj);
}

      // var longestStreakObj;
      // var longestStreak = allStreaksArray.forEach(function(obj) {
      //   if (obj.streak >= streakLength)
      //     longestStreakObj = {
      //       streak: streakLength +1,
      //       date: obj.date,
      //     };

  // });
<|endoftext|>


<commit_before>/// <reference types="cypress" />

// test features on test-page view
context('Test Page Tests (features)', () => {
	beforeEach(() => {
		cy.visit('/test-page');
	});

	describe('Translations', () => {
		it('text contains', () => {
			cy.get('.t-t > :nth-child(2) > :nth-child(1)').contains('app.company.name');

			cy.get('.t-t > :nth-child(2) > :nth-child(3)').contains(
				'The first three letters of alphabet are: a, l and p'
			);

			cy.get('.t-t > :nth-child(4) > :nth-child(2)').contains('test.text (t) = test.text (t)');

			cy.get('.t-t > :nth-child(8) > :nth-child(1)').contains('user.name: my name');

			cy.get('.t-t > :nth-child(8) > :nth-child(2)').contains('user.email: me@test.com');

			cy.get('p').contains('content string');

			cy.get('.t-a > :nth-child(1)').contains('ffffffrom b');

			cy.get('.t-a > :nth-child(6)').contains('from viewwwwwww');
		});
	});

	describe('Helpers', () => {
		it('eq helper in subfolder works', () => {
			cy.get('.col-md-8 > :nth-child(7)').contains('[Partial] pageTitle (view) = pageTitle (view)');
			cy.get('.shouldnotberendered').should('not.exist');
		});
	});
});
<commit_msg>test(project): add cypress test for viewlist helper<commit_after>/// <reference types="cypress" />

// test features on test-page view
context('Test Page Tests (features)', () => {
	beforeEach(() => {
		cy.visit('/test-page');
	});

	describe('Translations', () => {
		it('text contains', () => {
			cy.get('.t-t > :nth-child(2) > :nth-child(1)').contains('app.company.name');

			cy.get('.t-t > :nth-child(2) > :nth-child(3)').contains(
				'The first three letters of alphabet are: a, l and p'
			);

			cy.get('.t-t > :nth-child(4) > :nth-child(2)').contains('test.text (t) = test.text (t)');

			cy.get('.t-t > :nth-child(8) > :nth-child(1)').contains('user.name: my name');

			cy.get('.t-t > :nth-child(8) > :nth-child(2)').contains('user.email: me@test.com');

			cy.get('p').contains('content string');

			cy.get('.t-a > :nth-child(1)').contains('ffffffrom b');

			cy.get('.t-a > :nth-child(6)').contains('from viewwwwwww');
		});
	});

	describe('Viewlist Helper', () => {
		it('helper shows correct number of pages', () => {
			cy.get('.cy-viewlist > :nth-child(1) > ul > li').should('have.length', 6);
			cy.get('.cy-viewlist > :nth-child(2) > ul > li').should('have.length', 3);
			cy.get('.cy-viewlist > :nth-child(3) > ul > li').should('have.length', 2);
		});
	});

	describe('Custom Helpers', () => {
		it('eq helper in subfolder works', () => {
			cy.get('.col-md-8 > :nth-child(7)').contains('[Partial] pageTitle (view) = pageTitle (view)');
			cy.get('.shouldnotberendered').should('not.exist');
		});
	});
});
<|endoftext|>


<commit_before>/*jshint -W030 */
(function() {
  'use strict';
  var tty = require('tty');
  var clc = require('cli-color');

  // Emulate the Mocha base class a little bit
  // just to get things going

   var BaseClass = function() {
    var self = this;

    this.isatty = tty.isatty(1) && tty.isatty(2);

    this.window = {
      width : self.isatty ? (
                        process.stdout.getWindowSize ?
                        process.stdout.getWindowSize(1)[0] :
                        tty.getWindowSize()[1]
                      ) : 75
    };

    this.cursor = {
      hide: function(){
        self.isatty && process.stdout.write('\u001b[?25l');
      },

      show: function(){
        self.isatty && process.stdout.write('\u001b[?25h');
      },

      deleteLine: function(){
        self.isatty && process.stdout.write('\u001b[2K');
      },

      beginningOfLine: function(){
        self.isatty && process.stdout.write('\u001b[0G');
      },

      CR: function(){
        if (self.isatty) {
          self.cursor.deleteLine();
          self.cursor.beginningOfLine();
        } else {
          process.stdout.write('\n');
        }
      }
    };

   };

   var Base = new BaseClass();

  function NyanCat(baseReporterDecorator, formatError, config) {

    var width = Base.window.width * 0.75 | 0;
    var self = this;

    self.stats;
    self.rainbowColors = self.generateColors();
    self.colorIndex = 0;
    self.numberOfLines = 4;
    self.browser_logs = {};
    self.trajectories = [[], [], [], []];
    self.nyanCatWidth = 11;
    self.trajectoryWidthMax = (width - self.nyanCatWidth);
    self.scoreboardWidth = 5;
    self.tick = 0;
    self.colors = {
        'gray': 90,
        'fail': 31,
        'bright_pass': 92,
        'bright_fail': 91,
        'bright_yellow': 93,
        'skip': 36,
        'suite': 0,
        'error title': 0,
        'error message': 31,
        'error stack': 90,
        'checkmark': 32,
        'fast': 90,
        'medium': 33,
        'slow': 31,
        'pass': 32,
        'light': 90,
        'diff gutter': 90,
        'diff added': 42,
        'diff removed': 41
    };

    self.onRunStart = function (browsers) {
      Base.cursor.hide();

      self._browsers = [];
      self.browser_logs = {};
      self.browserErrors = [];
      self.allResults = {};
      self.errors = [];
      self.totalTime = 0;
      self.numberOfSlowTests = 0;
      self.numberOfBrowsers = (browsers || []).length;

      write('\n');
    };

    self.onBrowserLog = function(browser, log, type) {
      if (! self.browser_logs[browser.id]) {
        self.browser_logs[browser.id] = {
          name: browser.name,
          log_messages: []
        };
      }

      self.browser_logs[browser.id].log_messages.push(log);
    };

    self.onBrowserStart = function (browser) {
      self._browsers.push(browser);
      self.numberOfBrowsers = self._browsers.length;
    };

    self.onSpecComplete = function(browser, result) {
      self.stats = browser.lastResult;

      if (!result.success && !result.skipped) {
          var searchArray = self.errors;

          result.suite.forEach(function(suiteName, i, arr) {
            var suite = findByName(searchArray, suiteName, Suite);

            // if we reached the last suite
            // set the test information
            if (i == arr.length - 1 ) {
              suite.tests = (!suite.tests) ? [] : suite.tests;
              var test = findByName(suite.tests, result.description, Test);
              var brwsr = findByName(test.browsers, browser.name, Browser);

              brwsr.errors = result.log[0].split('\n');

            // Otherwise, keep looping through sub-suites
            } else {
              suite.suites = (!suite.suites) ? [] : suite.suites;
              searchArray = suite.suites;
            }

          });
        // }

      }

      self.draw();
    };

    self.onRunComplete = function(browsers, results) {
      if (self.browserErrors.length) {
        var hashes = '##########'.split('');
        var rainbowify = function(val, i, arr) {
          write(self.rainbowify(val));
        };
        while (hashes.length > 0) {
          hashes.forEach(rainbowify);
          write('\n');
          hashes.pop();
        }
        self.browserErrors.forEach(function(val, i, arr) {
          write('\n');
          write(clc.red(val));
          write('\n');
        });
        while(hashes.length < 10) {
          hashes.forEach(rainbowify);
          write('\n');
          hashes.push('#');
        }
        write('\n');

      } else {
        write("\n");
        write("\n");
        write("\n");
        write("\n");
        write("\n");

        Base.cursor.show();

        if (self.errors.length) {
          write(clc.red('Failed Tests:\n'));
          printSuitesArray(self.errors, 'red');
        }

        if (self.stats) {
          printStats(self.stats);
        }

        printBrowserLogs();
      }
    };

    self.onBrowserError = function(browser, error) {
      self.browserErrors.push(error);
    };

    function Browser(name) {
      this.name = name;
      this.errors = [];
    }

    function Test(name) {
      this.name = name;
      this.browsers = [];
    }

    function Suite(name) {
      this.name = name;
    }

    function findByName(arr, name, Constructor) {
      var it;
      // Look through the array for an object with a
      // 'name' property that matches the 'name' arg
      arr.every(function(el, i, arr) {
        if (el.name === name) {
          it = el;
          return false;
        }
        return true;
      });

      // If a matching object is not found, create a
      // new one and push it to the provided array
      if (!it) {
        it = new Constructor(name);
        arr.push(it);
      }

      // return the object
      return it;
    }

    function printBrowserLogs() {
      var printMsg = function(msg) {
        write( "    ");
        write( clc.cyan(msg) );
        write("\n");
      };

      for (var browser in self.browser_logs) {
        write( "LOG MESSAGES FOR: " + self.browser_logs[browser].name + " INSTANCE #:" + browser + "\n" );
        self.browser_logs[browser].log_messages.forEach(printMsg);
      }
    }

    function printStats(stats) {
      var inc = 3;

      write( clc.right(inc) );
      write( clc.green(stats.success + ' passed') );

      write( clc.right(inc) );
      write( clc.red(stats.failed + ' failed') );

      write( clc.right(inc) );
      write( clc.cyan(stats.skipped + ' skipped') );

      write('\n');
      write('\n');
    }

    function printSuitesArray(errors, color) {
      var indentation = 0;
      var inc = 3; // increment amount
      var counter = 0;

      // printer for individual errors
      var printErrors = function(errors, indentation) {
        var first = true;
        indentation += inc;
        errors.forEach(function(error, i, arr) {
          write('\n');
          write( clc.right(indentation) );
          if (first) {
            write( clc[color + 'Bright'](++counter + ') ' + error) );
          } else {
            write( clc.blackBright(error.replace(/(\?.+:)/, ':')) );
          }
          first = false;
        });
      };

      // printer for suites
      var printSuites = function(arr, indentation) {
        indentation += inc;
        arr.forEach(function(el, i, arr) {
          write(clc.right(indentation));
          if ( el instanceof Suite) {
            var str = el.name;

            if ( arr === errors ) {
              write( clc.white.underline(str) );

            } else {
              write( clc.white(str) );
            }

          } else if ( el instanceof Test ) {
            write( clc[color](el.name) );

          } else if ( el instanceof Browser ) {
            write( clc.yellow(el.name) );
            printErrors(el.errors, indentation);

          }
          write('\n');
          if (el.browsers) {
            printSuites(el.browsers, indentation);
            write('\n');
          }
          if (el.tests) {
            printSuites(el.tests, indentation);
          }
          if (el.suites) {
            printSuites(el.suites, indentation);
          }
        });
      };

      printSuites(errors, indentation);

    } // end print fn

    this.color = function(type, str) {
      if (config.colors === false) return str;
      return '\u001b[' + self.colors[type] + 'm' + str + '\u001b[0m';
    };

  }

  /**
   * Draw the nyan cat
   *
   * @api private
   */

  NyanCat.prototype.draw = function(){
    this.appendRainbow();
    this.drawScoreboard();
    this.drawRainbow();
    this.drawNyanCat();
    this.tick = !this.tick;
  };

  /**
   * Draw the "scoreboard" showing the number
   * of passes, failures and pending tests.
   *
   * @api private
   */

  NyanCat.prototype.drawScoreboard = function(){
    var stats = this.stats;
    var colors = this.colors;

    function draw(color, n) {
      write(' ');
      write('\u001b[' + color + 'm' + n + '\u001b[0m');
      write('\n');
    }

    draw(colors.pass, stats.success);
    draw(colors.fail, stats.failed);
    draw(colors.skip, stats.skipped);
    write('\n');

    this.cursorUp(this.numberOfLines);
  };

  /**
   * Append the rainbow.
   *
   * @api private
   */

  NyanCat.prototype.appendRainbow = function(){
    var segment = this.tick ? '_' : '-';
    var rainbowified = this.rainbowify(segment);

    for (var index = 0; index < this.numberOfLines; index++) {
      var trajectory = this.trajectories[index];
      if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
      trajectory.push(rainbowified);
    }
  };

  /**
   * Draw the rainbow.
   *
   * @api private
   */

  NyanCat.prototype.drawRainbow = function(){
    var self = this;

    this.trajectories.forEach(function(line, index) {
      write('\u001b[' + self.scoreboardWidth + 'C');
      write(line.join(''));
      write('\n');
    });

    this.cursorUp(this.numberOfLines);
  };

  /**
   * Draw the nyan cat
   *
   * @api private
   */

  NyanCat.prototype.drawNyanCat = function() {
    var self = this;
    var startWidth = this.scoreboardWidth + this.trajectories[0].length;
    var color = '\u001b[' + startWidth + 'C';
    var padding = '';

    write(color);
    write('_,------,');
    write('\n');

    write(color);
    padding = self.tick ? '  ' : '   ';
    write('_|' + padding + '/\\_/\\ ');
    write('\n');

    write(color);
    padding = self.tick ? '_' : '__';
    var tail = self.tick ? '~' : '^';
    var face;
    write(tail + '|' + padding + this.face() + ' ');
    write('\n');

    write(color);
    padding = self.tick ? ' ' : '  ';
    write(padding + '""  "" ');
    write('\n');

    this.cursorUp(this.numberOfLines);
  };

  /**
   * Draw nyan cat face.
   *
   * @return {String}
   * @api private
   */

  NyanCat.prototype.face = function() {
    var stats = this.stats;
    if (stats.failed) {
      return '( x .x)';
    } else if (stats.skipped) {
      return '( o .o)';
    } else if(stats.success) {
      return '( ^ .^)';
    } else {
      return '( - .-)';
    }
  };

  /**
   * Move cursor up `n`.
   *
   * @param {Number} n
   * @api private
   */

  NyanCat.prototype.cursorUp = function(n) {
    write('\u001b[' + n + 'A');
  };

  /**
   * Move cursor down `n`.
   *
   * @param {Number} n
   * @api private
   */

  NyanCat.prototype.cursorDown = function(n) {
    write('\u001b[' + n + 'B');
  };

  /**
   * Generate rainbow colors.
   *
   * @return {Array}
   * @api private
   */

  NyanCat.prototype.generateColors = function() {
    var colors = [];

    for (var i = 0; i < (6 * 7); i++) {
      var pi3 = Math.floor(Math.PI / 3);
      var n = (i * (1.0 / 6));
      var r = Math.floor(3 * Math.sin(n) + 3);
      var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
      var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
      colors.push(36 * r + 6 * g + b + 16);
    }

    return colors;
  };

  /**
   * Apply rainbow to the given `str`.
   *
   * @param {String} str
   * @return {String}
   * @api private
   */

  NyanCat.prototype.rainbowify = function(str) {
    var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
    this.colorIndex += 1;
    return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
  };

  /**
   * Stdout helper.
   */

  function write(string) {
    process.stdout.write(string);
  }

  NyanCat.$inject = ['baseReporterDecorator', 'formatError', 'config'];

  module.exports = {
    'reporter:nyan': ['type', NyanCat]
  };
})();
<commit_msg>fixes Cannot call method 'split' of null error<commit_after>/*jshint -W030 */
(function() {
  'use strict';
  var tty = require('tty');
  var clc = require('cli-color');

  // Emulate the Mocha base class a little bit
  // just to get things going

   var BaseClass = function() {
    var self = this;

    this.isatty = tty.isatty(1) && tty.isatty(2);

    this.window = {
      width : self.isatty ? (
                        process.stdout.getWindowSize ?
                        process.stdout.getWindowSize(1)[0] :
                        tty.getWindowSize()[1]
                      ) : 75
    };

    this.cursor = {
      hide: function(){
        self.isatty && process.stdout.write('\u001b[?25l');
      },

      show: function(){
        self.isatty && process.stdout.write('\u001b[?25h');
      },

      deleteLine: function(){
        self.isatty && process.stdout.write('\u001b[2K');
      },

      beginningOfLine: function(){
        self.isatty && process.stdout.write('\u001b[0G');
      },

      CR: function(){
        if (self.isatty) {
          self.cursor.deleteLine();
          self.cursor.beginningOfLine();
        } else {
          process.stdout.write('\n');
        }
      }
    };

   };

   var Base = new BaseClass();

  function NyanCat(baseReporterDecorator, formatError, config) {

    var width = Base.window.width * 0.75 | 0;
    var self = this;

    self.stats;
    self.rainbowColors = self.generateColors();
    self.colorIndex = 0;
    self.numberOfLines = 4;
    self.browser_logs = {};
    self.trajectories = [[], [], [], []];
    self.nyanCatWidth = 11;
    self.trajectoryWidthMax = (width - self.nyanCatWidth);
    self.scoreboardWidth = 5;
    self.tick = 0;
    self.colors = {
        'gray': 90,
        'fail': 31,
        'bright_pass': 92,
        'bright_fail': 91,
        'bright_yellow': 93,
        'skip': 36,
        'suite': 0,
        'error title': 0,
        'error message': 31,
        'error stack': 90,
        'checkmark': 32,
        'fast': 90,
        'medium': 33,
        'slow': 31,
        'pass': 32,
        'light': 90,
        'diff gutter': 90,
        'diff added': 42,
        'diff removed': 41
    };

    self.onRunStart = function (browsers) {
      Base.cursor.hide();

      self._browsers = [];
      self.browser_logs = {};
      self.browserErrors = [];
      self.allResults = {};
      self.errors = [];
      self.totalTime = 0;
      self.numberOfSlowTests = 0;
      self.numberOfBrowsers = (browsers || []).length;

      write('\n');
    };

    self.onBrowserLog = function(browser, log, type) {
      if (! self.browser_logs[browser.id]) {
        self.browser_logs[browser.id] = {
          name: browser.name,
          log_messages: []
        };
      }

      self.browser_logs[browser.id].log_messages.push(log);
    };

    self.onBrowserStart = function (browser) {
      self._browsers.push(browser);
      self.numberOfBrowsers = self._browsers.length;
    };

    self.onSpecComplete = function(browser, result) {
      self.stats = browser.lastResult;

      if (!result.success && !result.skipped) {
          var searchArray = self.errors;

          result.suite.forEach(function(suiteName, i, arr) {
            var suite = findByName(searchArray, suiteName, Suite);

            // if we reached the last suite
            // set the test information
            if (i == arr.length - 1 ) {
              suite.tests = (!suite.tests) ? [] : suite.tests;
              var test = findByName(suite.tests, result.description, Test);
              var brwsr = findByName(test.browsers, browser.name, Browser);

              if(result.log[0] !== null){
                brwsr.errors = result.log[0].split('\n');
              }

            // Otherwise, keep looping through sub-suites
            } else {
              suite.suites = (!suite.suites) ? [] : suite.suites;
              searchArray = suite.suites;
            }

          });
        // }

      }

      self.draw();
    };

    self.onRunComplete = function(browsers, results) {
      if (self.browserErrors.length) {
        var hashes = '##########'.split('');
        var rainbowify = function(val, i, arr) {
          write(self.rainbowify(val));
        };
        while (hashes.length > 0) {
          hashes.forEach(rainbowify);
          write('\n');
          hashes.pop();
        }
        self.browserErrors.forEach(function(val, i, arr) {
          write('\n');
          write(clc.red(val));
          write('\n');
        });
        while(hashes.length < 10) {
          hashes.forEach(rainbowify);
          write('\n');
          hashes.push('#');
        }
        write('\n');

      } else {
        write("\n");
        write("\n");
        write("\n");
        write("\n");
        write("\n");

        Base.cursor.show();

        if (self.errors.length) {
          write(clc.red('Failed Tests:\n'));
          printSuitesArray(self.errors, 'red');
        }

        if (self.stats) {
          printStats(self.stats);
        }

        printBrowserLogs();
      }
    };

    self.onBrowserError = function(browser, error) {
      self.browserErrors.push(error);
    };

    function Browser(name) {
      this.name = name;
      this.errors = [];
    }

    function Test(name) {
      this.name = name;
      this.browsers = [];
    }

    function Suite(name) {
      this.name = name;
    }

    function findByName(arr, name, Constructor) {
      var it;
      // Look through the array for an object with a
      // 'name' property that matches the 'name' arg
      arr.every(function(el, i, arr) {
        if (el.name === name) {
          it = el;
          return false;
        }
        return true;
      });

      // If a matching object is not found, create a
      // new one and push it to the provided array
      if (!it) {
        it = new Constructor(name);
        arr.push(it);
      }

      // return the object
      return it;
    }

    function printBrowserLogs() {
      var printMsg = function(msg) {
        write( "    ");
        write( clc.cyan(msg) );
        write("\n");
      };

      for (var browser in self.browser_logs) {
        write( "LOG MESSAGES FOR: " + self.browser_logs[browser].name + " INSTANCE #:" + browser + "\n" );
        self.browser_logs[browser].log_messages.forEach(printMsg);
      }
    }

    function printStats(stats) {
      var inc = 3;

      write( clc.right(inc) );
      write( clc.green(stats.success + ' passed') );

      write( clc.right(inc) );
      write( clc.red(stats.failed + ' failed') );

      write( clc.right(inc) );
      write( clc.cyan(stats.skipped + ' skipped') );

      write('\n');
      write('\n');
    }

    function printSuitesArray(errors, color) {
      var indentation = 0;
      var inc = 3; // increment amount
      var counter = 0;

      // printer for individual errors
      var printErrors = function(errors, indentation) {
        var first = true;
        indentation += inc;
        errors.forEach(function(error, i, arr) {
          write('\n');
          write( clc.right(indentation) );
          if (first) {
            write( clc[color + 'Bright'](++counter + ') ' + error) );
          } else {
            write( clc.blackBright(error.replace(/(\?.+:)/, ':')) );
          }
          first = false;
        });
      };

      // printer for suites
      var printSuites = function(arr, indentation) {
        indentation += inc;
        arr.forEach(function(el, i, arr) {
          write(clc.right(indentation));
          if ( el instanceof Suite) {
            var str = el.name;

            if ( arr === errors ) {
              write( clc.white.underline(str) );

            } else {
              write( clc.white(str) );
            }

          } else if ( el instanceof Test ) {
            write( clc[color](el.name) );

          } else if ( el instanceof Browser ) {
            write( clc.yellow(el.name) );
            printErrors(el.errors, indentation);

          }
          write('\n');
          if (el.browsers) {
            printSuites(el.browsers, indentation);
            write('\n');
          }
          if (el.tests) {
            printSuites(el.tests, indentation);
          }
          if (el.suites) {
            printSuites(el.suites, indentation);
          }
        });
      };

      printSuites(errors, indentation);

    } // end print fn

    this.color = function(type, str) {
      if (config.colors === false) return str;
      return '\u001b[' + self.colors[type] + 'm' + str + '\u001b[0m';
    };

  }

  /**
   * Draw the nyan cat
   *
   * @api private
   */

  NyanCat.prototype.draw = function(){
    this.appendRainbow();
    this.drawScoreboard();
    this.drawRainbow();
    this.drawNyanCat();
    this.tick = !this.tick;
  };

  /**
   * Draw the "scoreboard" showing the number
   * of passes, failures and pending tests.
   *
   * @api private
   */

  NyanCat.prototype.drawScoreboard = function(){
    var stats = this.stats;
    var colors = this.colors;

    function draw(color, n) {
      write(' ');
      write('\u001b[' + color + 'm' + n + '\u001b[0m');
      write('\n');
    }

    draw(colors.pass, stats.success);
    draw(colors.fail, stats.failed);
    draw(colors.skip, stats.skipped);
    write('\n');

    this.cursorUp(this.numberOfLines);
  };

  /**
   * Append the rainbow.
   *
   * @api private
   */

  NyanCat.prototype.appendRainbow = function(){
    var segment = this.tick ? '_' : '-';
    var rainbowified = this.rainbowify(segment);

    for (var index = 0; index < this.numberOfLines; index++) {
      var trajectory = this.trajectories[index];
      if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
      trajectory.push(rainbowified);
    }
  };

  /**
   * Draw the rainbow.
   *
   * @api private
   */

  NyanCat.prototype.drawRainbow = function(){
    var self = this;

    this.trajectories.forEach(function(line, index) {
      write('\u001b[' + self.scoreboardWidth + 'C');
      write(line.join(''));
      write('\n');
    });

    this.cursorUp(this.numberOfLines);
  };

  /**
   * Draw the nyan cat
   *
   * @api private
   */

  NyanCat.prototype.drawNyanCat = function() {
    var self = this;
    var startWidth = this.scoreboardWidth + this.trajectories[0].length;
    var color = '\u001b[' + startWidth + 'C';
    var padding = '';

    write(color);
    write('_,------,');
    write('\n');

    write(color);
    padding = self.tick ? '  ' : '   ';
    write('_|' + padding + '/\\_/\\ ');
    write('\n');

    write(color);
    padding = self.tick ? '_' : '__';
    var tail = self.tick ? '~' : '^';
    var face;
    write(tail + '|' + padding + this.face() + ' ');
    write('\n');

    write(color);
    padding = self.tick ? ' ' : '  ';
    write(padding + '""  "" ');
    write('\n');

    this.cursorUp(this.numberOfLines);
  };

  /**
   * Draw nyan cat face.
   *
   * @return {String}
   * @api private
   */

  NyanCat.prototype.face = function() {
    var stats = this.stats;
    if (stats.failed) {
      return '( x .x)';
    } else if (stats.skipped) {
      return '( o .o)';
    } else if(stats.success) {
      return '( ^ .^)';
    } else {
      return '( - .-)';
    }
  };

  /**
   * Move cursor up `n`.
   *
   * @param {Number} n
   * @api private
   */

  NyanCat.prototype.cursorUp = function(n) {
    write('\u001b[' + n + 'A');
  };

  /**
   * Move cursor down `n`.
   *
   * @param {Number} n
   * @api private
   */

  NyanCat.prototype.cursorDown = function(n) {
    write('\u001b[' + n + 'B');
  };

  /**
   * Generate rainbow colors.
   *
   * @return {Array}
   * @api private
   */

  NyanCat.prototype.generateColors = function() {
    var colors = [];

    for (var i = 0; i < (6 * 7); i++) {
      var pi3 = Math.floor(Math.PI / 3);
      var n = (i * (1.0 / 6));
      var r = Math.floor(3 * Math.sin(n) + 3);
      var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
      var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
      colors.push(36 * r + 6 * g + b + 16);
    }

    return colors;
  };

  /**
   * Apply rainbow to the given `str`.
   *
   * @param {String} str
   * @return {String}
   * @api private
   */

  NyanCat.prototype.rainbowify = function(str) {
    var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
    this.colorIndex += 1;
    return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
  };

  /**
   * Stdout helper.
   */

  function write(string) {
    process.stdout.write(string);
  }

  NyanCat.$inject = ['baseReporterDecorator', 'formatError', 'config'];

  module.exports = {
    'reporter:nyan': ['type', NyanCat]
  };
})();
<|endoftext|>


<commit_before>/**
 * Module dependences
 */

var debug = require('debug')('barracks');
var assert = require('assert');
var async = require('async');
var toString = Object.prototype.toString;

/**
 * Exports
 */

module.exports = Dispatcher;

/**
 * Dispatcher prototype
 */

var dispatcher = Dispatcher.prototype;

/**
 * Initialize the dispatcher with an
 * 'actions' object.
 *
 * @return {Object}
 * @api public
 */

function Dispatcher(actions) {

  if (!(this instanceof Dispatcher)) return new Dispatcher(actions);

  assert(actions, 'An \'actions\' object should be passed as an argument');
  assert('object' == typeof actions, 'Actions should be an object');
  _assertActionsObject(actions);

  this._isPending = {};
  this._isHandled = {};
  this._actions = actions;
  this._isDispatching = false;

  return this.dispatch.bind(this);
};

/**
 * Dispatch event to stores.
 *
 * @param {String} action
 * @param {Object | Object[]} data
 * @return {Function[]}
 * @api public
 */

dispatcher.dispatch = function(action, payload) {

  assert('string' == typeof action, 'Action should be a string');
  assert(!this._isDispatching, 'Cannot dispatch in the middle of a dispatch');

  this._isPending[action] = true;
  this._isDispatching = true;
  this._isHandled = {};
  this._isPending = {};
  this.locals = {};
  this.locals.payload = payload;

  try {
    var fn = _getAction.call(this, action);
  } catch (e) {
    _stopDispatching.call(this);
    throw e;
  }

  debug('Dispatched action \'%s\'.', action);
  fn.call(this, this.locals.payload, _stopDispatching.bind(this));
};

/**
 * Expose a delegation method to the registered actions. Calls `async.series()`
 * under the hood. Sets a 'pending' state to
 *
 * @param {String[] |} ids
 * @param {Function} done
 * @api public
 */

dispatcher.waitFor = function(actions, done) {
  assert(!done || 'function' == typeof done, 'Callback should be a function');

  if ('[object Array]' != toString.call(actions)) actions = [actions];

  var arr = actions.map(function(action) {
    assert('string' == typeof action, '.waitFor(): requires a string or array of strings');
    try {
      assert(!this._isPending[action], 'Circular dependency detected while waiting for \'' + action + '\'');
    } catch(e) {
      _stopDispatching.call(this);
      throw e;
    }

    this._isPending[action] = true;
    this._isHandled[action] = false;

    var nwAction = _getAction.call(this, action);
    return nwAction.bind(this, this.locals.payload);
  }.bind(this));

  debug('Waiting for actions ' + actions.map(function(action, i) {
    if (i == actions.length - 1) return action;
    return action + ', ';
  }));
  var nwArr = arr.concat(done.bind(this));

  // Call all functions in series and set their handled
  // state to `true` when finished.

  async.series(nwArr, cb);

  function cb() {
    actions.forEach(function(action) {
      this._isHandled[action] = true;
    }.bind(this));
  }
};

/**
 * Deep assert if the passed actions object is correct.
 *
 * @param {Object} actions
 * @api private
 */

function _assertActionsObject(actions) {
  Object.keys(actions).forEach(function(key) {
    var action = actions[key];
    if ('object' == typeof action) return _assertActionsObject(action);
    assert('function' == typeof action, 'Action should be a function');
  });
}

/**
 * Get the dispatched action. Traverses the call stack
 * recursively until a function is found.
 *
 * @param {String[]} arr
 * @param {String} action
 * @return {Function}
 * @api private
 */

function _getAction(action, arr, index) {
  arr = arr || action.split('_');
  index == index || 0;
  var val = arr[index];

  if ('object' == typeof val) return _getAction.call(this, action, arr, index++);

  var fn = this._actions;
  arr.forEach(function(obj, i) {
    assert(fn[arr[i]], 'Action \'' + action + '\' is not registered');
    fn = fn[arr[i]];
  }.bind(this));

  assert('function' == typeof fn, 'Action \'' + action + '\' is not registered');
  this._isPending[action] = true;
  return fn;
}

/**
 * Clear bookkeeping.
 *
 * @api private
 */

function _stopDispatching() {
  this._isDispatching = false;
  this._isPending = {};
  this._isHandled = {};
  this.locals = null;
}
<commit_msg>waitFor: fix cb bug<commit_after>/**
 * Module dependences
 */

var debug = require('debug')('barracks');
var assert = require('assert');
var async = require('async');
var toString = Object.prototype.toString;

/**
 * Exports
 */

module.exports = Dispatcher;

/**
 * Dispatcher prototype
 */

var dispatcher = Dispatcher.prototype;

/**
 * Initialize the dispatcher with an
 * 'actions' object.
 *
 * @return {Object}
 * @api public
 */

function Dispatcher(actions) {

  if (!(this instanceof Dispatcher)) return new Dispatcher(actions);

  assert(actions, 'An \'actions\' object should be passed as an argument');
  assert('object' == typeof actions, 'Actions should be an object');
  _assertActionsObject(actions);

  this._isPending = {};
  this._isHandled = {};
  this._actions = actions;
  this._isDispatching = false;

  return this.dispatch.bind(this);
};

/**
 * Dispatch event to stores.
 *
 * @param {String} action
 * @param {Object | Object[]} data
 * @return {Function[]}
 * @api public
 */

dispatcher.dispatch = function(action, payload) {

  assert('string' == typeof action, 'Action should be a string');
  assert(!this._isDispatching, 'Cannot dispatch in the middle of a dispatch');

  this._isPending[action] = true;
  this._isDispatching = true;
  this._isHandled = {};
  this._isPending = {};
  this.locals = {};
  this.locals.payload = payload;

  try {
    var fn = _getAction.call(this, action);
  } catch (e) {
    _stopDispatching.call(this);
    throw e;
  }

  debug('Dispatched action \'%s\'.', action);
  fn.call(this, this.locals.payload, _stopDispatching.bind(this));
};

/**
 * Expose a delegation method to the registered actions. Calls `async.series()`
 * under the hood. Sets a 'pending' state to
 *
 * @param {String[] |} ids
 * @param {Function} done
 * @api public
 */

dispatcher.waitFor = function(actions, done) {
  assert(!done || 'function' == typeof done, 'Callback should be a function');

  if ('[object Array]' != toString.call(actions)) actions = [actions];

  var arr = actions.map(function(action) {
    assert('string' == typeof action, '.waitFor(): requires a string or array of strings');
    try {
      assert(!this._isPending[action], 'Circular dependency detected while waiting for \'' + action + '\'');
    } catch(e) {
      _stopDispatching.call(this);
      throw e;
    }

    this._isPending[action] = true;
    this._isHandled[action] = false;

    var nwAction = _getAction.call(this, action);
    return nwAction.bind(this, this.locals.payload);
  }.bind(this));

  debug('Waiting for actions ' + actions.map(function(action, i) {
    if (i == actions.length - 1) return action;
    return action + ', ';
  }));
  var nwArr = arr.concat(done.bind(this));

  // Call all functions in series and set their handled
  // state to `true` when finished.

  async.series(nwArr, cb.bind(this));

  function cb() {
    actions.forEach(function(action) {
      this._isHandled[action] = true;
    }.bind(this));
  }
};

/**
 * Deep assert if the passed actions object is correct.
 *
 * @param {Object} actions
 * @api private
 */

function _assertActionsObject(actions) {
  Object.keys(actions).forEach(function(key) {
    var action = actions[key];
    if ('object' == typeof action) return _assertActionsObject(action);
    assert('function' == typeof action, 'Action should be a function');
  });
}

/**
 * Get the dispatched action. Traverses the call stack
 * recursively until a function is found.
 *
 * @param {String[]} arr
 * @param {String} action
 * @return {Function}
 * @api private
 */

function _getAction(action, arr, index) {
  arr = arr || action.split('_');
  index == index || 0;
  var val = arr[index];

  if ('object' == typeof val) return _getAction.call(this, action, arr, index++);

  var fn = this._actions;
  arr.forEach(function(obj, i) {
    assert(fn[arr[i]], 'Action \'' + action + '\' is not registered');
    fn = fn[arr[i]];
  }.bind(this));

  assert('function' == typeof fn, 'Action \'' + action + '\' is not registered');
  this._isPending[action] = true;
  return fn;
}

/**
 * Clear bookkeeping.
 *
 * @api private
 */

function _stopDispatching() {
  this._isDispatching = false;
  this._isPending = {};
  this._isHandled = {};
  this.locals = null;
}
<|endoftext|>


<commit_before>var Transform = require('stream').Transform;
var Readable = require('stream').Readable;
var inherits = require('inherits');
var path = require('path');
var JSONStream = require('JSONStream');
var combine = require('stream-combiner');
var nub = require('nub');
var depsTopoSort = require('deps-topo-sort');
var reverse = require('reversepoint');

module.exports = function (files, opts) {
    if (!opts) opts = {};

    var fr = new Factor(files, opts),
        parse, dup;

    if (opts.objectMode) {
      dup = combine(depsTopoSort(), reverse(), fr);
    } else {
      parse = JSONStream.parse([true]);
      dup = opts.raw
        ? combine(parse, depsTopoSort(), reverse(), fr)
        : combine(parse, depsTopoSort(), reverse(), fr, JSONStream.stringify());

      parse.on('error', function (err) { dup.emit('error', err) });
    }

    fr.on('error', function (err) { dup.emit('error', err) });
    fr.on('stream', function (s) {
        if (opts.raw) dup.emit('stream', s)
        else dup.emit('stream', s.pipe(JSONStream.stringify()))
    });
    return dup;
};
inherits(Factor, Transform);

function Factor (files, opts) {
    var self = this;
    if (!(this instanceof Factor)) return new Factor(files, opts);
    Transform.call(this, { objectMode: true });

    if (!opts) opts = {};
    this.basedir = opts.basedir || process.cwd();

    this._streams = {};
    this._groups = {};
    this._buffered = {};

    this._files = files.reduce(function (acc, file) {
        acc[path.resolve(self.basedir, file)] = true;
        return acc;
    }, {});

    this._thresholdVal = typeof opts.threshold === "number"
        ? opts.threshold : 1
    ;
    this._defaultThreshold = function(row, group) {
        return group.length > this._thresholdVal;
    };
    this._threshold = typeof opts.threshold === "function"
        ? opts.threshold
        : this._defaultThreshold
    ;
}

Factor.prototype._transform = function (row, enc, next) {
    var self = this;
    if (this._files[row.id]) {
        var s = this._streams[row.id];
        if (!s) s = this._makeStream(row);
        s.push(row);

        addGroups(row.id);
    } else {
        this._buffered[row.id] = row;
        if (this._groups[row.id]) {
            this._groups[row.id].forEach(addGroups);
        }
    }

    next();

    function addGroups (gid) {
        Object.keys(row.deps || {}).forEach(function (key) {
            var file = row.deps[key];
            var g = self._groups[file];
            if (!g) g = self._groups[file] = [];
            g.push(gid);
        });
    }
};

Factor.prototype._flush = function () {
    var self = this;

    var ensureCommon = {};
    Object.keys(self._buffered).forEach(function (file) {
        var row = self._buffered[file];

        var groups = nub(self._groups[file] || []);
        if (groups.length === 0) ensureCommon[file] = true;
        if (ensureCommon[file] || self._threshold(row, groups)) {
            Object.keys(row.deps).forEach(function(k) {
                ensureCommon[row.deps[k]] = true;
            });
            self.push(row);
        }
        else {
            groups.forEach(function (id) {
                self._streams[id].push(row);
            });
        }
    });

    Object.keys(self._streams).forEach(function (key) {
        self._streams[key].push(null);
    });
    self.push(null);
};

Factor.prototype._makeStream = function (row) {
    var s = new Readable({ objectMode: true });
    s.file = row.id;
    s._read = function () {};
    this._streams[row.id] = s;
    this.emit('stream', s);
    return s;
};
<commit_msg>re-normalize formatting<commit_after>var Transform = require('stream').Transform;
var Readable = require('stream').Readable;
var inherits = require('inherits');
var path = require('path');
var JSONStream = require('JSONStream');
var combine = require('stream-combiner');
var nub = require('nub');
var depsTopoSort = require('deps-topo-sort');
var reverse = require('reversepoint');

module.exports = function (files, opts) {
    if (!opts) opts = {};

    var fr = new Factor(files, opts);
    var parse, dup;

    if (opts.objectMode) {
        dup = combine(depsTopoSort(), reverse(), fr);
    }
    else {
        parse = JSONStream.parse([true]);
        dup = opts.raw
            ? combine(parse, depsTopoSort(), reverse(), fr)
            : combine(
                parse, depsTopoSort(), reverse(), fr, JSONStream.stringify()
            )
        ;
        parse.on('error', function (err) { dup.emit('error', err) });
    }

    fr.on('error', function (err) { dup.emit('error', err) });
    fr.on('stream', function (s) {
        if (opts.raw) dup.emit('stream', s)
        else dup.emit('stream', s.pipe(JSONStream.stringify()))
    });
    return dup;
};
inherits(Factor, Transform);

function Factor (files, opts) {
    var self = this;
    if (!(this instanceof Factor)) return new Factor(files, opts);
    Transform.call(this, { objectMode: true });

    if (!opts) opts = {};
    this.basedir = opts.basedir || process.cwd();

    this._streams = {};
    this._groups = {};
    this._buffered = {};

    this._files = files.reduce(function (acc, file) {
        acc[path.resolve(self.basedir, file)] = true;
        return acc;
    }, {});

    this._thresholdVal = typeof opts.threshold === "number"
        ? opts.threshold : 1
    ;
    this._defaultThreshold = function(row, group) {
        return group.length > this._thresholdVal;
    };
    this._threshold = typeof opts.threshold === "function"
        ? opts.threshold
        : this._defaultThreshold
    ;
}

Factor.prototype._transform = function (row, enc, next) {
    var self = this;
    if (this._files[row.id]) {
        var s = this._streams[row.id];
        if (!s) s = this._makeStream(row);
        s.push(row);

        addGroups(row.id);
    }
    else {
        this._buffered[row.id] = row;
        if (this._groups[row.id]) {
            this._groups[row.id].forEach(addGroups);
        }
    }

    next();

    function addGroups (gid) {
        Object.keys(row.deps || {}).forEach(function (key) {
            var file = row.deps[key];
            var g = self._groups[file];
            if (!g) g = self._groups[file] = [];
            g.push(gid);
        });
    }
};

Factor.prototype._flush = function () {
    var self = this;

    var ensureCommon = {};
    Object.keys(self._buffered).forEach(function (file) {
        var row = self._buffered[file];

        var groups = nub(self._groups[file] || []);
        if (groups.length === 0) ensureCommon[file] = true;
        if (ensureCommon[file] || self._threshold(row, groups)) {
            Object.keys(row.deps).forEach(function(k) {
                ensureCommon[row.deps[k]] = true;
            });
            self.push(row);
        }
        else {
            groups.forEach(function (id) {
                self._streams[id].push(row);
            });
        }
    });

    Object.keys(self._streams).forEach(function (key) {
        self._streams[key].push(null);
    });
    self.push(null);
};

Factor.prototype._makeStream = function (row) {
    var s = new Readable({ objectMode: true });
    s.file = row.id;
    s._read = function () {};
    this._streams[row.id] = s;
    this.emit('stream', s);
    return s;
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.get('/', function(request, response) {
  response.send('Hello World!');
});

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'));
});
<commit_msg>dave - spike<commit_after>var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.get('/', function(request, response) {
  response.send('Hello World! I am memebot. Please insert girder.');
});

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'));
});
<|endoftext|>