<commit_before>var inspector = require('..');
var expect = require('expect.js');

describe("url-inspector", function suite() {
	it("should inspect large file without downloading it entirely", function(done) {
		this.timeout(3000);
		inspector('https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.3.3.tar.xz', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.title).to.be.ok();
			expect(meta.type).to.be('archive');
			expect(meta.ext).to.be('xz');
			done();
		});
	});
	it("should return meta with width and height", function(done) {
		this.timeout(5000);
		inspector('https://upload.wikimedia.org/wikipedia/commons/b/bd/1110_desktop_visual.jpg', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('image');
			expect(meta.ext).to.be('jpg');
			expect(meta.title).to.be.ok();
			expect(meta.width).to.be.ok();
			expect(meta.height).to.be.ok();
			done();
		});
	});
	it("should return meta with thumbnail for a youtube video", function(done) {
		this.timeout(5000);
		inspector('https://www.youtube.com/watch?v=CtP8VABF5pk', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('video');
			expect(meta.thumbnail).to.be.ok();
			expect(meta.title).to.be.ok();
			expect(meta.embed).to.be.ok();
			expect(meta.ext).to.be('html');
			expect(meta.width).to.be.ok();
			expect(meta.height).to.be.ok();
			expect(meta.duration).to.be.ok();
			done();
		});
	});
	it("should just work with github.com", function(done) {
		this.timeout(5000);
		inspector('https://github.com/kapouer/url-inspector', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('link');
			expect(meta.title).to.be.ok();
			expect(meta.size).to.not.be.ok();
			done();
		});
	});
	it("should error out with a message", function(done) {
		this.timeout(5000);
		inspector('https://ubnhiryuklu.tar/ctalo', function(err, meta) {
			expect(err).to.be.ok();
			expect(meta).to.not.be.ok();
			done();
		});
	});
	it("should error out with a 404", function(done) {
		this.timeout(5000);
		inspector('https://google.com/ctalo', function(err, meta) {
			expect(err).to.be(404);
			expect(meta).to.not.be.ok();
			done();
		});
	});
	it("should redirect properly", function(done) {
		this.timeout(5000);
		inspector('https://github.com/Stuk/jszip/archive/master.zip', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('archive');
			expect(meta.title).to.be.ok();
			done();
		});
	});

});
<commit_msg>A failing oembed test<commit_after>var inspector = require('..');
var expect = require('expect.js');

describe("url-inspector", function suite() {
	it("should inspect large file without downloading it entirely", function(done) {
		this.timeout(3000);
		inspector('https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.3.3.tar.xz', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.title).to.be.ok();
			expect(meta.type).to.be('archive');
			expect(meta.ext).to.be('xz');
			done();
		});
	});
	it("should return meta with width and height", function(done) {
		this.timeout(5000);
		inspector('https://upload.wikimedia.org/wikipedia/commons/b/bd/1110_desktop_visual.jpg', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('image');
			expect(meta.ext).to.be('jpg');
			expect(meta.title).to.be.ok();
			expect(meta.width).to.be.ok();
			expect(meta.height).to.be.ok();
			done();
		});
	});
	it("should return meta with thumbnail for a youtube video", function(done) {
		this.timeout(5000);
		inspector('https://www.youtube.com/watch?v=CtP8VABF5pk', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('video');
			expect(meta.thumbnail).to.be.ok();
			expect(meta.title).to.be.ok();
			expect(meta.embed).to.be.ok();
			expect(meta.ext).to.be('html');
			expect(meta.width).to.be.ok();
			expect(meta.height).to.be.ok();
			expect(meta.duration).to.be.ok();
			done();
		});
	});
	it("should just work with github.com", function(done) {
		this.timeout(5000);
		inspector('https://github.com/kapouer/url-inspector', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('link');
			expect(meta.title).to.be.ok();
			expect(meta.size).to.not.be.ok();
			done();
		});
	});
	it("should error out with a message", function(done) {
		this.timeout(5000);
		inspector('https://ubnhiryuklu.tar/ctalo', function(err, meta) {
			expect(err).to.be.ok();
			expect(meta).to.not.be.ok();
			done();
		});
	});
	it("should error out with a 404", function(done) {
		this.timeout(5000);
		inspector('https://google.com/ctalo', function(err, meta) {
			expect(err).to.be(404);
			expect(meta).to.not.be.ok();
			done();
		});
	});
	it("should redirect properly", function(done) {
		this.timeout(5000);
		inspector('https://github.com/Stuk/jszip/archive/master.zip', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('archive');
			expect(meta.title).to.be.ok();
			done();
		});
	});
	it("should inspect even when oembed endpoint fails", function(done) {
		this.timeout(5000);
		inspector('https://vimeo.com/75809732', function(err, meta) {
			expect(err).to.not.be.ok();
			expect(meta.type).to.be('link');
			expect(meta.thumbnail).to.be.ok();
			done();
		});
	});

});
<|endoftext|>


<commit_before>'use strict'

var test = require('tape')
var abstract = require('abstract-leveldown')

function isAbstract (db) {
  if (!db || typeof db !== 'object') { return false }
  return Object.keys(abstract.AbstractLevelDOWN.prototype).filter(function (name) {
    return name[0] !== '_'
  }).every(function (name) {
    return typeof db[name] === 'function'
  })
}

function down (db, type) {
  if (typeof db.down === 'function') return db.down(type)
  if (type && db.type === type) return db
  if (isAbstract(db.db)) return down(db.db, type)
  if (isAbstract(db._db)) return down(db._db, type)
  return type ? null : db
}

exports.args = function (level, expectedDown) {
  test('without arguments', function (t) {
    t.plan(3)

    var db = level()

    db.on('open', function () {
      t.ok(down(db) instanceof expectedDown, 'got expected down')
    })

    db.put('foo', 'bar', function (err) {
      t.ifError(err)
      t.notOk(err)
    })
  })

  test('with options and callback', function (t) {
    t.plan(6)

    level({ valueEncoding: 'json' }, function (err, db) {
      t.ifError(err)
      t.ok(db.isOpen())
      t.ok(down(db) instanceof expectedDown, 'got expected down')

      var key = '' + Math.random()
      var value = { test_key: '' + new Date() }

      db.put(key, value, function (err) {
        t.notOk(err)

        db.get(key, function (err, _value) {
          t.ifError(err)
          t.deepEqual(_value, value)
        })
      })
    })
  })

  test('with options', function (t) {
    t.plan(4)

    var db = level({ valueEncoding: 'json' })
    var key = '' + Math.random()
    var value = { test_key: '' + new Date() }

    db.on('open', function () {
      t.ok(down(db) instanceof expectedDown, 'got expected down')
    })

    db.put(key, value, function (err) {
      t.notOk(err)

      db.get(key, function (err, _value) {
        t.ifError(err)
        t.deepEqual(_value, value)
      })
    })
  })

  test('with callback', function (t) {
    t.plan(6)

    level(function (err, db) {
      t.ifError(err)
      t.ok(db.isOpen())
      t.ok(down(db) instanceof expectedDown, 'got expected down')

      db.put('key', 'value', function (err) {
        t.notOk(err)

        db.get('key', function (err, value) {
          t.ifError(err)
          t.is(value, 'value')
        })
      })
    })
  })
}

exports.customLayers = function (level, expectedDown, expectedUp, rawValue) {
  test('custom layers with auto-open', function (t) {
    t.plan(9)

    var ret = level(function (err, db) {
      t.ifError(err)
      t.is(db, ret, 'got db')
      t.ok(down(db) instanceof expectedDown, 'got expected down')
      t.ok(db instanceof expectedUp, 'got expected up')

      db.put('key', 'value', function (err) {
        t.notOk(err)

        db.get('key', { asBuffer: false }, function (err, value) {
          t.ifError(err)
          t.is(value, 'value')
        })

        db.get('key', { valueEncoding: 'id', asBuffer: false }, function (err, value) {
          t.ifError(err)
          t.is(value, rawValue)
        })
      })
    })
  })
}

exports.options = function (levelTest) {
  test('opts precedence', function (t) {
    t.plan(6)

    var level = levelTest({ valueEncoding: 'utf8' })
    var db1 = level()
    var db2 = level({ valueEncoding: 'json' })
    var value = { test: true }

    db1.put('key', value, function (err) {
      t.ifError(err)

      db1.get('key', function (err, value1) {
        t.ifError(err)
        t.is(value1, '[object Object]')
      })
    })

    db2.put('key', value, function (err) {
      t.ifError(err)

      db2.get('key', function (err, value2) {
        t.ifError(err)
        t.deepEqual(value2, value)
      })
    })
  })
}
<commit_msg>Relax isAbstract check in tests (closes #125)<commit_after>'use strict'

var test = require('tape')

function isLooseAbstract (db) {
  if (!db || typeof db !== 'object') { return false }
  return typeof db._batch === 'function' && typeof db._iterator === 'function'
}

function down (db, type) {
  if (typeof db.down === 'function') return db.down(type)
  if (type && db.type === type) return db
  if (isLooseAbstract(db.db)) return down(db.db, type)
  if (isLooseAbstract(db._db)) return down(db._db, type)
  return type ? null : db
}

exports.args = function (level, expectedDown) {
  test('without arguments', function (t) {
    t.plan(3)

    var db = level()

    db.on('open', function () {
      t.ok(down(db) instanceof expectedDown, 'got expected down')
    })

    db.put('foo', 'bar', function (err) {
      t.ifError(err)
      t.notOk(err)
    })
  })

  test('with options and callback', function (t) {
    t.plan(6)

    level({ valueEncoding: 'json' }, function (err, db) {
      t.ifError(err)
      t.ok(db.isOpen())
      t.ok(down(db) instanceof expectedDown, 'got expected down')

      var key = '' + Math.random()
      var value = { test_key: '' + new Date() }

      db.put(key, value, function (err) {
        t.notOk(err)

        db.get(key, function (err, _value) {
          t.ifError(err)
          t.deepEqual(_value, value)
        })
      })
    })
  })

  test('with options', function (t) {
    t.plan(4)

    var db = level({ valueEncoding: 'json' })
    var key = '' + Math.random()
    var value = { test_key: '' + new Date() }

    db.on('open', function () {
      t.ok(down(db) instanceof expectedDown, 'got expected down')
    })

    db.put(key, value, function (err) {
      t.notOk(err)

      db.get(key, function (err, _value) {
        t.ifError(err)
        t.deepEqual(_value, value)
      })
    })
  })

  test('with callback', function (t) {
    t.plan(6)

    level(function (err, db) {
      t.ifError(err)
      t.ok(db.isOpen())
      t.ok(down(db) instanceof expectedDown, 'got expected down')

      db.put('key', 'value', function (err) {
        t.notOk(err)

        db.get('key', function (err, value) {
          t.ifError(err)
          t.is(value, 'value')
        })
      })
    })
  })
}

exports.customLayers = function (level, expectedDown, expectedUp, rawValue) {
  test('custom layers with auto-open', function (t) {
    t.plan(9)

    var ret = level(function (err, db) {
      t.ifError(err)
      t.is(db, ret, 'got db')
      t.ok(down(db) instanceof expectedDown, 'got expected down')
      t.ok(db instanceof expectedUp, 'got expected up')

      db.put('key', 'value', function (err) {
        t.notOk(err)

        db.get('key', { asBuffer: false }, function (err, value) {
          t.ifError(err)
          t.is(value, 'value')
        })

        db.get('key', { valueEncoding: 'id', asBuffer: false }, function (err, value) {
          t.ifError(err)
          t.is(value, rawValue)
        })
      })
    })
  })
}

exports.options = function (levelTest) {
  test('opts precedence', function (t) {
    t.plan(6)

    var level = levelTest({ valueEncoding: 'utf8' })
    var db1 = level()
    var db2 = level({ valueEncoding: 'json' })
    var value = { test: true }

    db1.put('key', value, function (err) {
      t.ifError(err)

      db1.get('key', function (err, value1) {
        t.ifError(err)
        t.is(value1, '[object Object]')
      })
    })

    db2.put('key', value, function (err) {
      t.ifError(err)

      db2.get('key', function (err, value2) {
        t.ifError(err)
        t.deepEqual(value2, value)
      })
    })
  })
}
<|endoftext|>


<commit_before>var hat = require('hat');
var cache = require('memory-cache');
var express = require('express');

var app = express();

app.get('/:id', function(req, res){
    var id = req.params.id;
    console.log("GET  - Getting Image: " + id);

    var image = cache.get(id);
    if (image)
    {
        console.log('     - Image found');
        var buffer = new Buffer(image, 'base64');
        res.set({
          'Content-Type': 'image/jpeg',
          'Content-Length': buffer.length,
          'Expires': new Date(Date.now() + 30000).toUTCString()
        });

        res.send(buffer);
    } else {
        console.log("     - Image not found.");
        res.send(404, "Could not find ID: " + id);
    }
});

app.get('/', function(req, res){
    res.redirect(301, 'https://github.com/steventhuriot/HyperIcon');
});

app.post('/', function(req, res) {
    var id = hat();
    var data = '';

    req.on('data', function(chunk) {
        data += chunk;
    });
    req.on('end', function() {
        cache.put(id, data, 30000);
    });

    console.log("POST - Created Image: " + id);
    res.send(id);
});

var port = process.env.PORT || 3000;
app.listen(port);

console.log("HyperIcon up and running.");<commit_msg>Heroku is giving issues with cache population<commit_after>var hat = require('hat');
var cache = require('memory-cache');
var express = require('express');

var app = express();

app.use (function(req, res, next) {
	if (req.method == 'POST') {
		var data='';
		req.setEncoding('utf8');
		req.on('data', function(chunk) {
		   data += chunk;
		});

		req.on('end', function() {
			req.body = data;
			next();
		});
	} else {
		next();
	}
});

app.get('/', function(req, res) {
    res.redirect(301, 'https://github.com/steventhuriot/HyperIcon');
});

app.get('/:id', function(req, res) {
    var id = req.params.id;
    console.log("GET  - Getting Image: " + id);

    var image = cache.get(id);
    if (image)
    {
        console.log('     - Image found');
        var buffer = new Buffer(image, 'base64');
        res.set({
          'Content-Type': 'image/jpeg',
          'Content-Length': buffer.length,
          'Expires': new Date(Date.now() + 30000).toUTCString()
        });

        res.send(buffer);
    } else {
        console.log("     - Image not found.");
        res.send(404, "Could not find ID: " + id);
    }
});

app.post('/', function(req, res) {
    var id = hat();
	cache.put(id, req.body, 30000);
	console.log("POST - Created Image: " + id);
	res.send(id);
});

var port = process.env.PORT || 3000;
app.listen(port);

console.log("HyperIcon up and running.");
<|endoftext|>


<commit_before>/**
 * Requires all lines to be at most the number of characters specified
 *
 * Types: `Integer` or `Object`
 *
 * Values:
 *  - `Integer`: lines should be at most the number of characters specified
 *  - `Object`:
 *     - `value`: (required) lines should be at most the number of characters specified
 *     - `tabSize`: (default: `1`) considered the tab character as number of specified spaces
 *     - `allExcept`: (default: `[]`) an array of conditions that will exempt a line
 *        - `regex`: allows regular expression literals to break the rule
 *        - `comments`: allows comments to break the rule
 *        - `urlComments`: allows comments with long urls to break the rule
 *        - `functionSignature`: allows function definitions to break the rule
 *        - `require`: allows require expressions to break the rule
 *     - `allowRegex`: *deprecated* use `allExcept: ["regex"]` instead
 *     - `allowComments`: *deprecated* use `allExcept: ["comments"]` instead
 *     - `allowUrlComments`: *deprecated* use `allExcept: ["urlComments"]` instead
 *
 * JSHint: [`maxlen`](http://jshint.com/docs/options/#maxlen)
 *
 * #### Example
 *
 * ```js
 * "maximumLineLength": 40
 * ```
 *
 * ##### Valid
 *
 * ```js
 * var aLineOf40Chars = 123456789012345678;
 * ```
 *
 * ##### Invalid
 *
 * ```js
 * var aLineOf41Chars = 1234567890123456789;
 * ```
 */

var assert = require('assert');

module.exports = function() {};

module.exports.prototype = {

    configure: function(maximumLineLength) {
        this._tabSize = '';
        this._allowRegex = false;
        this._allowComments = false;
        this._allowUrlComments = false;
        this._allowRequire = false;

        if (typeof maximumLineLength === 'object') {
            assert(
                typeof maximumLineLength.value === 'number',
                this.getOptionName() + ' option requires the "value" property to be defined'
            );

            this._maximumLineLength = maximumLineLength.value;
            var tabSize = maximumLineLength.tabSize || 0;

            while (tabSize--) {
                this._tabSize += ' ';
            }

            var exceptions = maximumLineLength.allExcept || [];
            this._allowRegex = (exceptions.indexOf('regex') !== -1);
            this._allowComments = (exceptions.indexOf('comments') !== -1);
            this._allowUrlComments = (exceptions.indexOf('urlComments') !== -1);
            this._allowFunctionSignature = (exceptions.indexOf('functionSignature') !== -1);
            this._allowRequire = (exceptions.indexOf('require') !== -1);

            if (maximumLineLength.hasOwnProperty('allowRegex')) {
                this._allowRegex = (maximumLineLength.allowRegex === true);
            }
            if (maximumLineLength.hasOwnProperty('allowComments')) {
                this._allowComments = (maximumLineLength.allowComments === true);
            }
            if (maximumLineLength.hasOwnProperty('allowUrlComments')) {
                this._allowUrlComments = (maximumLineLength.allowUrlComments === true);
            }

        } else {
            assert(
                typeof maximumLineLength === 'number',
                this.getOptionName() + ' option requires number value or options object'
            );

            this._maximumLineLength = maximumLineLength;
        }
    },

    getOptionName: function() {
        return 'maximumLineLength';
    },

    check: function(file, errors) {
        var maximumLineLength = this._maximumLineLength;

        var line;
        var lines = this._allowComments ?
            file.getLinesWithCommentsRemoved() : file.getLines();

        // This check should not be destructive
        lines = lines.slice();

        if (this._allowRegex) {
            file.iterateTokensByType('RegularExpression', function(token) {
                for (var i = token.loc.start.line; i <= token.loc.end.line; i++) {
                    lines[i - 1] = '';
                }
            });
        }

        if (this._allowUrlComments) {
            file.iterateTokensByType(['Line', 'Block'], function(comment) {
                for (var i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
                    lines[i - 1] = lines[i - 1].replace(/(http|https|ftp):\/\/[^\s$]+/, '');
                }
            });
        }

        if (this._allowFunctionSignature) {
            var functionDeclarationLocs = [];
            var searchBodyForDecl = function searchBodyForDecl(node) {
                node.body.forEach(function(bodyNode) {
                    if (bodyNode.type === 'FunctionDeclaration') {
                        // get the loc for the `function Identifier` portion
                        functionDeclarationLocs.push(bodyNode.id.loc);
                        // get the locs for the params
                        bodyNode.params.forEach(function(param) { functionDeclarationLocs.push(param.loc); });
                        return;

                    } else if (bodyNode.type === 'ClassDeclaration') {
                        searchBodyForDecl(bodyNode.body);
                        return;

                    } else if (bodyNode.type === 'MethodDefinition') {
                        // get the loc for method name
                        functionDeclarationLocs.push(bodyNode.key.loc);
                        // get the locs for the params
                        bodyNode.value.params.forEach(function(param) { functionDeclarationLocs.push(param.loc); });
                        return;
                    }
                });
            };
            searchBodyForDecl(file.getTree());

            functionDeclarationLocs.forEach(function(loc) {
                for (var i = loc.start.line; i <= loc.end.line; i++) {
                    lines[i - 1] = '';
                }
            });
        }

        if (this._allowRequire) {
            file.iterateNodesByType('CallExpression', function(node) {
                if (node.callee.name === 'require') {
                    for (var i = node.loc.start.line; i <= node.loc.end.line; i++) {
                        lines[i - 1] = '';
                    }
                }
            });
        }

        for (var i = 0, l = lines.length; i < l; i++) {
            line = this._tabSize ? lines[i].replace(/\t/g, this._tabSize) : lines[i];

            if (line.length > maximumLineLength) {
                errors.add(
                    'Line must be at most ' + maximumLineLength + ' characters',
                    i + 1,
                    lines[i].length
                );
            }
        }
    }

};
<commit_msg>`maximumLineLength`: abstract common boilerplate into local `removeLoc` function<commit_after>/**
 * Requires all lines to be at most the number of characters specified
 *
 * Types: `Integer` or `Object`
 *
 * Values:
 *  - `Integer`: lines should be at most the number of characters specified
 *  - `Object`:
 *     - `value`: (required) lines should be at most the number of characters specified
 *     - `tabSize`: (default: `1`) considered the tab character as number of specified spaces
 *     - `allExcept`: (default: `[]`) an array of conditions that will exempt a line
 *        - `regex`: allows regular expression literals to break the rule
 *        - `comments`: allows comments to break the rule
 *        - `urlComments`: allows comments with long urls to break the rule
 *        - `functionSignature`: allows function definitions to break the rule
 *        - `require`: allows require expressions to break the rule
 *     - `allowRegex`: *deprecated* use `allExcept: ["regex"]` instead
 *     - `allowComments`: *deprecated* use `allExcept: ["comments"]` instead
 *     - `allowUrlComments`: *deprecated* use `allExcept: ["urlComments"]` instead
 *
 * JSHint: [`maxlen`](http://jshint.com/docs/options/#maxlen)
 *
 * #### Example
 *
 * ```js
 * "maximumLineLength": 40
 * ```
 *
 * ##### Valid
 *
 * ```js
 * var aLineOf40Chars = 123456789012345678;
 * ```
 *
 * ##### Invalid
 *
 * ```js
 * var aLineOf41Chars = 1234567890123456789;
 * ```
 */

var assert = require('assert');

module.exports = function() {};

module.exports.prototype = {

    configure: function(maximumLineLength) {
        this._tabSize = '';
        this._allowRegex = false;
        this._allowComments = false;
        this._allowUrlComments = false;
        this._allowRequire = false;

        if (typeof maximumLineLength === 'object') {
            assert(
                typeof maximumLineLength.value === 'number',
                this.getOptionName() + ' option requires the "value" property to be defined'
            );

            this._maximumLineLength = maximumLineLength.value;
            var tabSize = maximumLineLength.tabSize || 0;

            while (tabSize--) {
                this._tabSize += ' ';
            }

            var exceptions = maximumLineLength.allExcept || [];
            this._allowRegex = (exceptions.indexOf('regex') !== -1);
            this._allowComments = (exceptions.indexOf('comments') !== -1);
            this._allowUrlComments = (exceptions.indexOf('urlComments') !== -1);
            this._allowFunctionSignature = (exceptions.indexOf('functionSignature') !== -1);
            this._allowRequire = (exceptions.indexOf('require') !== -1);

            if (maximumLineLength.hasOwnProperty('allowRegex')) {
                this._allowRegex = (maximumLineLength.allowRegex === true);
            }
            if (maximumLineLength.hasOwnProperty('allowComments')) {
                this._allowComments = (maximumLineLength.allowComments === true);
            }
            if (maximumLineLength.hasOwnProperty('allowUrlComments')) {
                this._allowUrlComments = (maximumLineLength.allowUrlComments === true);
            }

        } else {
            assert(
                typeof maximumLineLength === 'number',
                this.getOptionName() + ' option requires number value or options object'
            );

            this._maximumLineLength = maximumLineLength;
        }
    },

    getOptionName: function() {
        return 'maximumLineLength';
    },

    check: function(file, errors) {
        var maximumLineLength = this._maximumLineLength;

        var line;
        var lines = this._allowComments ?
            file.getLinesWithCommentsRemoved() : file.getLines();

        // This check should not be destructive
        lines = lines.slice();

        var removeLoc = function(tokenOrNode) {
            for (var i = tokenOrNode.loc.start.line; i <= tokenOrNode.loc.end.line; i++) {
                lines[i - 1] = '';
            }
        };

        if (this._allowRegex) {
            file.iterateTokensByType('RegularExpression', function(token) {
                removeLoc(token);
            });
        }

        if (this._allowUrlComments) {
            file.iterateTokensByType(['Line', 'Block'], function(comment) {
                for (var i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
                    lines[i - 1] = lines[i - 1].replace(/(http|https|ftp):\/\/[^\s$]+/, '');
                }
            });
        }

        if (this._allowFunctionSignature) {
            var functionDeclarationLocs = [];
            var searchBodyForDecl = function searchBodyForDecl(node) {
                node.body.forEach(function(bodyNode) {
                    if (bodyNode.type === 'FunctionDeclaration') {
                        // get the loc for the `function Identifier` portion
                        functionDeclarationLocs.push(bodyNode.id.loc);
                        // get the locs for the params
                        bodyNode.params.forEach(function(param) { functionDeclarationLocs.push(param.loc); });
                        return;

                    } else if (bodyNode.type === 'ClassDeclaration') {
                        searchBodyForDecl(bodyNode.body);
                        return;

                    } else if (bodyNode.type === 'MethodDefinition') {
                        // get the loc for method name
                        functionDeclarationLocs.push(bodyNode.key.loc);
                        // get the locs for the params
                        bodyNode.value.params.forEach(function(param) { functionDeclarationLocs.push(param.loc); });
                        return;
                    }
                });
            };
            searchBodyForDecl(file.getTree());

            functionDeclarationLocs.forEach(function(loc) {
                for (var i = loc.start.line; i <= loc.end.line; i++) {
                    lines[i - 1] = '';
                }
            });
        }

        if (this._allowRequire) {
            file.iterateNodesByType('CallExpression', function(node) {
                if (node.callee.name === 'require') {
                    removeLoc(node);
                }
            });
        }

        for (var i = 0, l = lines.length; i < l; i++) {
            line = this._tabSize ? lines[i].replace(/\t/g, this._tabSize) : lines[i];

            if (line.length > maximumLineLength) {
                errors.add(
                    'Line must be at most ' + maximumLineLength + ' characters',
                    i + 1,
                    lines[i].length
                );
            }
        }
    }

};
<|endoftext|>


<commit_before>DropboxOAuth = {};

// Request dropbox credentials for the user
// @param options {optional}
// @param callback {Function} Callback function to call on
//   completion. Takes one argument, credentialToken on success, or Error on
//   error.
DropboxOAuth.requestCredential = function (options, callback) {
  // support both (options, callback) and (callback).
  if (!callback && typeof options === 'function') {
    callback = options;
    options = {};
  }

  var config = ServiceConfiguration.configurations.findOne({service: 'dropbox'});
  if (!config) {
    callback && callback(new ServiceConfiguration.ConfigError("Service not configured"));
    return;
  }

  var credentialToken = Random.secret();

  var loginStyle = OAuth._loginStyle('dropbox', config, options);

  var loginUrl =
        'https://www.dropbox.com/1/oauth2/authorize' +
        '?response_type=code' +
        '&client_id=' + config.clientId +
        '&redirect_uri=' + OAuth._redirectUri('dropbox', config, {}, {secure: true}) +
        '&state=' + OAuth._stateParam(loginStyle, credentialToken);

  OAuth.launchLogin({
    loginService: "dropbox",
    loginStyle: loginStyle,
    loginUrl: loginUrl,
    credentialRequestCompleteCallback: callback,
    credentialToken: credentialToken,
    popupOptions: { height: 600 }
  });
};
<commit_msg>Hot fix problem of redirect url with close query param<commit_after>DropboxOAuth = {};

// Request dropbox credentials for the user
// @param options {optional}
// @param callback {Function} Callback function to call on
//   completion. Takes one argument, credentialToken on success, or Error on
//   error.
DropboxOAuth.requestCredential = function (options, callback) {
  // support both (options, callback) and (callback).
  if (!callback && typeof options === 'function') {
    callback = options;
    options = {};
  }

  var config = ServiceConfiguration.configurations.findOne({service: 'dropbox'});
  if (!config) {
    callback && callback(new ServiceConfiguration.ConfigError("Service not configured"));
    return;
  }

  var credentialToken = Random.secret();

  var loginStyle = OAuth._loginStyle('dropbox', config, options);

  var loginUrl =
        'https://www.dropbox.com/1/oauth2/authorize' +
        '?response_type=code' +
        '&client_id=' + config.clientId +
        '&redirect_uri=' + OAuth._redirectUri('dropbox', config, {}, {secure: true}) +
        '&state=' + OAuth._stateParam(loginStyle, credentialToken);
  loginUrl = loginUrl.replace('?close&', '?close=true&');

  OAuth.launchLogin({
    loginService: "dropbox",
    loginStyle: loginStyle,
    loginUrl: loginUrl,
    credentialRequestCompleteCallback: callback,
    credentialToken: credentialToken,
    popupOptions: { height: 600 }
  });
};
<|endoftext|>


<commit_before>var fs = require('fs');
var filename = '/users/petersirka/desktop/test/aaa';
var nosql = require('../index');
var db = nosql.load(filename);
var assert = require('assert');

var write = true;
var read = true;
var remove = true;

var indexComplete = 0;
var indexInsert = 0;

db.on('insert', function(count) {
	console.log('insert ---> ', count);
});

db.on('error', function(err, name) {
	console.log('error ---> ', err, name);
});

db.on('drop', function(a) {
	console.log('DROP', a);
});

db.on('update/remove', function(beg, countUpdate, countDelete) {
	console.log('update/remove ---> ', beg, countUpdate, countDelete);
});

db.on('update', function(doc) {
	console.log('THIS UPDATED', doc);
});

db.on('resume', function() {
	console.log('RESUME');
});

db.on('each', function(status) {
	console.log('each ---> ', status);
});

db.on('complete', function(status) {
	console.log('complete --> ', status);
});

db.on('change', function(description) {
	console.log('change --> ', description);
});

if (write) {

	if (fs.existsSync(filename + '.nosql'))
		fs.unlinkSync(filename + '.nosql');

	for (var i = 0; i < 100000; i++)
		db.insert({ index: i });

	db.insert({ index: 100001 }, 'super');
}

if (read) {
	setTimeout(function() {

		db.read('doc.index > 0 && doc.index < 5', function(e, selected) {

			var str = '';

			selected.sort(function(a,b) {
				if (a.index < b.index)
					return -1;
				return 1;
			});

			selected.forEach(function(o) {
				str += o.index + '';
			});

			console.log('--' + str);
			assert.ok(str === '234', 'read');

			console.log(selected);
		}, 1, 3);

		db.read('doc.index > 100 && doc.index < 105', function(e, selected) {
			console.log(selected);
		}, 1, 3);

		db.each(function(o) {
			if (o.index === 4300)
				console.log('>>> ', o);
		});

	}, 500);
}

db.one('doc.index === 89080', function(e, doc) {
	console.log(doc);
});

setTimeout(function() {
	db.top(5, 'doc.index < 15', function(e, selected) {
		console.log('TOP', selected);
	});
}, 500);

setTimeout(function() {

	db.update(function(o) {

		if (o.index > 10 && o.index < 20)
			o.index = 10000;

		return o;
	}, function() {
		console.log('UPDATED');
	}, 'Index > 10 && Index < 20');

}, 5000);

/*
setTimeout(function() {
	db.drop(function() {
		console.log('DROPPED');
	});
}, 7000);
*/

setTimeout(function() {
	db.count(null, function(e, count) {
		console.log('count');
	});
}, 2000);

if (remove) {
	setTimeout(function() {
		db.remove('doc.index > 105', function() {
			console.log('remove');
		}, 'remove doc.index > 105');

		console.log(db.created);
		console.log(db.updated);
	}, 4000);
}

setTimeout(function() {

	console.log('');
	console.log('CHANGELOG:');
	console.log('');
	db.changelog.read(function(lines) {
		console.log(lines);
	});
/*
	db.clear(function() {
		console.log('clear');
		db.insert({r: true});
	}, 'clear');
*/
}, 7000);<commit_msg>Fix changelog.<commit_after>var fs = require('fs');
var filename = '/users/petersirka/desktop/test/aaa';
var nosql = require('../index');
var db = nosql.load(filename);
var assert = require('assert');

var write = true;
var read = true;
var remove = true;

var indexComplete = 0;
var indexInsert = 0;

db.on('insert', function(count) {
	console.log('insert ---> ', count);
});

db.on('error', function(err, name) {
	console.log('error ---> ', err, name);
});

db.on('drop', function(a) {
	console.log('DROP', a);
});

db.on('update/remove', function(beg, countUpdate, countDelete) {
	console.log('update/remove ---> ', beg, countUpdate, countDelete);
});

db.on('update', function(doc) {
	console.log('THIS UPDATED', doc);
});

db.on('resume', function() {
	console.log('RESUME');
});

db.on('each', function(status) {
	console.log('each ---> ', status);
});

db.on('complete', function(status) {
	console.log('complete --> ', status);
});

db.on('change', function(description) {
	console.log('change --> ', description);
});

if (write) {

	if (fs.existsSync(filename + '.nosql'))
		fs.unlinkSync(filename + '.nosql');

	for (var i = 0; i < 100000; i++)
		db.insert({ index: i });

	db.insert({ index: 100001 }, 'super');
}

if (read) {
	setTimeout(function() {

		db.read('doc.index > 0 && doc.index < 5', function(e, selected) {

			var str = '';

			selected.sort(function(a,b) {
				if (a.index < b.index)
					return -1;
				return 1;
			});

			selected.forEach(function(o) {
				str += o.index + '';
			});

			console.log('--' + str);
			assert.ok(str === '234', 'read');

			console.log(selected);
		}, 1, 3);

		db.read('doc.index > 100 && doc.index < 105', function(e, selected) {
			console.log(selected);
		}, 1, 3);

		db.each(function(o) {
			if (o.index === 4300)
				console.log('>>> ', o);
		});

	}, 500);
}

db.one('doc.index === 89080', function(e, doc) {
	console.log(doc);
});

setTimeout(function() {
	db.top(5, 'doc.index < 15', function(e, selected) {
		console.log('TOP', selected);
	});
}, 500);

setTimeout(function() {

	db.update(function(o) {

		if (o.index > 10 && o.index < 20)
			o.index = 10000;

		return o;
	}, function() {
		console.log('UPDATED');
	}, 'Index > 10 && Index < 20');

}, 5000);

/*
setTimeout(function() {
	db.drop(function() {
		console.log('DROPPED');
	});
}, 7000);
*/

setTimeout(function() {
	db.count(null, function(e, count) {
		console.log('count');
	});
}, 2000);

if (remove) {
	setTimeout(function() {
		db.remove('doc.index > 105', function() {
			console.log('remove');
		}, 'remove doc.index > 105');

		console.log(db.created);
		console.log(db.updated);
	}, 4000);
}

setTimeout(function() {

	console.log('');
	console.log('CHANGELOG:');
	console.log('');
	db.changelog.read(function(err, lines) {
		console.log(lines);
	});
/*
	db.clear(function() {
		console.log('clear');
		db.insert({r: true});
	}, 'clear');
*/
}, 7000);<|endoftext|>


<commit_before>(function(){

	var DEBUG = false;

	var doPost = false;

	try {
		doPost = !!window.top.postMessage;
	} catch(e){}

	var search = window.location.search,
		url, index;
	if( ( index = search.indexOf( "swarmURL=" ) ) != -1 )
		url = decodeURIComponent( search.slice( index + 9 ) );

	if ( !DEBUG && (!url || url.indexOf("http") !== 0) ) {
		return;
	}

	var submitTimeout = 5;

	var curHeartbeat;
	var beatRate = 240;

	// Expose the TestSwarm API
	window.TestSwarm = {
		submit: submit,
		heartbeat: function(){
			if ( curHeartbeat ) {
				clearTimeout( curHeartbeat );
			}

			curHeartbeat = setTimeout(function(){
				submit({ fail: -1, total: -1 });
			}, beatRate * 1000);
		},
		serialize: function(){
			return trimSerialize();
		}
	};

	// Prevent careless things from executing
	window.print = window.confirm = window.alert = window.open = function(){};

	window.onerror = function(e){
		document.body.appendChild( document.createTextNode( "ERROR: " + e ));
		submit({ fail: 0, error: 1, total: 1 });
		return false;
	};

	// QUnit (jQuery)
	// http://docs.jquery.com/QUnit
	if ( typeof QUnit !== "undefined" ) {
		QUnit.done = function( results ){
			submit({
				fail: results.failed,
				error: 0,
				total: results.total
			});
		};

		QUnit.log = window.TestSwarm.heartbeat;
		window.TestSwarm.heartbeat();

		window.TestSwarm.serialize = function(){
			// Clean up the HTML (remove any un-needed test markup)
			remove("nothiddendiv");
			remove("loadediframe");
			remove("dl");
			remove("main");

			// Show any collapsed results
			var ol = document.getElementsByTagName("ol");
			for ( var i = 0; i < ol.length; i++ ) {
				ol[i].style.display = "block";
			}

			return trimSerialize();
		};

	// UnitTestJS (Prototype, Scriptaculous)
	// http://github.com/tobie/unittest_js/tree/master
	} else if ( typeof Test !== "undefined" && Test && Test.Unit && Test.Unit.runners ) {
		var total_runners = Test.Unit.runners.length, cur_runners = 0;
		var total = 0, fail = 0, error = 0;

		for (var i = 0; i < Test.Unit.runners.length; i++) (function(i){
			var finish = Test.Unit.runners[i].finish;
			Test.Unit.runners[i].finish = function(){
				finish.call( this );

				var results = this.getResult();
				total += results.assertions;
				fail += results.failures;
				error += results.errors;

				if ( ++cur_runners === total_runners ) {
					submit({
						fail: fail,
						error: error,
						total: total
					});
				}
			};
		})(i);

	// JSSpec (MooTools)
	// http://jania.pe.kr/aw/moin.cgi/JSSpec
	} else if ( typeof JSSpec !== "undefined" && JSSpec && JSSpec.Logger ) {
		var onRunnerEnd = JSSpec.Logger.prototype.onRunnerEnd;
		JSSpec.Logger.prototype.onRunnerEnd = function(){
			onRunnerEnd.call(this);

			// Show any collapsed results
			var ul = document.getElementsByTagName("ul");
			for ( var i = 0; i < ul.length; i++ ) {
				ul[i].style.display = "block";
			}

			submit({
				fail: JSSpec.runner.getTotalFailures(),
				error: JSSpec.runner.getTotalErrors(),
				total: JSSpec.runner.totalExamples
			});
		};

		window.TestSwarm.serialize = function(){
			// Show any collapsed results
			var ul = document.getElementsByTagName("ul");
			for ( var i = 0; i < ul.length; i++ ) {
				ul[i].style.display = "block";
			}

			return trimSerialize();
		};

	// JSUnit
	// http://www.jsunit.net/
	// Note: Injection file must be included before the frames
	//       are document.write()d into the page.
	} else if ( typeof JsUnitTestManager !== "undefined" ) {
		var _done = JsUnitTestManager.prototype._done;
		JsUnitTestManager.prototype._done = function(){
			_done.call(this);

			submit({
				fail: this.failureCount,
				error: this.errorCount,
				total: this.totalCount
			});
		};

		window.TestSwarm.serialize = function(){
			return "
" + this.log.join("\n") + "
";
		};

	// Selenium Core
	// http://seleniumhq.org/projects/core/
	} else if ( typeof SeleniumTestResult !== "undefined" && typeof LOG !== "undefined" ) {
		// Completely overwrite the postback
		SeleniumTestResult.prototype.post = function(){
			submit({
				fail: this.metrics.numCommandFailures,
				error: this.metrics.numCommandErrors,
				total: this.metrics.numCommandPasses + this.metrics.numCommandFailures + this.metrics.numCommandErrors
			});
		};

		window.TestSwarm.serialize = function(){
			var results = [];
			while ( LOG.pendingMessages.length ) {
				var msg = LOG.pendingMessages.shift();
				results.push( msg.type + ": " + msg.msg );
			}

			return "
" + results.join("\n") + "
";
		};

	// Dojo Objective Harness
	// http://docs.dojocampus.org/quickstart/doh
	} else if ( typeof doh !== "undefined" && doh._report ) {
		var _report = doh._report;
		doh._report = function(){
			_report.apply(this, arguments);

			submit({
				fail: doh._failureCount,
				error: doh._errorCount,
				total: doh._testCount
			});
		};

		window.TestSwarm.serialize = function(){
			return "
" + document.getElementById("logBody").innerHTML + "
";
		};
  // Screw.Unit
  // git://github.com/nathansobo/screw-unit.git
	} else if ( typeof Screw !== "undefined" && typeof jQuery !== "undefined" && Screw && Screw.Unit ) {
    $(Screw).bind("after", function() {
     var passed = $(".passed").length;
     var failed = $(".failed").length;
     submit({
        fail: failed,
        error: 0,
        total: failed + passed
      });
    });

    $(Screw).bind("loaded", function() {
      $(".it")
        .bind("passed", window.TestSwarm.heartbeat)
        .bind("failed", window.TestSwarm.heartbeat);
      window.TestSwarm.heartbeat();
    });

    window.TestSwarm.serialize = function(){
    	return trimSerialize();
    };
  }

	function trimSerialize(doc) {
		doc = doc || document;

		var scripts = doc.getElementsByTagName("script");
		while ( scripts.length ) {
			remove( scripts[0] );
		}

		var root = window.location.href.replace(/(https?:\/\/.*?)\/.*/, "$1");
		var cur = window.location.href.replace(/[^\/]*$/, "");

		var links = doc.getElementsByTagName("link");
		for ( var i = 0; i < links.length; i++ ) {
			var href = links[i].href;
			if ( href.indexOf("/") === 0 ) {
				href = root + href;
			} else if ( !/^https?:\/\//.test( href ) ) {
				href = cur + href;
			}
			links[i].href = href;
		}

		return ("" + doc.documentElement.innerHTML + "")
			.replace(/\s+/g, " ");
	}

	function remove(elem){
		if ( typeof elem === "string" ) {
			elem = document.getElementById( elem );
		}

		if ( elem ) {
			elem.parentNode.removeChild( elem );
		}
	}

	function submit(params){
		if ( curHeartbeat ) {
			clearTimeout( curHeartbeat );
		}

		var paramItems = (url.split("?")[1] || "").split("&");

		for ( var i = 0; i < paramItems.length; i++ ) {
			if ( paramItems[i] ) {
				var parts = paramItems[i].split("=");
				if ( !params[ parts[0] ] ) {
					params[ parts[0] ] = parts[1];
				}
			}
		}

		if ( !params.state ) {
			params.state = "saverun";
		}

		if ( !params.results ) {
			params.results = window.TestSwarm.serialize();
		}

		if ( doPost ) {
			// Build Query String
			var query = "";

			for ( var i in params ) {
				query += ( query ? "&" : "" ) + i + "=" +
					encodeURIComponent(params[i]);
			}

			if ( DEBUG ) {
				alert( query );
			} else {
				window.top.postMessage( query, "*" );
			}

		} else {
			var form = document.createElement("form");
			form.action = url;
			form.method = "POST";

			for ( var i in params ) {
				var input = document.createElement("input");
				input.type = "hidden";
				input.name = i;
				input.value = params[i];
				form.appendChild( input );
			}

			if ( DEBUG ) {
				alert( form.innerHTML );
			} else {

				// Watch for the result submission timing out
				setTimeout(function(){
					submit( params );
				}, submitTimeout * 1000);

				document.body.appendChild( form );
				form.submit();
			}
		}
	}

})();
<commit_msg>Updated inject script for Test Swarm [#1187]<commit_after>/**
 * JavaScript file to included by the test suite page that it loaded
 * inside the iframe on the "run" pages. This injection must be done
 * by the guest page, it can't be loaded by TestSwarm.
 * Example:
 * - https://github.com/jquery/jquery/blob/master/test/data/testrunner.js
 * - https://github.com/jquery/jquery/blob/master/test/index.html
 *
 * @author John Resig, 2008-2011
 * @author Timo Tijhof, 2012
 * @since 0.1.0
 * @package TestSwarm
 */
/*global jQuery, $, QUnit, Test, JSSpec, JsUnitTestManager, SeleniumTestResult, LOG, doh, Screw*/
/*jshint forin:false, strict:false, loopfunc:true, browser:true, jquery:true*/
(function (undefined) {
	var	DEBUG, doPost, search, url, index, submitTimeout, curHeartbeat,
		beatRate, testFrameworks, onErrorFnPrev;

	DEBUG = false;

	doPost = false;
	search = window.location.search;
	index = search.indexOf( 'swarmURL=' );
	submitTimeout = 5;
	beatRate = 20;

	try {
		doPost = !!window.parent.postMessage;
	} catch ( e ) {}

	if ( index !== -1 ) {
		url = decodeURIComponent( search.slice( index + 9 ) );
	}

	if ( !DEBUG && ( !url || url.indexOf( 'http' ) !== 0 ) ) {
		return;
	}

	// Prevent blocking things from executing
	if ( !DEBUG ) {
		window.print = window.confirm = window.alert = window.open = function () {};
	}

	/** Utility functions **/

	function debugObj( obj ) {
		var i, str = '';
		for ( i in obj ) {
			str += ( str ? '\n' : '' ) + i + ':\n\t ' + obj[i];
		}
		return str;
	}

	function remove( elem ) {
		if ( typeof elem === 'string' ) {
			elem = document.getElementById( elem );
		}

		if ( elem ) {
			elem.parentNode.removeChild( elem );
		}
	}

	function trimSerialize( doc ) {
		var scripts, root, cur, links, i, href;
		doc = doc || document;

		scripts = doc.getElementsByTagName( 'script' );
		while ( scripts.length ) {
			remove( scripts[0] );
		}

		root = window.location.href.replace( /(https?:\/\/.*?)\/.*/, '$1' );
		cur = window.location.href.replace( /[^\/]*$/, '' );

		links = doc.getElementsByTagName( 'link' );
		for ( i = 0; i < links.length; i += 1 ) {
			href = links[i].href;
			if ( href.indexOf( '/' ) === 0 ) {
				href = root + href;
			} else if ( !/^https?:\/\//.test( href ) ) {
				href = cur + href;
			}
			links[i].href = href;
		}

		return ( '' + doc.documentElement.innerHTML + '' )
			.replace( /\s+/g, ' ' );
	}

	function submit( params ) {
		var form, i, input, key, paramItems, parts, query;

		if ( curHeartbeat ) {
			clearTimeout( curHeartbeat );
		}

		paramItems = (url.split( '?' )[1] || '' ).split( '&' );

		for ( i = 0; i < paramItems.length; i += 1 ) {
			if ( paramItems[i] ) {
				parts = paramItems[i].split( '=' );
				if ( !params[ parts[0] ] ) {
					params[ parts[0] ] = parts[1];
				}
			}
		}

		if ( !params.action ) {
			params.action = 'saverun';
		}

		if ( !params.report_html ) {
			params.report_html = window.TestSwarm.serialize();
		}

		if ( DEBUG ) {
			alert( debugObj( params ) ) ;
		}

		if ( doPost ) {
			// Build Query String
			query = '';

			for ( key in params ) {
				query += ( query ? '&' : '' ) + key + '=' + encodeURIComponent( params[key] );
			}

			if ( !DEBUG ) {
				window.parent.postMessage( query, '*' );
			}

		} else {
			form = document.createElement( 'form' );
			form.action = url;
			form.method = 'POST';

			for ( i in params ) {
				input = document.createElement( 'input' );
				input.type = 'hidden';
				input.name = i;
				input.value = params[i];
				form.appendChild( input );
			}

			if ( DEBUG ) {
				alert( url );

			} else {
				// Watch for the result submission timing out
				setTimeout(function () {
					submit( params );
				}, submitTimeout * 1000);

				document.body.appendChild( form );
				form.submit();
			}
		}
	}

	function detectAndInstall() {
		var key;
		for ( key in testFrameworks ) {
			if ( testFrameworks[key].detect() ) {
				testFrameworks[key].install();
				return key;
			}
		}
		return false;
	}

	// Preserve other handlers
	onErrorFnPrev = window.onerror;

	// Cover uncaught exceptions
	// Returning true will surpress the default browser handler,
	// returning false will let it run.
	window.onerror = function ( error, filePath, linerNr ) {
		var ret = false;
		if ( onErrorFnPrev ) {
			ret = onErrorFnPrev( error, filePath, linerNr );
		}

		// Treat return value as window.onerror itself does,
		// Only do our handling if not surpressed.
		if ( ret !== true ) {
			document.body.appendChild( document.createTextNode( '[TestSwarm] window.onerror: ' + error ) );
			submit({ fail: 0, error: 1, total: 1 });

			return false;
		}

		return ret;
	};

	// Expose the TestSwarm API
	window.TestSwarm = {
		submit: submit,
		heartbeat: function () {
			if ( curHeartbeat ) {
				clearTimeout( curHeartbeat );
			}

			curHeartbeat = setTimeout(function () {
				submit({ fail: -1, total: -1 });
			}, beatRate * 1000);
		},
		serialize: function () {
			return trimSerialize();
		}
	};

	testFrameworks = {
		// QUnit (by jQuery)
		// http://docs.jquery.com/QUnit
		'QUnit': {
			detect: function () {
				return typeof QUnit !== 'undefined';
			},
			install: function () {
				QUnit.done = function ( results ) {
					submit({
						fail: results.failed,
						error: 0,
						total: results.total
					});
				};

				QUnit.log = window.TestSwarm.heartbeat;
				window.TestSwarm.heartbeat();

				window.TestSwarm.serialize = function () {
					var ol, i;

					// Clean up the HTML (remove any un-needed test markup)
					remove( 'nothiddendiv' );
					remove( 'loadediframe' );
					remove( 'dl' );
					remove( 'main' );

					// Show any collapsed results
					ol = document.getElementsByTagName( 'ol' );
					for ( i = 0; i < ol.length; i += 1 ) {
						ol[i].style.display = 'block';
					}

					return trimSerialize();
				};
			}
		},

		// UnitTestJS (Prototype, Scriptaculous)
		// https://github.com/tobie/unittest_js
		'UnitTestJS': {
			detect: function () {
				return typeof Test !== 'undefined' && Test && Test.Unit && Test.Unit.runners;
			},
			install: function () {
				var	total_runners = Test.Unit.runners.length,
					cur_runners = 0,
					total = 0,
					fail = 0,
					error = 0,
					i;

				for ( i = 0; i < Test.Unit.runners.length; i += 1 ) {
					// Need to proxy the i variable into a local scope,
					// otherwise all the finish-functions created in this loop
					// will refer to the same i variable..
					(function ( i ) {
						var finish, results;

						finish = Test.Unit.runners[i].finish;
						Test.Unit.runners[i].finish = function () {
							finish.call( this );

							results = this.getResult();
							total += results.assertions;
							fail += results.failures;
							error += results.errors;

							cur_runners += 1;
							if ( cur_runners === total_runners ) {
								submit({
									fail: fail,
									error: error,
									total: total
								});
							}
						};
					}( i ) );
				}
			}
		},

		// JSSpec (MooTools)
		// http://jania.pe.kr/aw/moin.cgi/JSSpec
		// https://code.google.com/p/jsspec/
		'JSSpec': {
			detect: function () {
				return typeof JSSpec !== 'undefined' && JSSpec && JSSpec.Logger;
			},
			install: function () {
				var onRunnerEnd = JSSpec.Logger.prototype.onRunnerEnd;
				JSSpec.Logger.prototype.onRunnerEnd = function () {
					var ul, i;
					onRunnerEnd.call( this );

					// Show any collapsed results
					ul = document.getElementsByTagName( 'ul' );
					for ( i = 0; i < ul.length; i += 1 ) {
						ul[i].style.display = 'block';
					}

					submit({
						fail: JSSpec.runner.getTotalFailures(),
						error: JSSpec.runner.getTotalErrors(),
						total: JSSpec.runner.totalExamples
					});
				};

				window.TestSwarm.serialize = function () {
					var ul, i;
					// Show any collapsed results
					ul = document.getElementsByTagName( 'ul' );
					for ( i = 0; i < ul.length; i += 1 ) {
						ul[i].style.display = 'block';
					}

					return trimSerialize();
				};
			}
		},

		// JSUnit
		// http://www.jsunit.net/
		// Note: Injection file must be included before the frames
		// are document.write()d into the page.
		'JSUnit': {
			detect: function () {
				return typeof JsUnitTestManager !== 'undefined';
			},
			install: function () {
				var _done = JsUnitTestManager.prototype._done;
				JsUnitTestManager.prototype._done = function () {
					_done.call( this );

					submit({
						fail: this.failureCount,
						error: this.errorCount,
						total: this.totalCount
					});
				};

				window.TestSwarm.serialize = function () {
					return '
' + this.log.join( '\n' ) + '
';
				};
			}
		},

		// Selenium Core
		// http://seleniumhq.org/projects/core/
		'Selenium': {
			detect: function () {
				return typeof SeleniumTestResult !== 'undefined' && typeof LOG !== 'undefined';
			},
			install: function () {
				// Completely overwrite the postback
				SeleniumTestResult.prototype.post = function () {
					submit({
						fail: this.metrics.numCommandFailures,
						error: this.metrics.numCommandErrors,
						total: this.metrics.numCommandPasses + this.metrics.numCommandFailures + this.metrics.numCommandErrors
					});
				};

				window.TestSwarm.serialize = function () {
					var results = [], msg;
					while ( LOG.pendingMessages.length ) {
						msg = LOG.pendingMessages.shift();
						results.push( msg.type + ': ' + msg.msg );
					}

					return '
' + results.join( '\n' ) + '
';
				};
			}
		},

		// Dojo Objective Harness
		// http://docs.dojocampus.org/quickstart/doh
		'DOH': {
			detect: function () {
				return typeof doh !== 'undefined' && doh._report;
			},
			install: function () {
				var _report = doh._report;
				doh._report = function () {
					_report.apply( this, arguments );

					submit({
						fail: doh._failureCount,
						error: doh._errorCount,
						total: doh._testCount
					});
				};

				window.TestSwarm.serialize = function () {
					return '
' + document.getElementById( 'logBody' ).innerHTML + '
';
				};
			}
		},

		// Screw.Unit
		// https://github.com/nathansobo/screw-unit
		'Screw.Unit': {
			detect: function () {
				return typeof Screw !== 'undefined' && typeof jQuery !== 'undefined' && Screw && Screw.Unit;
			},
			install: function () {
				$(Screw).bind( 'after', function () {
					var	passed = $( '.passed' ).length,
						failed = $( '.failed' ).length;
					submit({
						fail: failed,
						error: 0,
						total: failed + passed
					});
				});

				$( Screw ).bind( 'loaded', function () {
					$( '.it' )
						.bind( 'passed', window.TestSwarm.heartbeat )
						.bind( 'failed', window.TestSwarm.heartbeat );
					window.TestSwarm.heartbeat();
				});

				window.TestSwarm.serialize = function () {
					return trimSerialize();
				};
			}
		}
	};

	detectAndInstall();

}() );
<|endoftext|>


<commit_before>var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var merge = require('merge-stream');
var browserSync = require('browser-sync');
var reload = browserSync.reload;

/* ========================================================
 * Paths Variable
 * ======================================================== */

var basePaths = {
    root: '../',
    theme: './',
    style: './sass/',
    bower: './bower_components/',
    npm: './node_modules/'
}

var style = {
    main: basePaths.style + 'style.scss',
    vendor: basePaths.style + 'vendor/'
}

var module = {
    slick: basePaths.npm + 'slick-carousel/slick/',
    fontawesome: basePaths.npm + 'slick-carousel/font-awesome/',
    bootstrap: basePaths.npm + 'bootstrap-plugins.sass/assets/'
}

/* ========================================================
 * Tasks with Browser Sync
 * ======================================================== */
gulp.task('browserSync', function() {

    var files = [
        '**/**/*.css',
        '**/**/*.scss',
        '**/**/*.php',
    ];

    browserSync.init(files, {
        proxy: "http://localhost:8888/hut.sctv.co.id/",
        notify: 'false'
    });
});

gulp.task('style', function() {
    return gulp.src(style.main)
        .pipe(plugins.plumber({
            errorHandler: function (err) {
                console.log(err);
                this.emit('end');
            }
        }))
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.sass())
        // .pipe(plugins.sass({ outputStyle: 'compressed' }))
        .pipe(plugins.autoprefixer())
        .pipe(plugins.sourcemaps.write())
        .pipe(plugins.rename('style.css'))
        .pipe(gulp.dest(basePaths.theme))
        .pipe(reload({ stream: true }));
});

gulp.task('js', function() {
    return gulp.src([
            './node_modules/jquery/dist/jquery.js',
            './node_modules/fastclick/lib/*.js',
            './node_modules/slick-carousel/slick/slick.js',
            path + '/js/news-sctv.js',
        ])
        .pipe(plugins.concat('news-sctv.js'))
        .pipe(gulp.dest(path))
        .pipe(plugins.uglify())
        .pipe(plugins.concat('news-sctv.min.js'))
        .pipe(gulp.dest(basePaths))
        .pipe(reload({ stream: true }));
});

/* ========================================================
 * Utility Tasks
 * ======================================================== */

gulp.task('bootstrap', function(){

    var bootstrapStyle = gulp.src(module.bootstrap + 'stylesheets/**/**/*')
        .pipe(gulp.dest(style.vendor + 'bootstrap-plugins.sass'));

    return merge(bootstrapStyle);
});

gulp.task('font-awesome', function(){

    //move font awesome scss to our main plugins.sass folder
    var faStyle = gulp.src(module.fontawesome + 'scss/*')
        .pipe(gulp.dest(style.vendor + 'font-awesome'));

    //move font_awesome fonts to themes root folder
    var faFont = gulp.src(module.fontawesome + 'fonts/**/*')
        .pipe(gulp.dest(basePaths.root + 'fonts'));

    //merge tasks
    return merge(faStyle, faFont);

});

gulp.task('slicky', function(){

    // move slick fonts to the fonts under our themes folder
    var slickFont = gulp.src(module.slick + 'fonts/*')
        .pipe(gulp.dest( './fonts'));

    var slickStyle = gulp.src([
        module.slick  + 'slick.scss',
        module.slick  + 'slick-theme.scss'
        ])
    .pipe(gulp.dest(style.vendor + 'slick'));

    // move ajax loader to custom themes folder
    var slickAjaxLoader = gulp.src(module.slick + 'ajax-loader.gif')
        .pipe(gulp.dest(basePaths.root));

    //merge tasks
    return merge(slickFont, slickStyle, slickAjaxLoader);

});

gulp.task('utility', ['bootstrap', 'slicky', 'font-awesome']);

/* ========================================================
 * Default Tasks
 * ======================================================== */

gulp.task('default', ['style', 'js', 'browserSync'], function() {
    gulp.watch('*.scss', {cwd: path + '/sass'}, ['style']);
    gulp.watch('**/*.scss', {cwd: path + '/sass'}, ['style']);
    gulp.watch('*.js', {cwd: path + '/js'}, ['js']);
});<commit_msg>add an array of js files and list of files to move when gulp dist is running<commit_after>var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var merge = require('merge-stream');
var browserSync = require('browser-sync');
var reload = browserSync.reload;

/* ========================================================
 * Paths Variable
 * ======================================================== */

// base paths for the project
var basePaths = {
    root: '../',
    theme: './',
    style: './sass/',
    bower: './bower_components/',
    npm: './node_modules/'
}

// paths for the css/scss
var style = {
    main: basePaths.style + 'style.scss',
    vendor: basePaths.style + 'vendor/'
}

// paths for npm modules
var module = {
    slick: basePaths.npm + 'slick-carousel/slick/',
    fontawesome: basePaths.npm + 'slick-carousel/font-awesome/',
    bootstrap: basePaths.npm + 'bootstrap-plugins.sass/assets/'
}

// paths for the dist folder
var dist = './dist';

// list of files that are being moved to dist folder
var filesToMove = [
    '*.php',
    '*.css',
    './template-parts/*',
    './inc/*',
    './fonts/*'
];

var jsFiles = [
    basePaths.npm + 'jquery/dist/jquery.js',
    basePaths.npm + 'fastclick/lib/*.js',
    module.slick + 'slick.js',
    'js/main.js'
]
/* ========================================================
 * Tasks with Browser Sync
 * ======================================================== */
gulp.task('browserSync', function() {

    var files = [
        '**/**/*.css',
        '**/**/*.scss',
        '**/**/*.php',
    ];

    browserSync.init(files, {
        proxy: "http://localhost:8888/hut.sctv.co.id/",
        notify: 'false'
    });
});

gulp.task('style', function() {
    return gulp.src(style.main)
        .pipe(plugins.plumber({
            errorHandler: function(err) {
                console.log(err);
                this.emit('end');
            }
        }))
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer())
        .pipe(plugins.sourcemaps.write())
        .pipe(plugins.rename('style.css'))
        .pipe(gulp.dest(basePaths.theme))
        .pipe(reload({ stream: true }));
});

gulp.task('js', function() {
    return gulp.src(jsFiles)
        .pipe(plugins.concat('main.js'))
        .pipe(gulp.dest(basePaths.theme))
        .pipe(reload({ stream: true }));
});

/* ========================================================
 * Utility Tasks
 * ======================================================== */

gulp.task('bootstrap', function() {

    var bootstrapStyle = gulp.src(module.bootstrap + 'stylesheets/**/**/*')
        .pipe(gulp.dest(style.vendor + 'bootstrap-plugins.sass'));

    return merge(bootstrapStyle);
});

gulp.task('font-awesome', function() {

    //move font awesome scss to our main plugins.sass folder
    var faStyle = gulp.src(module.fontawesome + 'scss/*')
        .pipe(gulp.dest(style.vendor + 'font-awesome'));

    //move font_awesome fonts to themes root folder
    var faFont = gulp.src(module.fontawesome + 'fonts/**/*')
        .pipe(gulp.dest(basePaths.root + 'fonts'));

    //merge tasks
    return merge(faStyle, faFont);

});

gulp.task('slicky', function() {

    // move slick fonts to the fonts under our themes folder
    var slickFont = gulp.src(module.slick + 'fonts/*')
        .pipe(gulp.dest('./fonts'));

    var slickStyle = gulp.src([
            module.slick + 'slick.scss',
            module.slick + 'slick-theme.scss'
        ])
        .pipe(gulp.dest(style.vendor + 'slick'));

    // move ajax loader to custom themes folder
    var slickAjaxLoader = gulp.src(module.slick + 'ajax-loader.gif')
        .pipe(gulp.dest(basePaths.root));

    //merge tasks
    return merge(slickFont, slickStyle, slickAjaxLoader);

});

gulp.task('utility', ['bootstrap', 'slicky', 'font-awesome']);

/* ========================================================
 * Default Tasks
 * ======================================================== */

gulp.task('default', ['style', 'js', 'browserSync'], function() {
    gulp.watch('*.scss', { cwd: path + '/sass' }, ['style']);
    gulp.watch('**/*.scss', { cwd: path + '/sass' }, ['style']);
    gulp.watch('*.js', { cwd: path + '/js' }, ['js']);
});

/* ========================================================
 * Production Tasks
 * ======================================================== */

gulp.task('prod-style', function() {
    return gulp.src(style.main)
        .pipe(plugins.plumber({
            errorHandler: function(err) {
                console.log(err);
                this.emit('end');
            }
        }))
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.sass({ outputStyle: 'compressed' }))
        .pipe(plugins.autoprefixer())
        .pipe(plugins.sourcemaps.write())
        .pipe(plugins.rename('style.css'))
        .pipe(gulp.dest(dist))
        .pipe(reload({ stream: true }));
});

gulp.task('prod-js', function() {
    return gulp.src(jsFiles)
        .pipe(plugins.concat('main.min.js'))
        .pipe(plugins.uglify())
        .pipe(gulp.dest(dist))
});

gulp.task('setup', function() {
    return gulp.src(filesToMove, { base: './' })
        .pipe(gulp.dest(dist))
})

gulp.task('dist', ['prod-style', 'prod-js', 'setup']);
<|endoftext|>


<commit_before>/* global describe, it */

import assert from 'assert';
import StdoutInterceptor from './lib/stdout_interceptor';
import { Logger } from '../src/';

function clean (str) {
  var s = str.toString().trim();
  return s.slice(s.indexOf(' ') + 1);
}

describe('Logger', () => {
  describe('#constructor', () => {
    it('should produce an instance of Logger', () => {
      let logger = new Logger();
      assert.ok(logger instanceof Logger);
    });
  });

  describe('#error', () => {
    it('should build an error message', () => {
      let logger = new Logger(),
          message = logger.error();

      message.text('Hello world');

      assert.equal(message.type, 'error');
      assert.equal(message.toString(), '\u001b[31m\u001b[1mHello world\u001b[22m\u001b[39m');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.error('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), '⨉ [TEST]: ERROR: Testing logger library');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.error('test')
        .action('Tested')
        .data('this')
        .send();

      ceptor.release();
      output = ceptor.toString();

      assert.equal(clean(output), '\u001b[31m\u001b[1m⨉\u001b[22m\u001b[39m \u001b[37m[\u001b[39m\u001b[36mTEST\u001b[39m\u001b[37m]:\u001b[39m \u001b[31m\u001b[1mERROR: Tested\u001b[22m\u001b[39m \u001b[35mthis\u001b[39m');
    });
  });

  describe('#start', () => {
    it('should build a start message', () => {
      let logger = new Logger(),
          message = logger.start();

      message.text('Hello world');

      assert.equal(message.type, 'start');
      assert.equal(message.toString(), 'Hello world');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.start('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), '» [TEST]: Testing logger library …');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.start('test')
        .action('Tested')
        .data('this')
        .send();

      ceptor.release();
      output = ceptor.toString();

      assert.equal(clean(output), '\u001b[32m\u001b[1m»\u001b[22m\u001b[39m \u001b[37m[\u001b[39m\u001b[36mTEST\u001b[39m\u001b[37m]:\u001b[39m Tested \u001b[35mthis\u001b[39m …');
    });
  });

  describe('#success', () => {
    it('should build a success message', () => {
      let logger = new Logger(),
          message = logger.success();

      message.text('Hello world');

      assert.equal(message.type, 'success');
      assert.equal(message.toString(), 'Hello world');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.success('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), '✓ [TEST]: Testing logger library');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.success('test')
        .action('Tested')
        .data('this')
        .send();
      ceptor.release();

      output = ceptor.toString();

      assert.equal(clean(output), '\u001b[32m\u001b[1m✓\u001b[22m\u001b[39m \u001b[37m[\u001b[39m\u001b[36mTEST\u001b[39m\u001b[37m]:\u001b[39m \u001b[32m\u001b[1mTested\u001b[22m\u001b[39m \u001b[35mthis\u001b[39m');
    });
  });

  describe('#task', () => {
    it('should build an action message', () => {
      let logger = new Logger(),
          message = logger.task();

      message.text('Hello world');

      assert.equal(message.type, 'action');
      assert.equal(message.toString(), 'Hello world');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.task('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), '• [TEST]: Testing logger library');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.task('test')
        .action('Tested')
        .data('this library')
        .text('again')
        .send();
      ceptor.release();

      output = ceptor.toString();

      assert.equal(clean(output), '\u001b[90m•\u001b[39m \u001b[37m[\u001b[39m\u001b[36mTEST\u001b[39m\u001b[37m]:\u001b[39m Tested \u001b[35mthis library\u001b[39m again');
    });
  });

  describe('#text', () => {
    it('should build a text message', () => {
      let logger = new Logger(),
          message = logger.text();

      message.text('Hello world');

      assert.equal(message.type, 'text');
      assert.equal(message.toString(), 'Hello world');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.text('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), 'test Testing logger library');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.text()
        .action('Tested')
        .data('this')
        .send();
      ceptor.release();

      output = ceptor.toString();

      assert.equal(clean(output), 'Tested \u001b[35mthis\u001b[39m');
    });
  });
});
<commit_msg>Fixed whitepsace in logger<commit_after>/* global describe, it */

import assert from 'assert';
import StdoutInterceptor from './lib/stdout_interceptor';
import { Logger } from '../src/';

function clean (str) {
  var s = str.toString().trim();
  return s.slice(s.indexOf(' ') + 1);
}

describe('Logger', () => {
  describe('#constructor', () => {
    it('should produce an instance of Logger', () => {
      let logger = new Logger();
      assert.ok(logger instanceof Logger);
    });
  });

  describe('#error', () => {
    it('should build an error message', () => {
      let logger = new Logger(),
          message = logger.error();

      message.text('Hello world');

      assert.equal(message.type, 'error');
      assert.equal(message.toString(), '\u001b[31m\u001b[1mHello world\u001b[22m\u001b[39m');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.error('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), '⨉ [TEST]: ERROR: Testing logger library');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.error('test')
        .action('Tested')
        .data('this')
        .send();

      ceptor.release();
      output = ceptor.toString();

      assert.equal(clean(output), '\u001b[31m\u001b[1m⨉\u001b[22m\u001b[39m \u001b[37m[\u001b[39m\u001b[36mTEST\u001b[39m\u001b[37m]:\u001b[39m \u001b[31m\u001b[1mERROR: Tested\u001b[22m\u001b[39m \u001b[35mthis\u001b[39m');
    });
  });

  describe('#start', () => {
    it('should build a start message', () => {
      let logger = new Logger(),
          message = logger.start();

      message.text('Hello world');

      assert.equal(message.type, 'start');
      assert.equal(message.toString(), 'Hello world');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.start('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), '» [TEST]: Testing logger library …');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.start('test')
        .action('Tested')
        .data('this')
        .send();

      ceptor.release();
      output = ceptor.toString();

      assert.equal(clean(output), '\u001b[32m\u001b[1m»\u001b[22m\u001b[39m \u001b[37m[\u001b[39m\u001b[36mTEST\u001b[39m\u001b[37m]:\u001b[39m Tested \u001b[35mthis\u001b[39m …');
    });
  });

  describe('#success', () => {
    it('should build a success message', () => {
      let logger = new Logger(),
          message = logger.success();

      message.text('Hello world');

      assert.equal(message.type, 'success');
      assert.equal(message.toString(), 'Hello world');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.success('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), '✓ [TEST]: Testing logger library');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.success('test')
        .action('Tested')
        .data('this')
        .send();
      ceptor.release();

      output = ceptor.toString();

      assert.equal(clean(output), '\u001b[32m\u001b[1m✓\u001b[22m\u001b[39m \u001b[37m[\u001b[39m\u001b[36mTEST\u001b[39m\u001b[37m]:\u001b[39m \u001b[32m\u001b[1mTested\u001b[22m\u001b[39m \u001b[35mthis\u001b[39m');
    });
  });

  describe('#task', () => {
    it('should build an action message', () => {
      let logger = new Logger(),
          message = logger.task();

      message.text('Hello world');

      assert.equal(message.type, 'action');
      assert.equal(message.toString(), 'Hello world');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.task('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), '• [TEST]: Testing logger library');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.task('test')
        .action('Tested')
        .data('this library')
        .text('again')
        .send();
      ceptor.release();

      output = ceptor.toString();

      assert.equal(clean(output), '\u001b[90m•\u001b[39m \u001b[37m[\u001b[39m\u001b[36mTEST\u001b[39m\u001b[37m]:\u001b[39m Tested \u001b[35mthis library\u001b[39m again');
    });
  });

  describe('#text', () => {
    it('should build a text message', () => {
      let logger = new Logger(),
          message = logger.text();

      message.text('Hello world');

      assert.equal(message.type, 'text');
      assert.equal(message.toString(), 'Hello world');
    });

    it('should support sending immediately', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.text('test', 'Testing logger library');
      output = ceptor.release();

      assert.equal(clean(output), 'test Testing logger library');
    });

    it('should support colored formatting', () => {
      let logger = new Logger(),
          ceptor = new StdoutInterceptor(),
          output;

      ceptor.capture();
      logger.text()
        .action('Tested')
        .data('this')
        .send();
      ceptor.release();

      output = ceptor.toString();

      assert.equal(clean(output), 'Tested \u001b[35mthis\u001b[39m');
    });
  });
});
<|endoftext|>


<commit_before>import addons from '@storybook/addons';
import { STORY_EVENT_ID } from './events';

const getLocation = (context, locationsMap) => locationsMap[context.id];

function sendEvent(
  context,
  source,
  locationsMap,
  mainFileLocation,
  dependencies,
  localDependencies,
  prefix,
  idsToFrameworks
) {
  const channel = addons.getChannel();
  const currentLocation = getLocation(context, locationsMap);

  channel.emit(STORY_EVENT_ID, {
    edition: {
      source,
      mainFileLocation,
      dependencies,
      localDependencies,
      prefix,
      idsToFrameworks,
    },
    story: {
      kind: context.kind,
      story: context.story,
    },
    location: {
      currentLocation,
      locationsMap,
    },
  });
}

export function addSource(storyFn, sourceContext) {
  const {
    __STORY__: source,
    __ADDS_MAP__: locationsMap = {},
    __MAIN_FILE_LOCATION__: mainFileLocation = '/index.js',
    __MODULE_DEPENDENCIES__: dependencies = [],
    __LOCAL_DEPENDENCIES__: localDependencies = {},
    __SOURCE_PREFIX__: prefix,
    __IDS_TO_FRAMEWORKS__: idsToFrameworks,
  } = sourceContext;
  const decorated = context => {
    sendEvent(
      context,
      source,
      locationsMap,
      mainFileLocation,
      dependencies,
      localDependencies,
      prefix,
      idsToFrameworks
    );
    if (typeof storyFn === 'function') {
      return storyFn(context);
    }
    return storyFn;
  };
  decorated.story = (storyFn || {}).story;
  return decorated;
}

export function withSource(
  source,
  locationsMap = {},
  mainFileLocation = '/index.js',
  dependencies = [],
  localDependencies = {},
  prefix,
  idsToFrameworks
) {
  return (storyFn, context) => {
    sendEvent(
      context,
      source,
      locationsMap,
      mainFileLocation,
      dependencies,
      localDependencies,
      prefix,
      idsToFrameworks
    );
    return storyFn(context);
  };
}
<commit_msg>Fix addSource decoration for no-context invocations<commit_after>import addons from '@storybook/addons';
import { STORY_EVENT_ID } from './events';

const getLocation = (context, locationsMap) => locationsMap[context.id];

function sendEvent(
  context,
  source,
  locationsMap,
  mainFileLocation,
  dependencies,
  localDependencies,
  prefix,
  idsToFrameworks
) {
  const channel = addons.getChannel();
  const currentLocation = getLocation(context, locationsMap);

  channel.emit(STORY_EVENT_ID, {
    edition: {
      source,
      mainFileLocation,
      dependencies,
      localDependencies,
      prefix,
      idsToFrameworks,
    },
    story: {
      kind: context.kind,
      story: context.story,
    },
    location: {
      currentLocation,
      locationsMap,
    },
  });
}

export function addSource(storyFn, sourceContext) {
  const {
    __STORY__: source,
    __ADDS_MAP__: locationsMap = {},
    __MAIN_FILE_LOCATION__: mainFileLocation = '/index.js',
    __MODULE_DEPENDENCIES__: dependencies = [],
    __LOCAL_DEPENDENCIES__: localDependencies = {},
    __SOURCE_PREFIX__: prefix,
    __IDS_TO_FRAMEWORKS__: idsToFrameworks,
  } = sourceContext;
  const decorated = (context = {}) => {
    sendEvent(
      context,
      source,
      locationsMap,
      mainFileLocation,
      dependencies,
      localDependencies,
      prefix,
      idsToFrameworks
    );
    if (typeof storyFn === 'function') {
      return storyFn(context);
    }
    return storyFn;
  };
  decorated.story = (storyFn || {}).story;
  return decorated;
}

export function withSource(
  source,
  locationsMap = {},
  mainFileLocation = '/index.js',
  dependencies = [],
  localDependencies = {},
  prefix,
  idsToFrameworks
) {
  return (storyFn, context) => {
    sendEvent(
      context,
      source,
      locationsMap,
      mainFileLocation,
      dependencies,
      localDependencies,
      prefix,
      idsToFrameworks
    );
    return storyFn(context);
  };
}
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict';

require('should');
const Winston = require('winston');

class ConfigLike {
  constructor(data) {
    this.data = data;
  }

  get(str) {
    return this.data[str];
  }
}

describe('Logging', () => {
  const config = new ConfigLike({
    'log:level': 'info',
    'log:access:level': 'verbose'
  });
  const log = require('../lib/logger').attach(config.get('log:level'));

  it('returns a WINSTON object', () => {
    log.should.be.an.instanceOf(Winston.Logger);
  });

  it('sets the log level correctly', () => {
    log.level.should.be.exactly('info');
  });
});
<commit_msg>PD-7063 fixed typo with config declaration<commit_after>/* eslint-env mocha */
'use strict';

require('should');
const Winston = require('winston');

class ConfigLike {
  constructor(data) {
    this.data = data;
  }

  get(str) {
    return this.data[str];
  }
}

describe('Logging', () => {
  const config = new ConfigLike({
    'log:level': 'info'
  });
  const log = require('../lib/logger').attach(config.get('log:level'));

  it('returns a WINSTON object', () => {
    log.should.be.an.instanceOf(Winston.Logger);
  });

  it('sets the log level correctly', () => {
    log.level.should.be.exactly('info');
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var mkdirp = require('../').mkdirp;
var path = require('path');
var fs = require('fs');

exports.woo = function () {
    var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
    var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
    var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);

    var file = '/tmp/' + [x,y,z].join('/');

    mkdirp(file, 0755, function (err) {
        if (err) assert.fail(err);
        else path.exists(file, function (ex) {
            if (!ex) assert.fail('file not created')
            else fs.stat(file, function (err, stat) {
                if (err) assert.fail(err)
                else {
                    assert.eql(stat.mode & 0777, 0755);
                    assert.ok(stat.isDirectory(), 'target not a directory');
                }
            })
        })
    });
};
<commit_msg>never called back failing test<commit_after>var assert = require('assert');
var mkdirp = require('../').mkdirp;
var path = require('path');
var fs = require('fs');

exports.woo = function () {
    var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
    var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
    var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);

    var file = '/tmp/' + [x,y,z].join('/');
    var to = setTimeout(function () {
        assert.fail('never called back');
    }, 1000);

    mkdirp(file, 0755, function (err) {
        if (err) assert.fail(err);
        else path.exists(file, function (ex) {
            if (!ex) assert.fail('file not created')
            else fs.stat(file, function (err, stat) {
                if (err) assert.fail(err)
                else {
                    clearTimeout(to);
                    assert.eql(stat.mode & 0777, 0755);
                    assert.ok(stat.isDirectory(), 'target not a directory');
                }
            })
        })
    });
};
<|endoftext|>


<commit_before>var dotenv = require('dotenv');
dotenv.load();

var chai = require('chai');
var should = chai.should();
var db = require('../models');
var sequelize = db.sequelize;

describe('Opportunity Model', function() {

  it('should create a new opportunity without optional fields', function(done) {
    var body = { _csrf: 'undefined', _doc_id: '', title: 'Test opp3', purpose: 'anything', 'purpose-other': '', eligibleBusinessLocation: 'anywhere_in_pr', 'eligibleBusinessLocation-other': '', paperworkRequired: 'asdfasd', applicationCost: '23', applicationDeadline: '2014-12-31', avgApplicationTime: '90 days', benefitType: 'incentive', 'benefitType-other': '', benefitDescription: 'Una descripcion', agencyName: 'Una gencia', agencyContactName: 'Un contacto', agencyContactEmail: 'unemail', agencyContactPhone: '7875663317', minimumYearsInBusiness: '0', eligibleEntityTypes: 'non_profit', currentEmployeesRequired: '26_50', annualRevenue: '0_99999', eligibleIndustries: [ 'any', '' ], gender: 'any', age: '0', additionalGeneralInformation: '', moneyInvested: '' }
    var Opportunity = sequelize.model('opportunity');
    var instance = Opportunity.buildFromAdminForm(body);
    instance.validate().
    success(function(err) {
      if (err) {
        done(err);
      }
      instance.save().success(function(){
        done();
      })
      .error(function(err) {
        done(err);
      });
    });
  });

  it('should create a new opportunity with optional fields', function(done) {
    // purpose other is filled out, additionalGeneralInformation is filled out
    var body = { _csrf: 'undefined', _doc_id: '', title: 'Test opp3', purpose: 'Other', 'purpose-other': 'A different purpose', eligibleBusinessLocation: 'anywhere_in_pr', 'eligibleBusinessLocation-other': '', paperworkRequired: 'asdfasd', applicationCost: '23', applicationDeadline: '2014-12-31', avgApplicationTime: '90 days', benefitType: 'incentive', 'benefitType-other': '', benefitDescription: 'Una descripcion', agencyName: 'Una gencia', agencyContactName: 'Un contacto', agencyContactEmail: 'unemail', agencyContactPhone: '7875663317', minimumYearsInBusiness: '0', eligibleEntityTypes: 'non_profit', currentEmployeesRequired: '26_50', annualRevenue: '0_99999', eligibleIndustries: [ 'any', '' ], gender: 'any', age: '0', additionalGeneralInformation: 'Some other general information', moneyInvested: '' }
    var Opportunity = sequelize.model('opportunity');
    var instance = Opportunity.buildFromAdminForm(body);
    instance.validate().
    success(function(err) {
      if (err) {
        done(err);
      }
      instance.save().success(function(){
        done();
      })
      .error(function(err) {
        done(err);
      });
    });
  });

  it('should throw an error!', function(done) {
    // applicationCost is missing
    var body = { _csrf: 'undefined', _doc_id: '', title: 'Test opp3', purpose: 'Other', 'purpose-other': 'A different purpose', eligibleBusinessLocation: 'anywhere_in_pr', 'eligibleBusinessLocation-other': '', paperworkRequired: 'asdfasd', applicationCost: '', applicationDeadline: '2014-12-31', avgApplicationTime: '90 days', benefitType: 'incentive', 'benefitType-other': '', benefitDescription: 'Una descripcion', agencyName: 'Una gencia', agencyContactName: 'Un contacto', agencyContactEmail: 'unemail', agencyContactPhone: '7875663317', minimumYearsInBusiness: '0', eligibleEntityTypes: 'non_profit', currentEmployeesRequired: '26_50', annualRevenue: '0_99999', eligibleIndustries: [ 'any', '' ], gender: 'any', age: '0', additionalGeneralInformation: 'Some other general information', moneyInvested: '' }
    var Opportunity = sequelize.model('opportunity');
    var instance = Opportunity.buildFromAdminForm(body);
    instance.validate().
    success(function(err) {
      if (err) {
        should.exist(err);
        done();
      }
    });
  });

  after(function(done) {
    var Opportunity = sequelize.model('opportunity');
    Opportunity.destroy({title: 'Test opp3'}).success(function(rows) {
      done();
    });
  });
});
<commit_msg>Added 'other' field tests<commit_after>var dotenv = require('dotenv');
dotenv.load();

var chai = require('chai');
var should = chai.should();
var db = require('../models');
var sequelize = db.sequelize;

describe('Opportunity Model', function() {

  it('should create a new opportunity without optional fields', function(done) {
    var body = { _csrf: 'undefined', _doc_id: '', title: 'Test opp3', purpose: 'anything', 'purpose-other': '', eligibleBusinessLocation: 'anywhere_in_pr', 'eligibleBusinessLocation-other': '', paperworkRequired: 'asdfasd', applicationCost: '23', applicationDeadline: '2014-12-31', avgApplicationTime: '90 days', benefitType: 'incentive', 'benefitType-other': '', benefitDescription: 'Una descripcion', agencyName: 'Una gencia', agencyContactName: 'Un contacto', agencyContactEmail: 'unemail', agencyContactPhone: '7875663317', minimumYearsInBusiness: '0', eligibleEntityTypes: 'non_profit', currentEmployeesRequired: '26_50', annualRevenue: '0_99999', eligibleIndustries: [ 'any', '' ], gender: 'any', age: '0', additionalGeneralInformation: '', moneyInvested: '' }
    var Opportunity = sequelize.model('opportunity');
    var instance = Opportunity.buildFromAdminForm(body);
    instance.validate().
    success(function(err) {
      if (err) {
        done(err);
      }
      instance.save().success(function(){
        done();
      })
      .error(function(err) {
        done(err);
      });
    });
  });

  it('should create a new opportunity with optional fields', function(done) {
    // purpose other is filled out, additionalGeneralInformation is filled out
    var body = { _csrf: 'undefined', _doc_id: '', title: 'Test opp3', purpose: 'Other', 'purpose-other': 'A different purpose', eligibleBusinessLocation: 'anywhere_in_pr', 'eligibleBusinessLocation-other': '', paperworkRequired: 'asdfasd', applicationCost: '23', applicationDeadline: '2014-12-31', avgApplicationTime: '90 days', benefitType: 'incentive', 'benefitType-other': '', benefitDescription: 'Una descripcion', agencyName: 'Una gencia', agencyContactName: 'Un contacto', agencyContactEmail: 'unemail', agencyContactPhone: '7875663317', minimumYearsInBusiness: '0', eligibleEntityTypes: 'non_profit', currentEmployeesRequired: '26_50', annualRevenue: '0_99999', eligibleIndustries: [ 'any', '' ], gender: 'any', age: '0', additionalGeneralInformation: 'Some other general information', moneyInvested: '' }
    var Opportunity = sequelize.model('opportunity');
    var instance = Opportunity.buildFromAdminForm(body);
    instance.validate().
    success(function(err) {
      if (err) {
        done(err);
      }
      instance.save().success(function(){
        done();
      })
      .error(function(err) {
        done(err);
      });
    });
  });

  it('should throw an error if a required field is missing', function(done) {
    // applicationCost is missing
    var body = { _csrf: 'undefined', _doc_id: '', title: 'Test opp3', purpose: 'Other', 'purpose-other': 'A different purpose', eligibleBusinessLocation: 'anywhere_in_pr', 'eligibleBusinessLocation-other': '', paperworkRequired: 'asdfasd', applicationCost: '', applicationDeadline: '2014-12-31', avgApplicationTime: '90 days', benefitType: 'incentive', 'benefitType-other': '', benefitDescription: 'Una descripcion', agencyName: 'Una gencia', agencyContactName: 'Un contacto', agencyContactEmail: 'unemail', agencyContactPhone: '7875663317', minimumYearsInBusiness: '0', eligibleEntityTypes: 'non_profit', currentEmployeesRequired: '26_50', annualRevenue: '0_99999', eligibleIndustries: [ 'any', '' ], gender: 'any', age: '0', additionalGeneralInformation: 'Some other general information', moneyInvested: '' }
    var Opportunity = sequelize.model('opportunity');
    var instance = Opportunity.buildFromAdminForm(body);
    instance.validate().
    success(function(err) {
      if (err) {
        should.exist(err);
        done();
      }
    });
  });

  it('should correctly parse and save "other" text fields', function(done) {
    // purpose other is filled out, additionalGeneralInformation is filled out
    var body = { _csrf: 'undefined', _doc_id: '', title: 'Test opp3', purpose: 'other', 'purpose-other': 'A different purpose', eligibleBusinessLocation: 'anywhere_in_pr', 'eligibleBusinessLocation-other': '', paperworkRequired: 'asdfasd', applicationCost: '23', applicationDeadline: '2014-12-31', avgApplicationTime: '90 days', benefitType: 'incentive', 'benefitType-other': '', benefitDescription: 'Una descripcion', agencyName: 'Una gencia', agencyContactName: 'Un contacto', agencyContactEmail: 'unemail', agencyContactPhone: '7875663317', minimumYearsInBusiness: '0', eligibleEntityTypes: 'non_profit', currentEmployeesRequired: '26_50', annualRevenue: '0_99999', eligibleIndustries: [ 'any', ], gender: 'any', age: '0', additionalGeneralInformation: 'Some other general information', moneyInvested: '' }
    var Opportunity = sequelize.model('opportunity');
    var instance = Opportunity.buildFromAdminForm(body);
    instance.validate().
    success(function(err) {
      if (err) {
        done(err);
      }
      instance.save().success(function(){
        Opportunity.find({where: {title: 'Test opp3'} }).success(function(op) {
          op.purpose.should.equal('_a_different_purpose');
          done();
        });
      })
      .error(function(err) {
        done(err);
      });
    });
  });

  it('should correctly save "other" checkbox fields', function(done) {
    // purpose other is filled out, additionalGeneralInformation is filled out
    var body = { _csrf: 'undefined', _doc_id: '', title: 'Test opp3', purpose: 'other', 'purpose-other': 'A different purpose', eligibleBusinessLocation: 'anywhere_in_pr', 'eligibleBusinessLocation-other': '', paperworkRequired: 'asdfasd', applicationCost: '23', applicationDeadline: '2014-12-31', avgApplicationTime: '90 days', benefitType: 'incentive', 'benefitType-other': '', benefitDescription: 'Una descripcion', agencyName: 'Una gencia', agencyContactName: 'Un contacto', agencyContactEmail: 'unemail', agencyContactPhone: '7875663317', minimumYearsInBusiness: '0', eligibleEntityTypes: 'non_profit', currentEmployeesRequired: '26_50', annualRevenue: '0_99999', eligibleIndustries: [ 'any', 'other', 'Otro Distinto' ], gender: 'any', age: '0', additionalGeneralInformation: 'Some other general information', moneyInvested: '' }
    var Opportunity = sequelize.model('opportunity');
    var instance = Opportunity.buildFromAdminForm(body);
    instance.validate().
    success(function(err) {
      if (err) {
        done(err);
      }
      instance.save().success(function(){
        Opportunity.find({where: {title: 'Test opp3'} }).success(function(op) {
          op.eligibleIndustries.should.include('Otro Distinto');
          done();
        });
      })
      .error(function(err) {
        done(err);
      });
    });
  });

  afterEach(function(done) {
    var Opportunity = sequelize.model('opportunity');
    Opportunity.destroy({title: 'Test opp3'}).success(function(rows) {
      done();
    });
  });
});
<|endoftext|>