<commit_before>/* global describe, it, beforeEach, afterEach */
'use strict';

var should = require('chai').should(); // eslint-disable-line no-unused-vars
var fs = require('fs');
var path = require('path');
var temp = require('temp').track();
var watch = require('../index.js');

describe('watch', function() {
    var tempDir;
    var watchers = [];

    beforeEach(function(done) {
        tempDir = temp.mkdirSync('gulp-sane-watch');
        done();
    });

    afterEach(function(done) {
        watchers.forEach(function(watcher) {
            watcher.close();
        });

        temp.cleanupSync();
        done();
    });

    function once(done) {
        var f = function() {
            if (!f.called) {
                f.called = true;
                done();
            }
        };

        return f;
    }

    function allReady(watchers, cb) {
        var total = watchers.length;

        var makeReadyHandler = function() {
            total--;
            if (total === 0) {
                cb();
            }
        };

        for (var i = 0, l = total; i < l; i++) {
            watchers[i].on('ready', makeReadyHandler);
        }
    }

    it('should detect file creation', function(done) {
        done = once(done);

        var tempFile = path.join(tempDir, 'test.txt');
        var glob = path.join(tempDir, '*.txt');
        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'created');
        });
    });

    it('should detect file change', function(done) {
        done = once(done);

        var tempFile = path.join(tempDir, 'test.txt');
        fs.writeFileSync(tempFile, 'created');
        var glob = path.join(tempDir, '*.txt');
        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'changed');
        });
    });

    it('should detect file move', function(done) {
        done = once(done);

        var tempFile = path.join(tempDir, 'test.txt');
        var tempDir2 = temp.mkdirSync('gulp-sane-watch-2');
        var tempFile2 = path.join(tempDir2, 'test.txt');
        fs.writeFileSync(tempFile2, 'created');
        var glob = path.join(tempDir, '*.txt');
        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.renameSync(tempFile2, tempFile);
        });
    });

    // it('should detect moved directories', function(done) {
    //     done = once(done);

    //     var tempSubDir = path.join(tempDir, 'subdir');
    //     var tempDir2 = temp.mkdirSync('gulp-sane-watch-2');
    //     var tempFile2 = path.join(tempDir2, 'test.txt');
    //     fs.writeFileSync(tempFile2, 'created');
    //     var glob = path.join(tempDir, '**', '*.txt');
    //     watchers = watch(glob, {verbose: false}, function(filename, dir) {
    //         var full = path.join(dir, filename);
    //         full.should.equal(tempSubDir);
    //         done();
    //     });

    //     allReady(watchers, function() {
    //         fs.renameSync(tempDir2, tempSubDir);
    //     });
    // });

    it('should detect deleted directories', function(done) {
        done = once(done);

        var tempSubDir = path.join(tempDir, 'subdir');
        var tempFile = path.join(tempSubDir, 'test.txt');
        var tempDir2 = temp.mkdirSync('gulp-sane-watch-2');
        var tempSubDir2 = path.join(tempDir2, 'subdir');
        fs.mkdirSync(tempSubDir);
        fs.writeFileSync(tempFile, 'created');
        var glob = path.join(tempDir, '**', '*.txt');
        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(path.join(tempFile));
            done();
        });

        allReady(watchers, function() {
            fs.renameSync(tempSubDir, tempSubDir2);
        });
    });

    it('should debounce callback', function(done) {
        var calledCount = 0;
        var helper = function() {
            calledCount++;
        };

        var tempFile = path.join(tempDir, 'test.txt');
        var glob = path.join(tempDir, '*.txt');
        watchers = watch(glob, {verbose: false, debounce: 300}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(tempFile);
            helper();
        });

        this.timeout(0);

        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'created');
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'changed 1');
            }, 100);
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'changed 2');
            }, 200);
            setTimeout(function() {
                calledCount.should.equal(1);
                done();
            }, 1000);
        });
    });

    it('should debounce events', function(done) {
        var calledCount = {
            changed: 0,
            added: 0,
            deleted: 0
        };
        var helper = function(event) {
            calledCount[event]++;
        };

        var tempFile = path.join(tempDir, 'test.txt');
        var glob = path.join(tempDir, '*.txt');

        watchers = watch(glob, {
            verbose: false,
            debounce: 300,
            onAdd: function(filename, dir) {
                var full = path.join(dir, filename);
                full.should.equal(tempFile);
                helper('added');
            },
            onChange: function(filename, dir) {
                var full = path.join(dir, filename);
                full.should.equal(tempFile);
                helper('changed');
            },
            onDelete: function(filename, dir) {
                var full = path.join(dir, filename);
                full.should.equal(tempFile);
                helper('deleted');
            }
        });

        this.timeout(0);

        allReady(watchers, function() {
            var timeout = 1000;

            fs.writeFileSync(tempFile, 'created');
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'changed 1');
            }, 100);
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'changed 2');
            }, 200);

            setTimeout(function() {
                calledCount.changed.should.equal(1);
                calledCount.added.should.equal(1);
                fs.unlinkSync(tempFile);
                setTimeout(function() {
                    calledCount.deleted.should.equal(1);
                    done();
                }, 1000);
            }, timeout);
        });
    });

    it('should support multiple globs', function(done) {
        var tempFile1 = path.join(tempDir, 'test.txt');
        var tempFile2 = path.join(tempDir, 'test.tst');
        var glob1 = path.join(tempDir, '*.txt');
        var glob2 = path.join(tempDir, '*.tst');

        var changed = {};
        changed[tempFile1] = false;
        changed[tempFile2] = false;

        fs.writeFileSync(tempFile1, 'created');

        watchers = watch([glob1, glob2], {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            changed[full] = true;
        });

        this.timeout(0);
        allReady(watchers, function() {
            fs.writeFileSync(tempFile1, 'changed');
            fs.writeFileSync(tempFile2, 'created');

            setTimeout(function() {
                changed[tempFile1].should.equal(true);
                changed[tempFile2].should.equal(true);
                done();
            }, 1000);
        });
    });

    it('should support subdirectories', function(done) {
        done = once(done);

        var tempDir2 = path.join(tempDir, 'subdir');
        var tempFile = path.join(tempDir2, 'subtest.txt');
        var glob = path.join(tempDir, '**', '*.txt');

        fs.mkdirSync(tempDir2);

        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            if (full === tempDir2) {
                return;
            }

            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'created');
        });
    });

    it('should support newly created subdirectories', function(done) {
        done = once(done);

        var tempDir2 = path.join(tempDir, 'subdir');
        var tempFile = path.join(tempDir2, 'subtest.txt');
        var glob = path.join(tempDir, '**', '*.txt');

        watchers = watch(glob, {verbose: false}, function(filename, dir, stat) {
            var full = path.join(dir, filename);
            if (stat && stat.isDirectory()) {
                return;
            }

            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.mkdirSync(tempDir2);
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'created');
            }, 400);
        });
    });

    it('should support separate callbacks', function(done) {
        done = once(done);

        var tempDir2 = path.join(tempDir, 'subdir');
        var globs1 = [
            path.join(tempDir, '**', '*.txt'),
            path.join(tempDir, '**', '*.tst')
        ];
        var globs2 = [
            path.join(tempDir, '**', '*.css'),
            path.join(tempDir, '**', '*.js')
        ];

        var tempFile1 = path.join(tempDir, 'test.txt');
        var tempFile2 = path.join(tempDir2, 'test.tst');
        var tempFile3 = path.join(tempDir, 'test.js');
        var tempFile4 = path.join(tempDir2, 'test.css');

        var files1 = {};
        var files2 = {};
        files1[tempFile1] = false;
        files1[tempFile2] = false;
        files2[tempFile3] = false;
        files2[tempFile4] = false;

        var watchers1 = watch(globs1, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            if (typeof files1[full] === 'undefined') {
                return;
            }

            files1[full] = true;
        });

        var watchers2 = watch(globs2, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            if (typeof files2[full] === 'undefined') {
                return;
            }

            files2[full] = true;
        });

        watchers = watchers1.concat(watchers2);

        this.timeout(0);
        allReady(watchers, function() {
            fs.mkdirSync(tempDir2);
            setTimeout(function() {
                var file;
                for (file in files1) {
                    fs.writeFileSync(file, 'created');
                }

                for (file in files2) {
                    fs.writeFileSync(file, 'created');
                }

                setTimeout(function() {
                    var file;
                    for (file in files1) {
                        files1[file].should.equal(true);
                    }

                    for (file in files2) {
                        files2[file].should.equal(true);
                    }

                    done();
                }, 1000);
            }, 400);
        });
    });

    it('should properly find files by extension', function(done) {
        done = once(done);

        var tempFile = path.join(tempDir, 'test.txt~.part');
        var glob = path.join(tempDir, '*.txt');

        var calledCount = 0;
        watchers = watch(glob, {verbose: false}, function() {
            calledCount++;
        });

        this.timeout(0);
        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'created');
            setTimeout(function() {
                calledCount.should.equal(0);
                done();
            }, 1000);
        });
    });
});
<commit_msg>Fix test<commit_after>/* global describe, it, beforeEach, afterEach */
'use strict';

var should = require('chai').should(); // eslint-disable-line no-unused-vars
var fs = require('fs');
var path = require('path');
var temp = require('temp').track();
var watch = require('../index.js');

describe('watch', function() {
    var tempDir;
    var watchers = [];

    beforeEach(function(done) {
        tempDir = temp.mkdirSync('gulp-sane-watch');
        done();
    });

    afterEach(function(done) {
        watchers.forEach(function(watcher) {
            watcher.close();
        });

        temp.cleanupSync();
        done();
    });

    function once(done) {
        var f = function() {
            if (!f.called) {
                f.called = true;
                done();
            }
        };

        return f;
    }

    function allReady(watchers, cb) {
        var total = watchers.length;

        var makeReadyHandler = function() {
            total--;
            if (total === 0) {
                cb();
            }
        };

        for (var i = 0, l = total; i < l; i++) {
            watchers[i].on('ready', makeReadyHandler);
        }
    }

    it('should detect file creation', function(done) {
        done = once(done);

        var tempFile = path.join(tempDir, 'test.txt');
        var glob = path.join(tempDir, '*.txt');
        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'created');
        });
    });

    it('should detect file change', function(done) {
        done = once(done);

        var tempFile = path.join(tempDir, 'test.txt');
        fs.writeFileSync(tempFile, 'created');
        var glob = path.join(tempDir, '*.txt');
        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'changed');
        });
    });

    it('should detect file move', function(done) {
        done = once(done);

        var tempFile = path.join(tempDir, 'test.txt');
        var tempDir2 = temp.mkdirSync('gulp-sane-watch-2');
        var tempFile2 = path.join(tempDir2, 'test.txt');
        fs.writeFileSync(tempFile2, 'created');
        var glob = path.join(tempDir, '*.txt');
        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.renameSync(tempFile2, tempFile);
        });
    });

    // it('should detect moved directories', function(done) {
    //     done = once(done);

    //     var tempSubDir = path.join(tempDir, 'subdir');
    //     var tempDir2 = temp.mkdirSync('gulp-sane-watch-2');
    //     var tempFile2 = path.join(tempDir2, 'test.txt');
    //     fs.writeFileSync(tempFile2, 'created');
    //     var glob = path.join(tempDir, '**', '*.txt');
    //     watchers = watch(glob, {verbose: false}, function(filename, dir) {
    //         var full = path.join(dir, filename);
    //         full.should.equal(tempSubDir);
    //         done();
    //     });

    //     allReady(watchers, function() {
    //         fs.renameSync(tempDir2, tempSubDir);
    //     });
    // });

    it('should detect deleted directories', function(done) {
        done = once(done);

        var tempSubDir = path.join(tempDir, 'subdir');
        var tempFile = path.join(tempSubDir, 'test.txt');
        var tempDir2 = temp.mkdirSync('gulp-sane-watch-2');
        var tempSubDir2 = path.join(tempDir2, 'subdir');
        fs.mkdirSync(tempSubDir);
        fs.writeFileSync(tempFile, 'created');
        var glob = path.join(tempDir, '**', '*.txt');
        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.contain(path.join(tempSubDir));
            done();
        });

        allReady(watchers, function() {
            fs.renameSync(tempSubDir, tempSubDir2);
        });
    });

    it('should debounce callback', function(done) {
        var calledCount = 0;
        var helper = function() {
            calledCount++;
        };

        var tempFile = path.join(tempDir, 'test.txt');
        var glob = path.join(tempDir, '*.txt');
        watchers = watch(glob, {verbose: false, debounce: 300}, function(filename, dir) {
            var full = path.join(dir, filename);
            full.should.equal(tempFile);
            helper();
        });

        this.timeout(0);

        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'created');
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'changed 1');
            }, 100);
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'changed 2');
            }, 200);
            setTimeout(function() {
                calledCount.should.equal(1);
                done();
            }, 1000);
        });
    });

    it('should debounce events', function(done) {
        var calledCount = {
            changed: 0,
            added: 0,
            deleted: 0
        };
        var helper = function(event) {
            calledCount[event]++;
        };

        var tempFile = path.join(tempDir, 'test.txt');
        var glob = path.join(tempDir, '*.txt');

        watchers = watch(glob, {
            verbose: false,
            debounce: 300,
            onAdd: function(filename, dir) {
                var full = path.join(dir, filename);
                full.should.equal(tempFile);
                helper('added');
            },
            onChange: function(filename, dir) {
                var full = path.join(dir, filename);
                full.should.equal(tempFile);
                helper('changed');
            },
            onDelete: function(filename, dir) {
                var full = path.join(dir, filename);
                full.should.equal(tempFile);
                helper('deleted');
            }
        });

        this.timeout(0);

        allReady(watchers, function() {
            var timeout = 1000;

            fs.writeFileSync(tempFile, 'created');
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'changed 1');
            }, 100);
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'changed 2');
            }, 200);

            setTimeout(function() {
                calledCount.changed.should.equal(1);
                calledCount.added.should.equal(1);
                fs.unlinkSync(tempFile);
                setTimeout(function() {
                    calledCount.deleted.should.equal(1);
                    done();
                }, 1000);
            }, timeout);
        });
    });

    it('should support multiple globs', function(done) {
        var tempFile1 = path.join(tempDir, 'test.txt');
        var tempFile2 = path.join(tempDir, 'test.tst');
        var glob1 = path.join(tempDir, '*.txt');
        var glob2 = path.join(tempDir, '*.tst');

        var changed = {};
        changed[tempFile1] = false;
        changed[tempFile2] = false;

        fs.writeFileSync(tempFile1, 'created');

        watchers = watch([glob1, glob2], {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            changed[full] = true;
        });

        this.timeout(0);
        allReady(watchers, function() {
            fs.writeFileSync(tempFile1, 'changed');
            fs.writeFileSync(tempFile2, 'created');

            setTimeout(function() {
                changed[tempFile1].should.equal(true);
                changed[tempFile2].should.equal(true);
                done();
            }, 1000);
        });
    });

    it('should support subdirectories', function(done) {
        done = once(done);

        var tempDir2 = path.join(tempDir, 'subdir');
        var tempFile = path.join(tempDir2, 'subtest.txt');
        var glob = path.join(tempDir, '**', '*.txt');

        fs.mkdirSync(tempDir2);

        watchers = watch(glob, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            if (full === tempDir2) {
                return;
            }

            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'created');
        });
    });

    it('should support newly created subdirectories', function(done) {
        done = once(done);

        var tempDir2 = path.join(tempDir, 'subdir');
        var tempFile = path.join(tempDir2, 'subtest.txt');
        var glob = path.join(tempDir, '**', '*.txt');

        watchers = watch(glob, {verbose: false}, function(filename, dir, stat) {
            var full = path.join(dir, filename);
            if (stat && stat.isDirectory()) {
                return;
            }

            full.should.equal(tempFile);
            done();
        });

        allReady(watchers, function() {
            fs.mkdirSync(tempDir2);
            setTimeout(function() {
                fs.writeFileSync(tempFile, 'created');
            }, 400);
        });
    });

    it('should support separate callbacks', function(done) {
        done = once(done);

        var tempDir2 = path.join(tempDir, 'subdir');
        var globs1 = [
            path.join(tempDir, '**', '*.txt'),
            path.join(tempDir, '**', '*.tst')
        ];
        var globs2 = [
            path.join(tempDir, '**', '*.css'),
            path.join(tempDir, '**', '*.js')
        ];

        var tempFile1 = path.join(tempDir, 'test.txt');
        var tempFile2 = path.join(tempDir2, 'test.tst');
        var tempFile3 = path.join(tempDir, 'test.js');
        var tempFile4 = path.join(tempDir2, 'test.css');

        var files1 = {};
        var files2 = {};
        files1[tempFile1] = false;
        files1[tempFile2] = false;
        files2[tempFile3] = false;
        files2[tempFile4] = false;

        var watchers1 = watch(globs1, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            if (typeof files1[full] === 'undefined') {
                return;
            }

            files1[full] = true;
        });

        var watchers2 = watch(globs2, {verbose: false}, function(filename, dir) {
            var full = path.join(dir, filename);
            if (typeof files2[full] === 'undefined') {
                return;
            }

            files2[full] = true;
        });

        watchers = watchers1.concat(watchers2);

        this.timeout(0);
        allReady(watchers, function() {
            fs.mkdirSync(tempDir2);
            setTimeout(function() {
                var file;
                for (file in files1) {
                    fs.writeFileSync(file, 'created');
                }

                for (file in files2) {
                    fs.writeFileSync(file, 'created');
                }

                setTimeout(function() {
                    var file;
                    for (file in files1) {
                        files1[file].should.equal(true);
                    }

                    for (file in files2) {
                        files2[file].should.equal(true);
                    }

                    done();
                }, 1000);
            }, 400);
        });
    });

    it('should properly find files by extension', function(done) {
        done = once(done);

        var tempFile = path.join(tempDir, 'test.txt~.part');
        var glob = path.join(tempDir, '*.txt');

        var calledCount = 0;
        watchers = watch(glob, {verbose: false}, function() {
            calledCount++;
        });

        this.timeout(0);
        allReady(watchers, function() {
            fs.writeFileSync(tempFile, 'created');
            setTimeout(function() {
                calledCount.should.equal(0);
                done();
            }, 1000);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var Decompress = require('../');
var path = require('path');
var test = require('ava');

test('extract .tar', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test.tar'))
		.use(Decompress.tar());

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test.jpg');
	});
});

test('extract .tar.bz2', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test.tar.bz2'))
		.use(Decompress.tarbz2());

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test.jpg');
	});
});

test('extract .tar.gz', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test.tar.gz'))
		.use(Decompress.targz());

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test.jpg');
	});
});

test('extract .zip', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test.zip'))
		.use(Decompress.zip());

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test.jpg');
	});
});

test('extract using the strip option', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test-strip.zip'))
		.use(Decompress.zip({ strip: 1 }));

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test-strip.jpg');
	});
});
<commit_msg>Add CLI test<commit_after>'use strict';

var Decompress = require('../');
var fs = require('fs');
var path = require('path');
var rm = require('rimraf');
var spawn = require('child_process').spawn;
var test = require('ava');

test('extract .tar', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test.tar'))
		.use(Decompress.tar());

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test.jpg');
	});
});

test('extract .tar.bz2', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test.tar.bz2'))
		.use(Decompress.tarbz2());

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test.jpg');
	});
});

test('extract .tar.gz', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test.tar.gz'))
		.use(Decompress.targz());

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test.jpg');
	});
});

test('extract .zip', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test.zip'))
		.use(Decompress.zip());

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test.jpg');
	});
});

test('extract using the strip option', function (t) {
	t.plan(2);

	var decompress = new Decompress()
		.src(path.join(__dirname, 'fixtures/test-strip.zip'))
		.use(Decompress.zip({ strip: 1 }));

	decompress.run(function (err, files) {
		t.assert(!err);
		t.assert(files[0].path === 'test-strip.jpg');
	});
});

test('extract from stdin using the CLI', function (t) {
	t.plan(3);

	var tmp = path.join(__dirname, 'tmp');
	var cli = spawn(path.join(__dirname, '../cli.js'), [tmp]);
	var src = fs.createReadStream(path.join(__dirname, 'fixtures/test.zip'));

	cli.on('close', function (code) {
		t.assert(!code);

		fs.exists(path.join(tmp, 'test.jpg'), function (exists) {
			t.assert(exists);

			rm(tmp, function (err) {
				t.assert(!err);
			});
		});
	});

	src.pipe(cli.stdin);
});
<|endoftext|>


<commit_before>var expect = require("chai").expect;
var pindakaas = require("../");

describe("pindakaas", function () {
	"use strict";

	it("should expose an function", function () {
		expect(pindakaas).to.be.a("function");
	});

	describe("dates", function () {
		it("should parse relative dates without a time", function () {
			var result = pindakaas('overmorgen');
			var expected = new Date();
			expected.setDate(new Date().getDate() + 2);

			expect(result).to.be.an("array");
			expect(result[0].date).to.be.a("date");
			// Check parse result with a slight room for error.
			expect(result[0].date.getTime() - expected.getTime() < 10000).to.be.true;

		});
		it("should parse relative dates with a time", function () {
			var result = pindakaas('gister 15:41');
			var expected = new Date();
			expected.setDate(new Date().getDate() - 1);
			expected.setHours("15");
			expected.setMinutes("41");

			expect(result).to.be.an("array");
			expect(result[0].date).to.be.a("date");
			// Check parse result with a slight room for error.
			expect(result[0].date.getTime() - expected.getTime() < 10000).to.be.true;
		});
	})
});
<commit_msg>Update test.js<commit_after>var expect = require("chai").expect;
var pindakaas = require("../");

describe("pindakaas", function () {
	"use strict";

	it("should expose a function", function () {
		expect(pindakaas).to.be.a("function");
	});

	describe("dates", function () {
		it("should parse relative dates without a time", function () {
			var result = pindakaas('overmorgen');
			var expected = new Date();
			expected.setDate(new Date().getDate() + 2);

			expect(result).to.be.an("array");
			expect(result[0].date).to.be.a("date");
			// Check parse result with a slight room for error.
			expect(result[0].date.getTime() - expected.getTime() < 10000).to.be.true;

		});
		it("should parse relative dates with a time", function () {
			var result = pindakaas('gister 15:41');
			var expected = new Date();
			expected.setDate(new Date().getDate() - 1);
			expected.setHours("15");
			expected.setMinutes("41");

			expect(result).to.be.an("array");
			expect(result[0].date).to.be.a("date");
			// Check parse result with a slight room for error.
			expect(result[0].date.getTime() - expected.getTime() < 10000).to.be.true;
		});
	})
});
<|endoftext|>


<commit_before>angular.module('demo', ['img-src-ondemand'])
.run(function($document) {
  for (var i = 20; i > 0; --i) {
    var m = Math.random() * 500 >> 0,
        n = Math.random() * 500 >> 0;
    var img = document.createElement('img');
    img.setAttribute('src-ondemand', 'http://lorempixel.com/g/' + m + '/' + n);
    $document[0].body.appendChild(img);
  }
});
<commit_msg>It's included in test.html<commit_after><|endoftext|>


<commit_before>describe('md tests', function () {
  var expect;

  before(function () {
    expect = chai.expect;
    require.config({
      baseUrl: '/test'
    });
  });

  it('should load multiple dependencies', function (done) {
    require(['../md!a;b;c'], function (md) {
      expect(md).to.be.array;
      expect(md[0]).to.equal('a');
      expect(md[1]).to.equal('b');
      expect(md[2]).to.equal('c');
      done();
    });
  });
});
<commit_msg>Added relateive path test.<commit_after>describe('md tests', function () {
  var expect;

  before(function () {
    expect = chai.expect;
    require.config({
      baseUrl: '/test'
    });
  });

  it('should load multiple dependencies', function (done) {
    require(['../md!a;b;c'], function (md) {
      expect(md).to.be.array;
      expect(md[0]).to.equal('a');
      expect(md[1]).to.equal('b');
      expect(md[2]).to.equal('c');
      done();
    });
  });

  it('should load multiple dependencies with relative paths', function (done) {
    require.config({
      baseUrl: '/test/foo/bar'
    });
    require(['../../../md!../../a;../../b;../../c'], function (md) {
      expect(md).to.be.array;
      expect(md[0]).to.equal('a');
      expect(md[1]).to.equal('b');
      expect(md[2]).to.equal('c');
      require.config({
        baseUrl: '/test'
      });
      done();
    });
  });
});
<|endoftext|>


<commit_before>MockXHR.responses = {
  '/hello': function(xhr) {
    xhr.respond(200, 'hi')
  },
  '/boom': function(xhr) {
    xhr.respond(500, 'boom')
  },
  '/json': function(xhr) {
    xhr.respond(200, JSON.stringify({name: 'Hubot', login: 'hubot'}))
  },
  '/json-error': function(xhr) {
    xhr.respond(200, 'not json {')
  },
  '/headers': function(xhr) {
    var headers = [
      'Date: Mon, 13 Oct 2014 21:02:27 GMT',
      'Content-Type: text/html; charset=utf-8'
    ].join('\r\n')
    xhr.respond(200, 'hi', headers + '\r\n')
  }
}

window.XMLHttpRequest = MockXHR

asyncTest('populates response body', 3, function() {
  fetch('/hello').then(function(response) {
    equal(MockXHR.last().method, 'GET')
    equal(response.status, 200)
    equal(response.body, 'hi')
    start()
  })
})

asyncTest('sends request headers', 2, function() {
  fetch('/hello', {
    headers: {
      'Accept': 'application/json',
      'X-Test': '42'
    }
  }).then(function() {
    var request = MockXHR.last()
    equal(request.headers['Accept'], 'application/json')
    equal(request.headers['X-Test'], '42')
    start()
  })
})

asyncTest('parses response headers', 2, function() {
  fetch('/headers').then(function(response) {
    equal(response.headers.get('Date'), 'Mon, 13 Oct 2014 21:02:27 GMT')
    equal(response.headers.get('Content-Type'), 'text/html; charset=utf-8')
    start()
  })
})

asyncTest('resolves text promise', 1, function() {
  fetch('/hello').then(function(response) {
    return response.text()
  }).then(function(text) {
    equal(text, 'hi')
    start()
  })
})

asyncTest('parses json response', 2, function() {
  fetch('/json').then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.name, 'Hubot')
    equal(json.login, 'hubot')
    start()
  })
})

asyncTest('handles json parse error', 2, function() {
  fetch('/json-error').then(function(response) {
    return response.json()
  }).catch(function(error) {
    ok(error instanceof Error, 'JSON exception is an Error instance')
    ok(error.message, 'JSON exception has an error message')
    start()
  })
})

asyncTest('resolves blob promise', 2, function() {
  fetch('/hello').then(function(response) {
    return response.blob()
  }).then(function(blob) {
    ok(blob instanceof Blob, 'blob is a Blob instance')
    equal(blob.size, 2)
    start()
  })
})

asyncTest('post sends encoded body', 2, function() {
  fetch('/hello', {
    method: 'post',
    body: {
      name: 'Hubot',
      title: 'Hubot Robawt',
      undef: undefined,
      nil: null
    }
  }).then(function() {
    var request = MockXHR.last()
    equal(request.method, 'post')
    equal(request.data, 'name=Hubot&title=Hubot+Robawt&nil=')
    start()
  })
})

asyncTest('post sets content-type header', 1, function() {
  fetch('/hello', {
    method: 'post',
    body: {}
  }).then(function() {
    var request = MockXHR.last()
    equal(request.headers['Content-Type'], 'application/x-www-form-urlencoded; charset=UTF-8')
    start()
  })
})
<commit_msg>Test promise is resolved for non-200 response.<commit_after>MockXHR.responses = {
  '/hello': function(xhr) {
    xhr.respond(200, 'hi')
  },
  '/boom': function(xhr) {
    xhr.respond(500, 'boom')
  },
  '/json': function(xhr) {
    xhr.respond(200, JSON.stringify({name: 'Hubot', login: 'hubot'}))
  },
  '/json-error': function(xhr) {
    xhr.respond(200, 'not json {')
  },
  '/headers': function(xhr) {
    var headers = [
      'Date: Mon, 13 Oct 2014 21:02:27 GMT',
      'Content-Type: text/html; charset=utf-8'
    ].join('\r\n')
    xhr.respond(200, 'hi', headers + '\r\n')
  }
}

window.XMLHttpRequest = MockXHR

asyncTest('populates response body', 3, function() {
  fetch('/hello').then(function(response) {
    equal(MockXHR.last().method, 'GET')
    equal(response.status, 200)
    equal(response.body, 'hi')
    start()
  })
})

asyncTest('sends request headers', 2, function() {
  fetch('/hello', {
    headers: {
      'Accept': 'application/json',
      'X-Test': '42'
    }
  }).then(function() {
    var request = MockXHR.last()
    equal(request.headers['Accept'], 'application/json')
    equal(request.headers['X-Test'], '42')
    start()
  })
})

asyncTest('parses response headers', 2, function() {
  fetch('/headers').then(function(response) {
    equal(response.headers.get('Date'), 'Mon, 13 Oct 2014 21:02:27 GMT')
    equal(response.headers.get('Content-Type'), 'text/html; charset=utf-8')
    start()
  })
})

asyncTest('resolves promise on 500 error', 2, function() {
  fetch('/boom').then(function(response) {
    equal(response.status, 500)
    equal(response.body, 'boom')
    start()
  })
})

asyncTest('resolves text promise', 1, function() {
  fetch('/hello').then(function(response) {
    return response.text()
  }).then(function(text) {
    equal(text, 'hi')
    start()
  })
})

asyncTest('parses json response', 2, function() {
  fetch('/json').then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.name, 'Hubot')
    equal(json.login, 'hubot')
    start()
  })
})

asyncTest('handles json parse error', 2, function() {
  fetch('/json-error').then(function(response) {
    return response.json()
  }).catch(function(error) {
    ok(error instanceof Error, 'JSON exception is an Error instance')
    ok(error.message, 'JSON exception has an error message')
    start()
  })
})

asyncTest('resolves blob promise', 2, function() {
  fetch('/hello').then(function(response) {
    return response.blob()
  }).then(function(blob) {
    ok(blob instanceof Blob, 'blob is a Blob instance')
    equal(blob.size, 2)
    start()
  })
})

asyncTest('post sends encoded body', 2, function() {
  fetch('/hello', {
    method: 'post',
    body: {
      name: 'Hubot',
      title: 'Hubot Robawt',
      undef: undefined,
      nil: null
    }
  }).then(function() {
    var request = MockXHR.last()
    equal(request.method, 'post')
    equal(request.data, 'name=Hubot&title=Hubot+Robawt&nil=')
    start()
  })
})

asyncTest('post sets content-type header', 1, function() {
  fetch('/hello', {
    method: 'post',
    body: {}
  }).then(function() {
    var request = MockXHR.last()
    equal(request.headers['Content-Type'], 'application/x-www-form-urlencoded; charset=UTF-8')
    start()
  })
})
<|endoftext|>


<commit_before>if (!process.browser) {
  require('rimraf').sync('./test/db')
} else {
  require('level-js').destroy('./test/db', function () {})
}

var test = require('tape')

var levi = require('../')
var similarity = require('../lib/util/similarity')
var group = require('../lib/util/group')
var jsondown = require('jsondown')
var H = require('highland')

var lv = levi('./test/db')
.use(levi.tokenizer())
.use(levi.stemmer())
.use(levi.stopword())

test('pipeline', function (t) {
  t.plan(4)
  lv.pipeline('including a foo bar of __proto__ constructor.', function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      '@includ', '@foo', '@bar', '@__proto__', '@constructor'
    ], 'stemmer, stopwords, js reserved words')
  })
  lv.pipeline({
    a: 'foo bar',
    c: ['hello'],
    d: { asdf: { ghjk: 'world' } },
    e: 167,
    f: null
  }, function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      '@foo', '@bar', '@hello', '@world'
    ], 'text extraction from object')
  })
})

test('grouping', function (t) {
  H([{key: 1}, {key: 1}, {key: 2}, {key: 3}, {key: 3}])
  .through(group)
  .toArray(function (arr) {
    t.deepEqual(arr, [
      [ { key: 1 }, { key: 1 } ],
      [ { key: 2 } ],
      [ { key: 3 }, { key: 3 } ]
    ], 'grouping')
    t.end()
  })
})

test('similarity', function (t) {
  t.equal(Math.round(similarity(
    {x: 1, y: 3, z: -5, foo: 0},
    {x: 4, y: -2, z: -1}
  ) * 1000) / 1000, 0.111, 'cosine similarity')

  t.equal(similarity(
    {x: 1, y: 3, z: -5},
    {x: 0, y: 0, z: 0}
  ), 0, 'zero magitude vector')

  t.end()
})

test('CRUD', function (t) {
  var aObj = {
    a: 'hello world'
  }
  lv.put('a', aObj, function () {
    lv.get('a', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, aObj, 'put object')
    })
  })
  var bText = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
  lv.put('b', new Buffer(bText), function () {
    lv.get('b', function (err, value) {
      t.notOk(err)
      t.equal(value, bText, 'put buffer')
      t.equal(typeof value, 'string', 'buffer converted to string')
    })
  })
  var cText = 'Aldus PageMaker including versions of Lorem Ipsum.'
  lv.put('c', cText, function () {
    lv.get('c', function (err, value) {
      t.notOk(err)
      t.equal(value, cText, 'put string')
      lv.meta.get('size', function (err, size) {
        t.notOk(err)
        t.equal(size, 3, 'size correct')
      })
    })
  })

  lv.put('d', 'Rick rolling', function (err) {
    t.notOk(err)
    lv.searchStream('rolling and hatin').toArray(function (arr) {
      t.equal(arr.length, 1, 'correct put')
      t.equal(arr[0].key, 'd', 'correct put')
      t.equal(arr[0].value, 'Rick rolling', 'correct put')
      lv.put('d', 'Rick Ashley', function (err) {
        t.notOk(err)
        lv.searchStream('rolling').toArray(function (arr) {
          t.equal(arr.length, 0, 'correct clean up')
          lv.searchStream('ashley').toArray(function (arr) {
            t.equal(arr.length, 1, 'correct upsert')
            t.equal(arr[0].key, 'd', 'correct upsert')
            t.equal(arr[0].value, 'Rick Ashley', 'correct upsert')

            lv.del('a')
            lv.del('b')
            lv.del('c')
            lv.del('d', function (err) {
              t.notOk(err)
              lv.meta.get('size', function (err, size) {
                t.notOk(err && !err.notFound)
                t.notOk(size, 'empty after delete all')
                t.end()
              })
            })
          })
        })
      })
    })
  })
})

test('Search options', function (t) {
  t.plan(12)

  var live = lv.liveStream('green plant')

  H([{
    id: 'a',
    title: 'Mr. Green kills Colonel Mustard',
    body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. ' +
      'Mr. Green is not a very nice fellow.'
  }, {
    id: 'b',
    title: 'Plumb waters plant',
    body: 'Professor Plumb has a green plant in his study'
  }, {
    id: 'c',
    title: 'Scarlett helps Professor',
    body: 'Miss Scarlett watered Professor Plumbs green plant while he was away ' +
      'from his office last week.'
  }, {
    id: 'd',
    title: 'foo',
    body: 'bar'
  }])
  .map(H.wrapCallback(function (doc, cb) {
    lv.put(doc.id, doc, cb)
  }))
  .series()
  .done(function () {
    lv.searchStream('green plant').toArray(function (arr) {
      t.equal(arr.length, 3, 'search: correct number of results')
      t.equal(arr[0].key, 'b', 'search: correct score')

      lv.searchStream(['green', 'plant']).toArray(function (arr2) {
        t.deepEqual(arr2, arr, 'tokenized query')
      })

      lv.searchStream('green plant', { values: false }).toArray(function (arr) {
        t.notOk(arr[0].value, 'values: false')
      })

      lv.searchStream('green plant', { offset: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(1), 'query offset')
      })

      lv.searchStream('green plant', { limit: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(0, 1), 'limit')
      })

      live.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })

    lv.searchStream('green', { fields: { title: true } }).toArray(function (arr) {
      t.equal(arr.length, 1, 'fielded: correct number of results')
      t.equal(arr[0].key, 'a', 'fielded: correct result')
    })

    lv.searchStream('watering plant', { fields: { title: 1, body: 10 } }).toArray(function (arr) {
      t.equal(arr.length, 2, 'field boosting: correct number of results')
      t.equal(arr[0].key, 'c', 'field boosting: correct boosted result')
    })
  })
})
<commit_msg>fix standard<commit_after>if (!process.browser) {
  require('rimraf').sync('./test/db')
} else {
  require('level-js').destroy('./test/db', function () {})
}

var test = require('tape')

var levi = require('../')
var similarity = require('../lib/util/similarity')
var group = require('../lib/util/group')
// var jsondown = require('jsondown')
var H = require('highland')

var lv = levi('./test/db')
.use(levi.tokenizer())
.use(levi.stemmer())
.use(levi.stopword())

test('pipeline', function (t) {
  t.plan(4)
  lv.pipeline('including a foo bar of __proto__ constructor.', function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      '@includ', '@foo', '@bar', '@__proto__', '@constructor'
    ], 'stemmer, stopwords, js reserved words')
  })
  lv.pipeline({
    a: 'foo bar',
    c: ['hello'],
    d: { asdf: { ghjk: 'world' } },
    e: 167,
    f: null
  }, function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      '@foo', '@bar', '@hello', '@world'
    ], 'text extraction from object')
  })
})

test('grouping', function (t) {
  H([{key: 1}, {key: 1}, {key: 2}, {key: 3}, {key: 3}])
  .through(group)
  .toArray(function (arr) {
    t.deepEqual(arr, [
      [ { key: 1 }, { key: 1 } ],
      [ { key: 2 } ],
      [ { key: 3 }, { key: 3 } ]
    ], 'grouping')
    t.end()
  })
})

test('similarity', function (t) {
  t.equal(Math.round(similarity(
    {x: 1, y: 3, z: -5, foo: 0},
    {x: 4, y: -2, z: -1}
  ) * 1000) / 1000, 0.111, 'cosine similarity')

  t.equal(similarity(
    {x: 1, y: 3, z: -5},
    {x: 0, y: 0, z: 0}
  ), 0, 'zero magitude vector')

  t.end()
})

test('CRUD', function (t) {
  var aObj = {
    a: 'hello world'
  }
  lv.put('a', aObj, function () {
    lv.get('a', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, aObj, 'put object')
    })
  })
  var bText = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
  lv.put('b', new Buffer(bText), function () {
    lv.get('b', function (err, value) {
      t.notOk(err)
      t.equal(value, bText, 'put buffer')
      t.equal(typeof value, 'string', 'buffer converted to string')
    })
  })
  var cText = 'Aldus PageMaker including versions of Lorem Ipsum.'
  lv.put('c', cText, function () {
    lv.get('c', function (err, value) {
      t.notOk(err)
      t.equal(value, cText, 'put string')
      lv.meta.get('size', function (err, size) {
        t.notOk(err)
        t.equal(size, 3, 'size correct')
      })
    })
  })

  lv.put('d', 'Rick rolling', function (err) {
    t.notOk(err)
    lv.searchStream('rolling and hatin').toArray(function (arr) {
      t.equal(arr.length, 1, 'correct put')
      t.equal(arr[0].key, 'd', 'correct put')
      t.equal(arr[0].value, 'Rick rolling', 'correct put')
      lv.put('d', 'Rick Ashley', function (err) {
        t.notOk(err)
        lv.searchStream('rolling').toArray(function (arr) {
          t.equal(arr.length, 0, 'correct clean up')
          lv.searchStream('ashley').toArray(function (arr) {
            t.equal(arr.length, 1, 'correct upsert')
            t.equal(arr[0].key, 'd', 'correct upsert')
            t.equal(arr[0].value, 'Rick Ashley', 'correct upsert')

            lv.del('a')
            lv.del('b')
            lv.del('c')
            lv.del('d', function (err) {
              t.notOk(err)
              lv.meta.get('size', function (err, size) {
                t.notOk(err && !err.notFound)
                t.notOk(size, 'empty after delete all')
                t.end()
              })
            })
          })
        })
      })
    })
  })
})

test('Search options', function (t) {
  t.plan(12)

  var live = lv.liveStream('green plant')

  H([{
    id: 'a',
    title: 'Mr. Green kills Colonel Mustard',
    body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. ' +
      'Mr. Green is not a very nice fellow.'
  }, {
    id: 'b',
    title: 'Plumb waters plant',
    body: 'Professor Plumb has a green plant in his study'
  }, {
    id: 'c',
    title: 'Scarlett helps Professor',
    body: 'Miss Scarlett watered Professor Plumbs green plant while he was away ' +
      'from his office last week.'
  }, {
    id: 'd',
    title: 'foo',
    body: 'bar'
  }])
  .map(H.wrapCallback(function (doc, cb) {
    lv.put(doc.id, doc, cb)
  }))
  .series()
  .done(function () {
    lv.searchStream('green plant').toArray(function (arr) {
      t.equal(arr.length, 3, 'search: correct number of results')
      t.equal(arr[0].key, 'b', 'search: correct score')

      lv.searchStream(['green', 'plant']).toArray(function (arr2) {
        t.deepEqual(arr2, arr, 'tokenized query')
      })

      lv.searchStream('green plant', { values: false }).toArray(function (arr) {
        t.notOk(arr[0].value, 'values: false')
      })

      lv.searchStream('green plant', { offset: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(1), 'query offset')
      })

      lv.searchStream('green plant', { limit: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(0, 1), 'limit')
      })

      live.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })

    lv.searchStream('green', { fields: { title: true } }).toArray(function (arr) {
      t.equal(arr.length, 1, 'fielded: correct number of results')
      t.equal(arr[0].key, 'a', 'fielded: correct result')
    })

    lv.searchStream('watering plant', { fields: { title: 1, body: 10 } }).toArray(function (arr) {
      t.equal(arr.length, 2, 'field boosting: correct number of results')
      t.equal(arr[0].key, 'c', 'field boosting: correct boosted result')
    })
  })
})
<|endoftext|>


<commit_before>/* global describe: false, it: false, beforeEach: false, afterEach: false */
(function (document, $, MIDIKeys) {
    'use strict';

    function createKeyEvent(c) {
        var event = document.createEvent('HTMLEvents');
        event.initEvent('keydown', true, false);
        event.keyCode = c.charCodeAt(0);
        return event;
    }

    describe('MIDIKeys', function () {

        var el;

        beforeEach(function () {
            el = document.createElement('div');
        });

        it('translates keydown events into MIDI NOTE ON messages', function (done) {
            var plugin = new MIDIKeys(el);

            plugin.option('onmidimessage', function (message) {
                expect(message.data[0]).to.equal(0x90, 'Should be a MIDI NOTE ON event');
                expect(message.data[1]).to.equal(48, 'Should be a C3 note');
                expect(message.data[2]).to.equal(127, 'Should have default velocity');
                done();
            });

            el.dispatchEvent(createKeyEvent('Z'));
        });

        it('ceases to fire events after being deregistered', function () {

        });

    });

    describe('jquery.midiKeys', function () {

        describe('plugin registration', function () {

            it('should be attached to jQuery prototype', function () {
                expect($.fn.hasOwnProperty('midiKeys')).to.equal(true);
            });

            it('initializes with defaults withour error, returning the element', function () {
                var $el = $('

');
                expect($el).to.equal($el.midiKeys());
            });

        });

        describe('execution', function () {

            var $el;

            beforeEach(function () {
                $el = $('

').midiKeys();
            });

            it('translates keydown events into MIDI NOTE ON messages', function (done) {
                $el.midiKeys('option', 'onmidimessage', function (message) {
                    expect(message.data[0]).to.equal(0x90, 'Should be a MIDI NOTE ON event');
                    expect(message.data[1]).to.equal(48, 'Should be a C3 note');
                    expect(message.data[2]).to.equal(127, 'Should have default velocity');
                    done();
                });

                $el[0].dispatchEvent(createKeyEvent('Z'));
            });

            afterEach(function () {
                $el.midiKeys('destroy');
            });
        });

    });

}(this.document, this.jQuery, this.MIDIKeys));
<commit_msg>extracted helper functions<commit_after>/* global describe: false, it: false, beforeEach: false, afterEach: false */
(function (document, $, MIDIKeys) {
    'use strict';

    function createKeyEvent(type, key) {
        var event = document.createEvent('HTMLEvents');
        event.initEvent(type, true, false);
        event.keyCode = key.charCodeAt(0);
        return event;
    }

    function triggerKeyEvent(el, type, key) {
        el.dispatchEvent(createKeyEvent(type, key));
    }

    function triggerKeydown(el, key) {
        triggerKeyEvent(el, 'keydown', key);
    }

    describe('MIDIKeys', function () {

        var el;

        beforeEach(function () {
            el = document.createElement('div');
        });

        it('translates keydown events into MIDI NOTE ON messages', function (done) {
            var plugin = new MIDIKeys(el);

            plugin.option('onmidimessage', function (message) {
                expect(message.data[0]).to.equal(0x90, 'Should be a MIDI NOTE ON event');
                expect(message.data[1]).to.equal(48, 'Should be a C3 note');
                expect(message.data[2]).to.equal(127, 'Should have default velocity');
                done();
            });

            triggerKeydown(el, 'Z');
        });

    });

    describe('jquery.midiKeys', function () {

        describe('plugin registration', function () {

            it('should be attached to jQuery prototype', function () {
                expect($.fn.hasOwnProperty('midiKeys')).to.equal(true);
            });

            it('initializes with defaults withour error, returning the element', function () {
                var $el = $('

');
                expect($el).to.equal($el.midiKeys());
            });

        });

        describe('execution', function () {

            var $el;

            beforeEach(function () {
                $el = $('

').midiKeys();
            });

            it('translates keydown events into MIDI NOTE ON messages', function (done) {
                $el.midiKeys('option', 'onmidimessage', function (message) {
                    expect(message.data[0]).to.equal(0x90, 'Should be a MIDI NOTE ON event');
                    expect(message.data[1]).to.equal(48, 'Should be a C3 note');
                    expect(message.data[2]).to.equal(127, 'Should have default velocity');
                    done();
                });

                triggerKeydown($el[0], 'Z');
            });

            afterEach(function () {
                $el.midiKeys('destroy');
            });
        });

    });

}(this.document, this.jQuery, this.MIDIKeys));
<|endoftext|>


<commit_before>/**
 *
 */

var assert=require('assert');

var WebServer=require('../server.js');
var server=new WebServer({port:8091});

var http=require('http');
http.request({
	hostname: 'http://localhost',
	port: 8091
}, function(res) {

}).on('error', function(e) {
	assert.fail(e.message);
}).end();

setTimeout(function(){
	assert.fail('fail');
},1000);<commit_msg>remove timeout<commit_after>/**
 *
 */

var assert=require('assert');

var WebServer=require('../server.js');
var server=new WebServer({port:8091});

var http=require('http');
http.request({
	hostname: 'http://localhost',
	port: 8091
}, function(res) {

}).on('error', function(e) {
	assert.fail(e.message);
}).end();
<|endoftext|>


<commit_before>import React from 'react';
import { getContext } from 'recompose';
import tinycolor from 'tinycolor2';
import PropTypes from 'prop-types';

export default getContext({
  theme: PropTypes.object,
})(({ width, height, size, theme, clean }) => {
  const color = clean ? '#FFF' : theme.get().color;

  return (
    <svg
      width={width || size || 100}
      height={height || Math.round(size / 1001 * 790) || 79}
      viewBox="0 0 1001 790"
      xmlns="http://www.w3.org/2000/svg"
    >
      <defs>
        <linearGradient
          x1="50%"
          y1="0%"
          x2="50%"
          y2="99.273%"
          id="linearGradient-1"
        >
          <stop
            stopColor={tinycolor(color)
              .lighten(8)
              .spin(6)
              .toRgbString()}
            stopOpacity=".617"
            offset="0%"
          />
          <stop
            stopColor={tinycolor(color)
              .darken(4)
              .spin(-3)
              .toRgbString()}
            stopOpacity=".863"
            offset="100%"
          />
        </linearGradient>
        <linearGradient
          x1="15.734%"
          y1="1.293%"
          x2="49.318%"
          y2="94.09%"
          id="linearGradient-2"
        >
          <stop
            stopColor={tinycolor(color)
              .lighten(8)
              .spin(6)
              .toRgbString()}
            stopOpacity=".587"
            offset="0%"
          />
          <stop
            stopColor={tinycolor(color)
              .darken(4)
              .spin(-3)
              .toRgbString()}
            stopOpacity=".651"
            offset="100%"
          />
        </linearGradient>
        <linearGradient
          x1="82.681%"
          y1="29.971%"
          x2="50%"
          y2="70.029%"
          id="linearGradient-3"
        >
          <stop
            stopColor={tinycolor(color)
              .lighten(8)
              .spin(6)
              .toRgbString()}
            offset="0%"
          />
          <stop
            stopColor={tinycolor(color)
              .darken(4)
              .spin(-3)
              .toRgbString()}
            offset="100%"
          />
        </linearGradient>
        <linearGradient
          x1="8.793%"
          y1="13.73%"
          x2="50%"
          y2="89.257%"
          id="linearGradient-4"
        >
          <stop
            stopColor={tinycolor(color)
              .lighten(8)
              .spin(6)
              .toRgbString()}
            stopOpacity=".502"
            offset="0%"
          />
          <stop
            stopColor={tinycolor(color)
              .darken(4)
              .spin(-3)
              .toRgbString()}
            stopOpacity=".758"
            offset="100%"
          />
        </linearGradient>
      </defs>
      <g id="Page-1" fill="none" fillRule="evenodd">
        <g id="Artboard">
          <g id="logo">
            <g id="Page-1">
              <polygon
                id="left"
                fill="url(#linearGradient-1)"
                opacity=".7"
                points="1 580 301.446897 60 501 790"
              />
              <polygon
                id="inner-left"
                fill="url(#linearGradient-2)"
                points="1001 580 301 60 501 790"
              />
              <polygon
                id="right"
                fill="url(#linearGradient-3)"
                opacity=".7"
                transform="matrix(-1 0 0 1 1502 0)"
                points="501 580 801 0 1001 790"
              />
              <polygon
                id="inner-right"
                fill="url(#linearGradient-4)"
                transform="matrix(-1 0 0 1 701.997 0)"
                points="701 579.999802 0.997192 0 200.997192 790"
              />
            </g>
          </g>
        </g>
      </g>
    </svg>
  );
});
<commit_msg>small fix in logo<commit_after>import React from 'react';
import { getContext } from 'recompose';
import tinycolor from 'tinycolor2';
import PropTypes from 'prop-types';

export default getContext({
  theme: PropTypes.object,
})(({ width, height, size, theme, clean, className }) => {
  const color = clean ? '#FFF' : theme.get().color;

  return (
    <svg
      width={width || size || 100}
      height={height || Math.round(size / 1001 * 790) || 79}
      viewBox="0 0 1001 790"
      xmlns="http://www.w3.org/2000/svg"
      className={className}
    >
      <defs>
        <linearGradient
          x1="50%"
          y1="0%"
          x2="50%"
          y2="99.273%"
          id="linearGradient-1"
        >
          <stop
            stopColor={tinycolor(color)
              .lighten(8)
              .spin(6)
              .toRgbString()}
            stopOpacity=".617"
            offset="0%"
          />
          <stop
            stopColor={tinycolor(color)
              .darken(4)
              .spin(-3)
              .toRgbString()}
            stopOpacity=".863"
            offset="100%"
          />
        </linearGradient>
        <linearGradient
          x1="15.734%"
          y1="1.293%"
          x2="49.318%"
          y2="94.09%"
          id="linearGradient-2"
        >
          <stop
            stopColor={tinycolor(color)
              .lighten(8)
              .spin(6)
              .toRgbString()}
            stopOpacity=".587"
            offset="0%"
          />
          <stop
            stopColor={tinycolor(color)
              .darken(4)
              .spin(-3)
              .toRgbString()}
            stopOpacity=".651"
            offset="100%"
          />
        </linearGradient>
        <linearGradient
          x1="82.681%"
          y1="29.971%"
          x2="50%"
          y2="70.029%"
          id="linearGradient-3"
        >
          <stop
            stopColor={tinycolor(color)
              .lighten(8)
              .spin(6)
              .toRgbString()}
            offset="0%"
          />
          <stop
            stopColor={tinycolor(color)
              .darken(4)
              .spin(-3)
              .toRgbString()}
            offset="100%"
          />
        </linearGradient>
        <linearGradient
          x1="8.793%"
          y1="13.73%"
          x2="50%"
          y2="89.257%"
          id="linearGradient-4"
        >
          <stop
            stopColor={tinycolor(color)
              .lighten(8)
              .spin(6)
              .toRgbString()}
            stopOpacity=".502"
            offset="0%"
          />
          <stop
            stopColor={tinycolor(color)
              .darken(4)
              .spin(-3)
              .toRgbString()}
            stopOpacity=".758"
            offset="100%"
          />
        </linearGradient>
      </defs>
      <g id="Page-1" fill="none" fillRule="evenodd">
        <g id="Artboard">
          <g id="logo">
            <g id="Page-1">
              <polygon
                id="left"
                fill="url(#linearGradient-1)"
                opacity=".7"
                points="1 580 301.446897 60 501 790"
              />
              <polygon
                id="inner-left"
                fill="url(#linearGradient-2)"
                points="1001 580 301 60 501 790"
              />
              <polygon
                id="right"
                fill="url(#linearGradient-3)"
                opacity=".7"
                transform="matrix(-1 0 0 1 1502 0)"
                points="501 580 801 0 1001 790"
              />
              <polygon
                id="inner-right"
                fill="url(#linearGradient-4)"
                transform="matrix(-1 0 0 1 701.997 0)"
                points="701 579.999802 0.997192 0 200.997192 790"
              />
            </g>
          </g>
        </g>
      </g>
    </svg>
  );
});
<|endoftext|>


<commit_before>/**
 * Summary: inherit from lib.PubSub if a class wants publish/subscribe ability
 * Methods:
 *  - publish(signal, args...) - all subscribers to signal will be called
 *     with the list of arguments provided.
 *  - subscribe(signal, ctx, method, args...) - register a bound method
 *     to a signal.  Any args that are passed in will be the first args
 *     when the method is invoked during a publish.
 *  Usage notes: There is one special signal '__any'.  Any subscribers to
 *     '__any' will be called on every publish with the first publish
 *     argument being the signal itself (after any args passed in during
 *     the corresponding subscribe).
 *     Calling the super constructor is not required for descendants of
 *     lib.PubSub.
 */

jsio('import lib.Callback as Callback');
from ..std.uuid import uuid;

var ctx = jsio.__env.global,
	SLICE = Array.prototype.slice;

exports = Class(function () {

	this.init = function () {};

	this.publish = function (signal) {
		if (this._subscribers) {
			var args = SLICE.call(arguments, 1);
			if (this._subscribers.__any) {
				var anyArgs = [signal].concat(args),
					subs = this._subscribers.__any.slice(0);
				for(var i = 0, sub; sub = subs[i]; ++i) {
					sub.apply(ctx, anyArgs);
				}
			}

			if (!this._subscribers[signal]) {
				return this;
			}

			var subs = this._subscribers[signal].slice(0);
			for (var i = 0, sub; sub = subs[i]; ++i) {
				sub.apply(ctx, args);
			}
		}
		return this;
	};

	this.subscribe = function (signal, ctx, method) {
		var cb;
		if (arguments.length == 2) {
			cb = ctx;
		} else {
			cb = bind.apply(GLOBAL, SLICE.call(arguments, 1));
			cb._ctx = ctx; // references for unsubscription
			cb._method = method;
		}

		var s = this._subscribers || (this._subscribers = {});
		(s[signal] || (s[signal] = [])).push(cb);
		return this;
	};

	this.subscribeOnce = function (signal, ctx, method) {
		var args = arguments,
			cb = bind(this, function () {
				this.unsubscribe(signal, cb);
				if (args.length == 2) {
					ctx.apply(GLOBAL, arguments);
				} else {
					bind.apply(GLOBAL, SLICE.call(args, 1))
						.apply(GLOBAL, arguments);
				}
			});

		if (args.length >= 3) {
			cb._ctx = ctx;
			cb._method = method;
		}

		return this.subscribe(signal, cb);
	};

	// If no method is specified, all subscriptions with a callback context
	// of ctx will be removed.

	this.unsubscribe = function (signal, ctx, method) {
		if (!this._subscribers || !this._subscribers[signal]) {
			return this;
		}
		var subs = this._subscribers[signal];
		for (var i = 0, c; c = subs[i]; ++i) {
			if (c == ctx || c._ctx == ctx && (!method || c._method == method)) {
				subs.splice(i--, 1);
			}
		}
		return this;
	};

	/**
	 * EventEmitter-style API
	 * http://nodejs.org/api/events.html
	 */

	this.listeners = function (type) {
		this._subscribers = (this._subscribers ? this._subscribers : {});
		return (this.hasOwnProperty.call(this._subscribers, type))
			? this._subscribers[type]
			: (this._subscribers[type] = []);
	};

	this.addListener = this.on = function (type, f) {
		if (this.listeners(type).length + 1 > this._maxListeners && this._maxListeners !== 0) {
			if (typeof console !== "undefined") {
				console.warn("Possible EventEmitter memory leak detected. " + this._subscribers[type].length + " listeners added. Use emitter.setMaxListeners() to increase limit.");
			}
		}
		this.emit("newListener", type, f);
		return this.subscribe(type, this, f);
	};

	this.once = function (type, f) {
		return this.subscribeOnce(type, this, f);
	};

        this.chain = function (evnt, func) {
                var i,
                        cbs = this._callbacks || (this._callbacks = {}),
                        callback = new Callback(),
                        next = bind(this, function (val, cancel) {
                                var cb = this._callbacks[evnt][i] || {
                                        // i is poiting to the end of the queue, so creating custom cb object.
                                        fire: bind(this, function (val, cancel) {
                                                // call pending callbacks from the next event.

                                                var current = this._callbacks[evnt],
                                                        last = current[i];

                                                // if we are chaining a second signal, that mapping cb will be added
                                                // to the end of current event's queue, which becomes i'th value.
                                                if (last) {
                                                        last.fire(cancel);
                                                        last.clear();
                                                        // this is to remove the last cb which is just a mapping
                                                        // between event queues.
                                                        current.pop();
                                                }
                                                // remove current event
                                                this._activeCBs.shift();
                                        })
                                };

                                // execution of next function in the queue can be aborted
                                // by passing true as a paramter to the cb.
                                if (cancel) {
                                        // even if we want to cancel, we need to fire so that
                                        // we can reset all the callbacks
                                        cb.fire(val, cancel);
                                } else {
                                        // call the registered callback function with value and
                                        // fire function.
                                        // binding val to fire so that next function in the chain will also
                                        // get the value.
                                        func(val, bind(cb, cb.fire, val));
                                }

                                callback.reset();
                        });

                callback.run(next);

                if (!cbs[evnt]) {
                        // we need to register only once, remaining will be taken care
                        // by the next function.
                        cbs[evnt] = [];
                        this.on(evnt, bind(this, function (val) {
                                var active_cbs = this._activeCBs || (this._activeCBs = []),
				len = active_cbs.length,
                                pending, last;

                                // add to queue.
                                // this is needed for multi signal chaining
                                active_cbs.push(evnt);
                                if (len === 0) {

                                        // if there is no active function, fire cb immedietly.
                                        callback.fire(val);
                                } else {
                                        // some other execution is ongoing, add to the queue.
                                        last = active_cbs[len - 1];
                                        pending = new Callback();
                                        pending.run(bind(callback, callback.fire, val));
                                        // add to the end of last event's queue
                                        this._callbacks[last].push(pending);
                                }
                        }));
                }
                i = cbs[evnt].push(callback);
        };

	this.removeListener = function (type, f) {
		this.unsubscribe(type, this, f);
		return this;
	};

	this.removeAllListeners = function (type) {
		var current = (!this._callbacks || !this._callbacks[type]) ? [] : this._callbacks[type]
			cb_length = current.length;

		if (cb_length > 0) {
			for (var i = 0; i < cb_length; i++) {
				current[i].clear();
			}

			delete this._callbacks[type];
			this._activeCBs = this._activeCBs.filter(function (event) {
				return event !== type;
			});
                }

		if (this._subscribers) {
			for (var k in this._subscribers) {
				if (type == null || type == k) {
					delete this._subscribers[k];
				}
			}
		}
		return this;
	};

	this.emit = function (type) {
		this.publish.apply(this, arguments);
		return this.listeners(type).length > 0;
	};

	this._maxListeners = 10;

	this.setMaxListeners = function (_maxListeners) {
		this._maxListeners = _maxListeners;
	};

	this.hasListeners = function (type) {
		return this._subscribers && this._subscribers[type] && this._subscribers[type].length;
	};

	/**
	 * listenTo for inverting control of #subscribe, #on, etc.
	 * @param {object} obj something extending js.io's lib.PubSub
	 * @param {string} name the event name to listen to
	 * @param {callback} function to run on event
	 * @return {this}
	 */
	this.listenTo = function (obj, name, callback) {
		var listeningTo = this._listeningTo || (this._listeningTo = {});
		var id = obj._listenId || (obj._listenId = uuid(8, 16));
		listeningTo[id] = obj;
		obj.subscribe(name, this, callback);
		return this;
	};

	/**
	 * Stop listening to objects previously passed to `listenTo`.
	 *
	 * @example
	 *     // Stop listening to all events on all objects
	 *     this.stopListening();
	 *
	 *     // Stop listening to all events on `obj`
	 *     this.stopListening(obj);
	 *
	 *     // Stop all of my callbacks for a given event
	 *     this.stopListening(obj, name);
	 *
	 *     // Stop a single callback from firing
	 *     this.stopListening(obj, name, callback);
	 *
	 * @param {object} [obj] object extending lib.PubSub and using listenTo
	 * @param {string} [name] the event name to listen to
	 * @param {callback} [callback] function to stop running
	 * @return {this}
	 */
	this.stopListening = function (obj, name, callback) {
		var events, names, retain, i, j, k, l, ev;
		var listeningTo = this._listeningTo;
		if (!listeningTo) {
			return this;
		}

		logger.log(obj);
		var remove = !name && !callback;
		if (obj) {
			(listeningTo = {})[obj._listenId] = obj;
		}

		for (var id in listeningTo) {
			obj = listeningTo[id];

			names = name ? [name] : Object.keys(obj._subscribers);
			for (i = 0, l = names.length; i < l; i++) {
				name = names[i];
				if (events = obj._subscribers[name]) {
					obj._subscribers[name] = retain = [];
					for (j = 0, k = events.length; j < k; j++) {
						ev = events[j];
						if ((callback && callback !== ev._method) ||
								(this && this !== ev._ctx)) {
							retain.push(ev);
						}
					}
					if (!retain.length) delete obj._subscribers[name];
				}
			}
			if (remove) {
				delete this._listeningTo[id];
			}
		}
		return this;
	};
});

<commit_msg>removelistener updated to clear chaining cbs<commit_after>/**
 * Summary: inherit from lib.PubSub if a class wants publish/subscribe ability
 * Methods:
 *  - publish(signal, args...) - all subscribers to signal will be called
 *     with the list of arguments provided.
 *  - subscribe(signal, ctx, method, args...) - register a bound method
 *     to a signal.  Any args that are passed in will be the first args
 *     when the method is invoked during a publish.
 *  Usage notes: There is one special signal '__any'.  Any subscribers to
 *     '__any' will be called on every publish with the first publish
 *     argument being the signal itself (after any args passed in during
 *     the corresponding subscribe).
 *     Calling the super constructor is not required for descendants of
 *     lib.PubSub.
 */

jsio('import lib.Callback as Callback');
from ..std.uuid import uuid;

var ctx = jsio.__env.global,
	SLICE = Array.prototype.slice;

exports = Class(function () {

	this.init = function () {};

	this.publish = function (signal) {
		if (this._subscribers) {
			var args = SLICE.call(arguments, 1);
			if (this._subscribers.__any) {
				var anyArgs = [signal].concat(args),
					subs = this._subscribers.__any.slice(0);
				for(var i = 0, sub; sub = subs[i]; ++i) {
					sub.apply(ctx, anyArgs);
				}
			}

			if (!this._subscribers[signal]) {
				return this;
			}

			var subs = this._subscribers[signal].slice(0);
			for (var i = 0, sub; sub = subs[i]; ++i) {
				sub.apply(ctx, args);
			}
		}
		return this;
	};

	this.subscribe = function (signal, ctx, method) {
		var cb;
		if (arguments.length == 2) {
			cb = ctx;
		} else {
			cb = bind.apply(GLOBAL, SLICE.call(arguments, 1));
			cb._ctx = ctx; // references for unsubscription
			cb._method = method;
		}

		var s = this._subscribers || (this._subscribers = {});
		(s[signal] || (s[signal] = [])).push(cb);
		return this;
	};

	this.subscribeOnce = function (signal, ctx, method) {
		var args = arguments,
			cb = bind(this, function () {
				this.unsubscribe(signal, cb);
				if (args.length == 2) {
					ctx.apply(GLOBAL, arguments);
				} else {
					bind.apply(GLOBAL, SLICE.call(args, 1))
						.apply(GLOBAL, arguments);
				}
			});

		if (args.length >= 3) {
			cb._ctx = ctx;
			cb._method = method;
		}

		return this.subscribe(signal, cb);
	};

	// If no method is specified, all subscriptions with a callback context
	// of ctx will be removed.

	this.unsubscribe = function (signal, ctx, method) {
		if (!this._subscribers || !this._subscribers[signal]) {
			return this;
		}
		var subs = this._subscribers[signal];
		for (var i = 0, c; c = subs[i]; ++i) {
			if (c == ctx || c._ctx == ctx && (!method || c._method == method)) {
				subs.splice(i--, 1);
			}
		}
		return this;
	};

	/**
	 * EventEmitter-style API
	 * http://nodejs.org/api/events.html
	 */

	this.listeners = function (type) {
		this._subscribers = (this._subscribers ? this._subscribers : {});
		return (this.hasOwnProperty.call(this._subscribers, type))
			? this._subscribers[type]
			: (this._subscribers[type] = []);
	};

	this.addListener = this.on = function (type, f) {
		if (this.listeners(type).length + 1 > this._maxListeners && this._maxListeners !== 0) {
			if (typeof console !== "undefined") {
				console.warn("Possible EventEmitter memory leak detected. " + this._subscribers[type].length + " listeners added. Use emitter.setMaxListeners() to increase limit.");
			}
		}
		this.emit("newListener", type, f);
		return this.subscribe(type, this, f);
	};

	this.once = function (type, f) {
		return this.subscribeOnce(type, this, f);
	};

        this.chain = function (evnt, func) {
                var i,
                        cbs = this._callbacks || (this._callbacks = {}),
                        callback = new Callback(),
                        next = bind(this, function (val, cancel) {
                                var cb = this._callbacks[evnt][i] || {
                                        // i is pointing to the end of the queue, so creating custom cb object.
                                        fire: bind(this, function (val, cancel) {
                                                // call pending callbacks from the next event.

                                                var current = this._callbacks[evnt],
                                                        last = current[i];

                                                // if we are chaining a second signal, that mapping cb will be added
                                                // to the end of current event's queue, which becomes i'th value.
                                                if (last) {
                                                        last.fire(cancel);
                                                        last.clear();
                                                        // this is to remove the last cb which is just a mapping
                                                        // between event queues.
                                                        current.pop();
                                                }
                                                // remove current event
                                                this._activeCBs.shift();
                                        })
                                };

                                // execution of next function in the queue can be aborted
                                // by passing true as a paramter to the cb.
                                if (cancel) {
                                        // even if we want to cancel, we need to fire so that
                                        // we can reset all the callbacks
                                        cb.fire(val, cancel);
                                } else {
                                        // call the registered callback function with value and
                                        // fire function.
                                        // binding val to fire so that next function in the chain will also
                                        // get the value.
                                        func(val, bind(cb, cb.fire, val));
                                }

                                callback.reset();
                        });

                callback.run(next);

                if (!cbs[evnt]) {
                        // we need to register only once, remaining will be taken care
                        // by the next function.
                        cbs[evnt] = [];
                        this.on(evnt, bind(this, function (val) {
                                var active_cbs = this._activeCBs || (this._activeCBs = []),
					len = active_cbs.length,
					pending, last;

                                // add to queue.
                                // this is needed for multi signal chaining
                                active_cbs.push(evnt);
                                if (len === 0) {

                                        // if there is no active function, fire cb immedietly.
                                        callback.fire(val);
                                } else {
                                        // some other execution is ongoing, add to the queue.
                                        last = active_cbs[len - 1];
                                        pending = new Callback();
                                        pending.run(bind(callback, callback.fire, val));
                                        // add to the end of last event's queue
                                        this._callbacks[last].push(pending);
                                }
                        }));
                }
                i = cbs[evnt].push(callback);
        };

	this.removeListener = function (type, f) {
		this.unsubscribe(type, this, f);
		return this;
	};

	this.removeAllListeners = function (type) {
		if (this._callbacks) {
			for (var evnt in this._callbacks) {
				if (type == null || type == evnt) {
					delete this._callbacks[evnt];
				}
			}
		}

		if (this._activeCBs) {
			if (type == null) {
				this._activeCBs = []
			} else {
				this._activeCBs = this._activeCBs.filter(function (event) {
					return event !== type;
				});
			}
		}

		if (this._subscribers) {
			for (var k in this._subscribers) {
				if (type == null || type == k) {
					delete this._subscribers[k];
				}
			}
		}
		return this;
	};

	this.emit = function (type) {
		this.publish.apply(this, arguments);
		return this.listeners(type).length > 0;
	};

	this._maxListeners = 10;

	this.setMaxListeners = function (_maxListeners) {
		this._maxListeners = _maxListeners;
	};

	this.hasListeners = function (type) {
		return this._subscribers && this._subscribers[type] && this._subscribers[type].length;
	};

	/**
	 * listenTo for inverting control of #subscribe, #on, etc.
	 * @param {object} obj something extending js.io's lib.PubSub
	 * @param {string} name the event name to listen to
	 * @param {callback} function to run on event
	 * @return {this}
	 */
	this.listenTo = function (obj, name, callback) {
		var listeningTo = this._listeningTo || (this._listeningTo = {});
		var id = obj._listenId || (obj._listenId = uuid(8, 16));
		listeningTo[id] = obj;
		obj.subscribe(name, this, callback);
		return this;
	};

	/**
	 * Stop listening to objects previously passed to `listenTo`.
	 *
	 * @example
	 *     // Stop listening to all events on all objects
	 *     this.stopListening();
	 *
	 *     // Stop listening to all events on `obj`
	 *     this.stopListening(obj);
	 *
	 *     // Stop all of my callbacks for a given event
	 *     this.stopListening(obj, name);
	 *
	 *     // Stop a single callback from firing
	 *     this.stopListening(obj, name, callback);
	 *
	 * @param {object} [obj] object extending lib.PubSub and using listenTo
	 * @param {string} [name] the event name to listen to
	 * @param {callback} [callback] function to stop running
	 * @return {this}
	 */
	this.stopListening = function (obj, name, callback) {
		var events, names, retain, i, j, k, l, ev;
		var listeningTo = this._listeningTo;
		if (!listeningTo) {
			return this;
		}

		logger.log(obj);
		var remove = !name && !callback;
		if (obj) {
			(listeningTo = {})[obj._listenId] = obj;
		}

		for (var id in listeningTo) {
			obj = listeningTo[id];

			names = name ? [name] : Object.keys(obj._subscribers);
			for (i = 0, l = names.length; i < l; i++) {
				name = names[i];
				if (events = obj._subscribers[name]) {
					obj._subscribers[name] = retain = [];
					for (j = 0, k = events.length; j < k; j++) {
						ev = events[j];
						if ((callback && callback !== ev._method) ||
								(this && this !== ev._ctx)) {
							retain.push(ev);
						}
					}
					if (!retain.length) delete obj._subscribers[name];
				}
			}
			if (remove) {
				delete this._listeningTo[id];
			}
		}
		return this;
	};
});

<|endoftext|>


<commit_before><commit_msg>Naming changes.<commit_after><|endoftext|>