<commit_before>var nodespec = require('./common');

var AssertionError = require('assert').AssertionError;

var Example = require('../lib/example').Example;
var SingleResult = require('../lib/result').SingleResult;
var Pending = require('../lib/exceptions').Pending;
var context = require('../lib/context');

nodespec.describe("Example", function() {
    this.subject("example", function() {
        return new Example("example description", this.options, this.block);
    });
    this.subject("options", function() {
        return {group: this.group, nodespec: this.nodespec, deps: this.deps};
    });
    this.subject("deps", function() {
        return {
            SingleResult: SingleResult,
            Context: context.Context,
            Pending: Pending
        };
    });
    this.subject("block", function() {
        return this.sinon.spy();
    });
    this.subject("group", function() {
        var group = new Object;
        group.full_description = "group description";
        group.before_hooks = [];
        group.after_hooks = [];
        group.subjects = [];
        return group;
    });
    this.subject("nodespec", function() {
        return nodespec("target for testing");
    });
    this.after(function() { this.nodespec.abandon(); });
    this.describe("initialisation", function() {
        this.example("should have description", function() {
            this.assert.equal(this.example.description, "example description");
        });
        this.example("timeout defaults to Example.DEFAULT_TIMEOUT", function() {
            this.sinon.stub(Example, "DEFAULT_TIMEOUT", 9);
            this.assert.equal(this.example.timeout, 9);
        });
        this.context("timeout specififed in options", function() {
            this.subject("example", function() {
                this.options.timeout = 99;
                return new Example("custom timeout", this.options, this.block);
            });
            this.example("timeout overridden", function() {
                this.assert.equal(this.example.timeout, 99);
            });
        });
        this.example("group taken from options", function() {
            this.assert.strictEqual(this.example.group, this.group);
        });
        this.example("nodespec taken from options", function() {
            this.assert.strictEqual(this.example.group, this.group);
        });
        this.example("full_description built from group", function() {
            this.assert.equal(this.example.full_description,
                              "group description example description");
        });
        this.example("file and line of initialiser recorded", function() {
            // This would normally be the group.example call
            // that defines the test
            this.assert.equal(this.example.file_path, __filename);
            this.assert.equal(this.example.line_number, 12);
        });
        this.example("should have block", function() {
            this.assert.strictEqual(this.example.block, this.block);
        });
        this.context("called without block", function() {
            this.subject("example", function() {
                return new Example("no block", this.options);
            });
            this.example("should not have block", function() {
                this.assert.equal(this.example.block, undefined);
            });
            this.example("should have is_pending = true", function() {
                this.assert.equal(this.example.is_pending, true);
            });
        })
    });
    this.describe("timeout_after", function() {
        this.example("can modify timeout", function() {
            this.example.timeout_after(7);
            this.assert.equal(this.example.timeout, 7);
        });
    });
    this.describe("exec", function() {
        this.subject("context", function() {
            var context = new Object;
            context._setup_done = this.sinon.spy(function(done) {
                if (done) { context.done = done; }
            });
            context.check_expected_assertions = this.sinon.stub();
            return context;
        });
        this.subject("emitter", function() {
            var emitter = new Object;
            emitter.emit = this.sinon.spy();
            return emitter;
        });
        this.before(function() {
            var ctx = this.context;
            this.ctx_cls = this.sinon.stub(context, 'Context', function() {
                return ctx;
            });
            this.ctx_cls.prototype = context.Context.prototype;
            this.deps.Context = this.ctx_cls;
        });
        this.example("should create context using nodespec", function(test) {
            test.expect(3);
            test.example.exec(test.emitter, function() {
                test.sinon.assert.calledOnce(test.ctx_cls);
                var call = test.ctx_cls.getCall(0);
                test.assert.ok(call.thisValue instanceof context.Context);
                test.assert.strictEqual(call.args[0], test.nodespec);
                test.done();
            });
        });
        this.context("non-async block", function() {
            this.subject("block", function() {
                return this.sinon.spy();
            });
            sync_exec_behaviour(this, {
                type: "pass",
                event: "examplePass"
            });
        });
        this.context("non-async block that throws AssertionError", function() {
            this.subject("block", function() {
                var ex = this.exception;
                return this.sinon.spy(function() { throw ex; });
            });
            this.subject("exception", function() {
                return new AssertionError({message: "fail"});
            });
            sync_exec_behaviour(this, {
                type: "fail",
                event: "exampleFail",
                error: "exception"
            });
        });
        this.context("non-async block that raises Pending", function() {
            this.subject("block", function() {
                var ex = this.exception;
                return this.sinon.spy(function() { throw ex; });
            });
            this.subject("exception", function() {
                return new Pending("reason");
            });
            sync_exec_behaviour(this, {
                type: "pend",
                event: "examplePend",
                error: "exception"
            });
        });
        this.context("non-async block with ordinary error", function() {
            this.subject("block", function() {
                var ex = this.exception;
                return this.sinon.spy(function() { throw ex; });
            });
            this.subject("exception", function() {
                return new Error("epic fail");
            });
            sync_exec_behaviour(this, {
                type: "error",
                event: "exampleError",
                error: "exception"
            });
        });
        this.context("async block", function() {
            this.subject("block", function() {
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    t.done();
                };
            });
            async_exec_behaviour(this, {
                type: "pass",
                event: "examplePass"
            });
        });
        this.context("async block that throws AssertionError", function() {
            this.subject("block", function() {
                var ex = this.exception;
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    process.nextTick(function() {
                        throw ex;
                    });
                };
            });
            var group_name = this.description;
            this.subject("exception", function() {
                return new AssertionError({message: group_name});
            });
            async_exec_behaviour(this, {
                type: "fail",
                event: "exampleFail",
                error: "exception"
            });
            this.example("should return fail result", function(test) {
                test.expect(3);
                test.example.exec(test.emitter, function(err, result) {
                    test.assert.equal(err, null);
                    test.assert.ok(result instanceof SingleResult);
                    test.assert.equal(result.type, "fail");
                    test.done();
                });
            });
        });
        this.context("async block that doesn't call done", function() {
            this.subject("block", function() {
                var test = this;
                test.sinon.useFakeTimers();
                test.block_spy = this.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    process.nextTick(function() {
                        test.sinon.clock.tick(5100);
                    });
                };
            });
            this.example("should error out after timeout", function(test) {
                test.expect(1);
                test.example.exec(test.emitter, function(err, result) {
                    test.assert.equal(result.type, "error");
                    test.done();
                }).timeout_after(6);
            });
        });
    });
});
nodespec.exec();

function sync_exec_behaviour(group, options) {
    group.example("should run block in context", function(test) {
        test.expect(3);
        test.example.exec(test.emitter, function() {
            test.sinon.assert.calledOnce(test.block);
            var call = test.block.getCall(0);
            test.assert.strictEqual(call.thisValue, test.context);
            test.assert.equal(call.args.length, 0);
            test.done();
        });
    });
    exec_behaviour(group, options);
}
function async_exec_behaviour(group, options) {
    group.example("should call block with context", function(test) {
        test.expect(3);
        test.example.exec(test.emitter, function() {
            test.sinon.assert.calledOnce(test.block_spy);
            var call = test.block_spy.getCall(0);
            test.assert.notStrictEqual(call.thisValue, test.context);
            test.assert.strictEqual(call.args[0], test.context);
            test.done();
        });
    });
    exec_behaviour(group, options);
}
function exec_behaviour(group, options) {
    var type = options.type, event = options.event, error = options.error;
    group.example("should return "+type+" result", function(test) {
        test.expect(3);
        test.example.exec(test.emitter, function(err, result) {
            test.assert.equal(err, null);
            test.assert.ok(result instanceof SingleResult);
            test.assert.equal(result.type, type);
            test.done();
        });
    });
    group.example("should emit events", function(test) {
        test.expect(9);
        test.example.exec(test.emitter, function(err, result) {
            test.sinon.assert.calledThrice(test.emitter.emit);
            // exampleStart(example)
            var c1 = test.emitter.emit.getCall(0);
            test.assert.equal(c1.args[0], "exampleStart");
            test.assert.equal(c1.args[1], test.example);
            // exampleComplete(example, result)
            var c2 = test.emitter.emit.getCall(1);
            test.assert.equal(c2.args[0], "exampleComplete");
            test.assert.equal(c2.args[1], test.example);
            test.assert.equal(c2.args[2], result);
            // example<event>(example, error)
            var c3 = test.emitter.emit.getCall(2);
            test.assert.equal(c3.args[0], event);
            test.assert.equal(c3.args[1], test.example);
            test.assert.equal(c3.args[2], error ? test[error] : error);
            test.done();
        })
    });
}
<commit_msg>More example execution specs<commit_after>var nodespec = require('./common');

var AssertionError = require('assert').AssertionError;

var Example = require('../lib/example').Example;
var SingleResult = require('../lib/result').SingleResult;
var Pending = require('../lib/exceptions').Pending;
var context = require('../lib/context');

nodespec.describe("Example", function() {
    this.subject("example", function() {
        return new Example("example description", this.options, this.block);
    });
    this.subject("options", function() {
        return {group: this.group, nodespec: this.nodespec, deps: this.deps};
    });
    this.subject("deps", function() {
        return {
            SingleResult: SingleResult,
            Context: context.Context,
            Pending: Pending
        };
    });
    this.subject("block", function() {
        return this.sinon.spy();
    });
    this.subject("group", function() {
        var group = new Object;
        group.full_description = "group description";
        group.before_hooks = [];
        group.after_hooks = [];
        group.subjects = [];
        return group;
    });
    this.subject("nodespec", function() {
        return nodespec("target for testing");
    });
    this.after(function() { this.nodespec.abandon(); });
    this.describe("initialisation", function() {
        this.example("should have description", function() {
            this.assert.equal(this.example.description, "example description");
        });
        this.example("timeout defaults to Example.DEFAULT_TIMEOUT", function() {
            this.sinon.stub(Example, "DEFAULT_TIMEOUT", 9);
            this.assert.equal(this.example.timeout, 9);
        });
        this.context("timeout specififed in options", function() {
            this.subject("example", function() {
                this.options.timeout = 99;
                return new Example("custom timeout", this.options, this.block);
            });
            this.example("timeout overridden", function() {
                this.assert.equal(this.example.timeout, 99);
            });
        });
        this.example("group taken from options", function() {
            this.assert.strictEqual(this.example.group, this.group);
        });
        this.example("nodespec taken from options", function() {
            this.assert.strictEqual(this.example.group, this.group);
        });
        this.example("full_description built from group", function() {
            this.assert.equal(this.example.full_description,
                              "group description example description");
        });
        this.example("file and line of initialiser recorded", function() {
            // This would normally be the group.example call
            // that defines the test
            this.assert.equal(this.example.file_path, __filename);
            this.assert.equal(this.example.line_number, 12);
        });
        this.example("should have block", function() {
            this.assert.strictEqual(this.example.block, this.block);
        });
        this.context("called without block", function() {
            this.subject("example", function() {
                return new Example("no block", this.options);
            });
            this.example("should not have block", function() {
                this.assert.equal(this.example.block, undefined);
            });
            this.example("should have is_pending = true", function() {
                this.assert.equal(this.example.is_pending, true);
            });
        })
    });
    this.describe("timeout_after", function() {
        this.example("can modify timeout", function() {
            this.example.timeout_after(7);
            this.assert.equal(this.example.timeout, 7);
        });
    });
    this.describe("exec", function() {
        this.subject("context", function() {
            var context = new Object;
            context._setup_done = this.sinon.spy(function(done) {
                if (done) { context.done = done; }
            });
            context.check_expected_assertions = this.sinon.stub();
            return context;
        });
        this.subject("emitter", function() {
            var emitter = new Object;
            emitter.emit = this.sinon.spy();
            return emitter;
        });
        this.before(function() {
            var ctx = this.context;
            this.ctx_cls = this.sinon.stub(context, 'Context', function() {
                return ctx;
            });
            this.ctx_cls.prototype = context.Context.prototype;
            this.deps.Context = this.ctx_cls;
        });
        this.example("should create context using nodespec", function(test) {
            test.expect(3);
            test.example.exec(test.emitter, function() {
                test.sinon.assert.calledOnce(test.ctx_cls);
                var call = test.ctx_cls.getCall(0);
                test.assert.ok(call.thisValue instanceof context.Context);
                test.assert.strictEqual(call.args[0], test.nodespec);
                test.done();
            });
        });
        this.context("no block", function() {
            this.subject("block", function() {
                return undefined;
            });
            exec_behaviour(this, {
                type: "pend",
                event: "examplePend"
            });
        });
        this.context("non-async block", function() {
            this.subject("block", function() {
                return this.sinon.spy();
            });
            sync_exec_behaviour(this, {
                type: "pass",
                event: "examplePass"
            });
        });
        this.context("non-async block that throws AssertionError", function() {
            this.subject("block", function() {
                var ex = this.exception;
                return this.sinon.spy(function() { throw ex; });
            });
            this.subject("exception", function() {
                return new AssertionError({message: "fail"});
            });
            sync_exec_behaviour(this, {
                type: "fail",
                event: "exampleFail",
                error: "exception"
            });
        });
        this.context("non-async block that raises Pending", function() {
            this.subject("block", function() {
                var ex = this.exception;
                return this.sinon.spy(function() { throw ex; });
            });
            this.subject("exception", function() {
                return new Pending("reason");
            });
            sync_exec_behaviour(this, {
                type: "pend",
                event: "examplePend",
                error: "exception"
            });
        });
        this.context("non-async block with ordinary error", function() {
            this.subject("block", function() {
                var ex = this.exception;
                return this.sinon.spy(function() { throw ex; });
            });
            this.subject("exception", function() {
                return new Error("epic fail");
            });
            sync_exec_behaviour(this, {
                type: "error",
                event: "exampleError",
                error: "exception"
            });
        });
        this.context("async block", function() {
            this.subject("block", function() {
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    t.done();
                };
            });
            async_exec_behaviour(this, {
                type: "pass",
                event: "examplePass"
            });
        });
        this.context("async block throwing async AssertionError", function() {
            this.subject("block", function() {
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    process.nextTick(function() {
                        throw test.exception;
                    });
                };
            });
            this.subject("exception", function() {
                return new AssertionError({message: "block failing assertion"});
            });
            async_exec_behaviour(this, {
                type: "fail",
                event: "exampleFail",
                error: "exception"
            });
        });
        this.context("async block throwing sync AssertionError", function() {
            this.subject("block", function() {
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    throw test.exception;
                };
            });
            this.subject("exception", function() {
                return new AssertionError({message: "block failing assertion"});
            });
            async_exec_behaviour(this, {
                type: "fail",
                event: "exampleFail",
                error: "exception"
            });
        });
        this.context("async block throwing async Pending", function() {
            this.subject("block", function() {
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    process.nextTick(function() {
                        throw test.exception;
                    });
                };
            });
            this.subject("exception", function() {
                return new Pending("test not implemented");
            });
            async_exec_behaviour(this, {
                type: "pend",
                event: "examplePend",
                error: "exception"
            });
        });
        this.context("async block throwing sync Pending", function() {
            this.subject("block", function() {
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    throw test.exception;
                };
            });
            this.subject("exception", function() {
                return new Pending("test not implemented");
            });
            async_exec_behaviour(this, {
                type: "pend",
                event: "examplePend",
                error: "exception"
            });
        });
        this.context("async block throwing async Error", function() {
            this.subject("block", function() {
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    process.nextTick(function() {
                        throw test.exception;
                    });
                };
            });
            this.subject("exception", function() {
                return new Error("arbitrary error");
            });
            async_exec_behaviour(this, {
                type: "error",
                event: "exampleError",
                error: "exception"
            });
        });
        this.context("async block throwing sync Error", function() {
            this.subject("block", function() {
                var test = this;
                test.block_spy = test.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    throw test.exception;
                };
            });
            this.subject("exception", function() {
                return new Error("arbitrary error");
            });
            async_exec_behaviour(this, {
                type: "error",
                event: "exampleError",
                error: "exception"
            });
        });
        this.context("async block that doesn't call done", function() {
            this.subject("block", function() {
                var test = this;
                test.sinon.useFakeTimers();
                test.block_spy = this.sinon.spy();
                return function(t) {
                    test.block_spy.apply(this, arguments);
                    process.nextTick(function() {
                        test.sinon.clock.tick(4000);
                    });
                };
            });
            this.before(function() {
                this.example.timeout_after(3.5);
            });
            this.example("should error out after timeout", function(test) {
                test.expect(1);
                test.example.exec(test.emitter, function(err, result) {
                    test.assert.equal(result.type, "error");
                    test.done();
                })
            });
            this.example("should emit events", function(test) {
                test.expect(10);
                test.example.exec(test.emitter, function(err, result) {
                    test.sinon.assert.calledThrice(test.emitter.emit);
                    var c1 = test.emitter.emit.getCall(0);
                    test.assert.equal(c1.args[0], "exampleStart");
                    test.assert.equal(c1.args[1], test.example);
                    var c2 = test.emitter.emit.getCall(1);
                    test.assert.equal(c2.args[0], "exampleComplete");
                    test.assert.equal(c2.args[1], test.example);
                    test.assert.equal(c2.args[2], result);
                    var c3 = test.emitter.emit.getCall(2);
                    test.assert.equal(c3.args[0], "exampleError");
                    test.assert.equal(c3.args[1], test.example);
                    test.assert.ok(c3.args[2] instanceof Error);
                    test.assert.ok(
                        /done\(\) not called/.test(c3.args[2].message)
                    );
                    test.done();
                })
            });
        });
    });
});
nodespec.exec();

function sync_exec_behaviour(group, options) {
    group.example("should run block in context", function(test) {
        test.expect(3);
        test.example.exec(test.emitter, function() {
            test.sinon.assert.calledOnce(test.block);
            var call = test.block.getCall(0);
            test.assert.strictEqual(call.thisValue, test.context);
            test.assert.equal(call.args.length, 0);
            test.done();
        });
    });
    exec_behaviour(group, options);
}
function async_exec_behaviour(group, options) {
    group.example("should call block with context", function(test) {
        test.expect(3);
        test.example.exec(test.emitter, function() {
            test.sinon.assert.calledOnce(test.block_spy);
            var call = test.block_spy.getCall(0);
            test.assert.notStrictEqual(call.thisValue, test.context);
            test.assert.strictEqual(call.args[0], test.context);
            test.done();
        });
    });
    exec_behaviour(group, options);
}
function exec_behaviour(group, options) {
    var type = options.type, event = options.event, error = options.error;
    group.example("should return "+type+" result", function(test) {
        test.expect(3);
        test.example.exec(test.emitter, function(err, result) {
            test.assert.equal(err, null);
            test.assert.ok(result instanceof SingleResult);
            test.assert.equal(result.type, type);
            test.done();
        });
    });
    group.example("should emit events", function(test) {
        test.expect(9);
        test.example.exec(test.emitter, function(err, result) {
            test.sinon.assert.calledThrice(test.emitter.emit);
            // exampleStart(example)
            var c1 = test.emitter.emit.getCall(0);
            test.assert.equal(c1.args[0], "exampleStart");
            test.assert.equal(c1.args[1], test.example);
            // exampleComplete(example, result)
            var c2 = test.emitter.emit.getCall(1);
            test.assert.equal(c2.args[0], "exampleComplete");
            test.assert.equal(c2.args[1], test.example);
            test.assert.equal(c2.args[2], result);
            // example<event>(example, error)
            var c3 = test.emitter.emit.getCall(2);
            test.assert.equal(c3.args[0], event);
            test.assert.equal(c3.args[1], test.example);
            test.assert.equal(c3.args[2], error ? test[error] : error);
            test.done();
        })
    });
}
<|endoftext|>


<commit_before>// fileTransformer.js

const path = require('path');

module.exports = {
  process(src, filename, config, options) {
    return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
  },
};
<commit_msg>Fix delete semicolons<commit_after>// fileTransformer.js

const path = require('path')

module.exports = {
  process(src, filename, config, options) {
    return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'
  },
}
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

module.exports = function (app, db) {

	app.route('/:url')
		.get(checkIfExisting);

	app.get('/new/:url*', createNewShortUrl);

	function checkIfExisting(req, res){
		var url = process.env.BASE_URL + req.params.url;
		if( url != process.env.BASE_URL + 'favicon.ico') {
			findLink(url, db, res);
		}
	}

	function createLinkHash(url){
		var hash = 0,
			i,
			character,
			length;

		if (url.length === 0) return hash;

		for (i = 0, length = url.length; i < length; i++) {
			character   = url.charCodeAt(i);
			hash  = ((hash << 5) - hash) + character;
			hash |= 0;
		}
		return hash;
	}

	function createNewShortUrl(req, res){
		var url = req.url.slice(5);
		var urlsJson = {};

		if(validLink(url)){
			urlsJson = {
				"original_url" : url,
				"short_url" : process.env.BASE_URL + createLinkHash(url)
			};
		res.send(urlsJson);
		saveLink(urlsJson, db);
		} else {
			urlsJson = { "error" : "Bad url format.  You must have a protocol and site" };
			res.send(urlsJson);
		}
	}

	function findLink(link, db, res){
		var links = db.collection('links');
		links.findOne({ "short_url" : link }, function(err, result){
			if(err) throw err;
			if(result){
				res.redirect(result.original_url);
			} else {
				res.send({ "error" : "No record found" });
			}
		});
	}

	function saveLink(link, db){
		var links = db.collection('links');
		links.save(link, function(err, result){
			if(err) throw err;
			console.log('Saved: ' + link);
		});
	}

	function validLink(url){
		//regex courtesy of https://mathiasbynens.be/demo/url-regex, using the @mattfarina version
		var regex = /^([a-z][a-z0-9\*\-\.]*):\/\/(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@)?(?:(?:[a-z0-9\-\.]|%[0-9a-f]{2})+|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]))(?::[0-9]+)?(?:[\/|\?](?:[\w#!:\.\?\+=&@!$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})*)?$/i;
		return regex.test(url);
	}
};
<commit_msg>Add logging for url search<commit_after>/*jslint node: true */
'use strict';

module.exports = function (app, db) {

	app.route('/:url')
		.get(checkIfExisting);

	app.get('/new/:url*', createNewShortUrl);

	function checkIfExisting(req, res){
		var url = process.env.BASE_URL + req.params.url;
		if( url != process.env.BASE_URL + 'favicon.ico') {
      console.log('Searching for url: ' + url);
			findLink(url, db, res);
		}
	}

	function createLinkHash(url){
		var hash = 0,
			i,
			character,
			length;

		if (url.length === 0) return hash;

		for (i = 0, length = url.length; i < length; i++) {
			character   = url.charCodeAt(i);
			hash  = ((hash << 5) - hash) + character;
			hash |= 0;
		}
		return hash;
	}

	function createNewShortUrl(req, res){
		var url = req.url.slice(5);
		var urlsJson = {};

		if(validLink(url)){
			urlsJson = {
				"original_url" : url,
				"short_url" : process.env.BASE_URL + createLinkHash(url)
			};
		res.send(urlsJson);
		saveLink(urlsJson, db);
		} else {
			urlsJson = { "error" : "Bad url format.  You must have a protocol and site" };
			res.send(urlsJson);
		}
	}

	function findLink(link, db, res){
		var links = db.collection('links');
		links.findOne({ "short_url" : link }, function(err, result){
			if(err) throw err;
			if(result){
				res.redirect(result.original_url);
			} else {
				res.send({ "error" : "No record found" });
			}
		});
	}

	function saveLink(link, db){
		var links = db.collection('links');
		links.save(link, function(err, result){
			if(err) throw err;
			console.log('Saved: ' + link);
		});
	}

	function validLink(url){
		//regex courtesy of https://mathiasbynens.be/demo/url-regex, using the @mattfarina version
		var regex = /^([a-z][a-z0-9\*\-\.]*):\/\/(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@)?(?:(?:[a-z0-9\-\.]|%[0-9a-f]{2})+|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]))(?::[0-9]+)?(?:[\/|\?](?:[\w#!:\.\?\+=&@!$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})*)?$/i;
		return regex.test(url);
	}
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var stew = require('broccoli-stew');
var VersionChecker = require('ember-cli-version-checker');

module.exports = {
  name: 'ember-moment',

  included: function() {
    this._super.included.apply(this, arguments);
  },

  treeForApp: function(tree) {
    var checker = new VersionChecker(this);
    var dep = checker.for('ember', 'bower');

    if (dep.satisfies('>= 1.13.0') || dep.satisfies('>= 2.0.0-beta')) {
      tree = stew.rm(tree, 'initializers/legacy-register.js');
    }

    return tree;
  }
};
<commit_msg>tweaking the version checker to remove legacy initializer<commit_after>'use strict';

var path = require('path');
var stew = require('broccoli-stew');
var VersionChecker = require('ember-cli-version-checker');

module.exports = {
  name: 'ember-moment',

  included: function() {
    this._super.included.apply(this, arguments);
  },

  treeForApp: function(tree) {
    var checker = new VersionChecker(this);
    var dep = checker.for('ember', 'bower');

    if (dep.satisfies('>= 1.13.0 || >= 2')) {
      tree = stew.rm(tree, 'initializers/legacy-register.js');
    }

    return tree;
  }
};
<|endoftext|>


<commit_before>const webpack = require("webpack") // eslint-disable-line no-undef
const WorkboxPlugin = require("workbox-webpack-plugin") // eslint-disable-line no-undef

const settings = window.settings // Replaced by django-npm-mjs
const transpile = window.transpile // Replaced by django-npm-mjs

const baseRule = {
    test: /\.(js|mjs)$/,
    use: {
        loader: "babel-loader",
        options: {
            presets: ["@babel/preset-env"]
        }
    }
}

const predefinedVariables = {
    "settings_STATIC_URL": JSON.stringify(settings.STATIC_URL),
    "settings_REGISTRATION_OPEN": settings.REGISTRATION_OPEN,
    "settings_SOCIALACCOUNT_OPEN": settings.SOCIALACCOUNT_OPEN,
    "settings_PASSWORD_LOGIN": settings.PASSWORD_LOGIN,
    "settings_CONTACT_EMAIL": JSON.stringify(settings.CONTACT_EMAIL),
    "settings_WS_SERVER": settings.WS_SERVER ? JSON.stringify(settings.WS_SERVER) : false,
    "settings_WS_PORT": settings.WS_PORT,
    "settings_IS_FREE": settings.IS_FREE,
    "settings_TEST_SERVER": settings.TEST_SERVER,
    "settings_DEBUG": settings.DEBUG,
    "settings_SOURCE_MAPS": JSON.stringify(settings.SOURCE_MAPS) || false,
    "settings_USE_SERVICE_WORKER": settings.USE_SERVICE_WORKER,
    "settings_JSONPATCH": settings.JSONPATCH,
    "settings_MEDIA_MAX_SIZE": settings.MEDIA_MAX_SIZE,
    "transpile_VERSION": transpile.VERSION
}

if (settings.DEBUG) {
    baseRule.exclude = /node_modules/
    predefinedVariables.staticUrl = `(url => ${settings.STATIC_URL} + url)`
} else {
    predefinedVariables.staticUrl = `(url => ${settings.STATIC_URL} + url + "?v=" + ${transpile.VERSION})`
}

module.exports = { // eslint-disable-line no-undef
    mode: settings.DEBUG ? "development" : "production",
    devtool: settings.SOURCE_MAPS || false,
    module: {
        rules: [
            {
                test: /\.js$/,
                use: ["source-map-loader"],
                enforce: "pre"
            },
            {
                test: /\.(csljson)$/i,
                use: [
                    {
                        loader: "file-loader",
                    },
                ],
            },
            baseRule
        ]
    },
    output: {
        path: transpile.OUT_DIR,
        chunkFilename: "[id]-" + transpile.VERSION + ".js",
        publicPath: transpile.BASE_URL,
        crossOriginLoading: "anonymous"
    },
    plugins: [
        new webpack.DefinePlugin(predefinedVariables),
        new WorkboxPlugin.GenerateSW({
            clientsClaim: true,
            skipWaiting: true,
            inlineWorkboxRuntime: true,
            swDest: "sw.js",
            exclude: [
                "admin_console.js",
                "maintenance.js",
                "schema_export.js",
                "test_caret.js",
                "document_template_admin.js",
                "**/.*",
                "**/*.map",
                "**/*.gz"
            ],
            manifestTransforms: [
                manifestEntries => ({
                    manifest: manifestEntries.map((entry) => {
                        if (!entry.url.includes(String(transpile.VERSION))) {
                            entry.url += `?v=${transpile.VERSION}`
                        }
                        return entry
                    })
                })
            ],
            additionalManifestEntries: transpile.STATIC_FRONTEND_FILES.map(
                url => {
                    if (url.includes("/fonts/")) {
                        return {url, revision: transpile.VERSION.toString()}
                    } else {
                        return {url: `${url}?v=${transpile.VERSION}`, revision: null}
                    }
                }
            ).concat(
                [
                    "/",
                    "/api/jsi18n/",
                    "/manifest.json"
                ].map(
                    url => ({url, revision: transpile.VERSION.toString()})
                )
            ),
        }),
    ],
    entry: transpile.ENTRIES
}
<commit_msg>disable workbox logs<commit_after>const webpack = require("webpack") // eslint-disable-line no-undef
const WorkboxPlugin = require("workbox-webpack-plugin") // eslint-disable-line no-undef

const settings = window.settings // Replaced by django-npm-mjs
const transpile = window.transpile // Replaced by django-npm-mjs

const baseRule = {
    test: /\.(js|mjs)$/,
    use: {
        loader: "babel-loader",
        options: {
            presets: ["@babel/preset-env"]
        }
    }
}

const predefinedVariables = {
    "settings_STATIC_URL": JSON.stringify(settings.STATIC_URL),
    "settings_REGISTRATION_OPEN": settings.REGISTRATION_OPEN,
    "settings_SOCIALACCOUNT_OPEN": settings.SOCIALACCOUNT_OPEN,
    "settings_PASSWORD_LOGIN": settings.PASSWORD_LOGIN,
    "settings_CONTACT_EMAIL": JSON.stringify(settings.CONTACT_EMAIL),
    "settings_WS_SERVER": settings.WS_SERVER ? JSON.stringify(settings.WS_SERVER) : false,
    "settings_WS_PORT": settings.WS_PORT,
    "settings_IS_FREE": settings.IS_FREE,
    "settings_TEST_SERVER": settings.TEST_SERVER,
    "settings_DEBUG": settings.DEBUG,
    "settings_SOURCE_MAPS": JSON.stringify(settings.SOURCE_MAPS) || false,
    "settings_USE_SERVICE_WORKER": settings.USE_SERVICE_WORKER,
    "settings_JSONPATCH": settings.JSONPATCH,
    "settings_MEDIA_MAX_SIZE": settings.MEDIA_MAX_SIZE,
    "transpile_VERSION": transpile.VERSION
}

if (settings.DEBUG) {
    baseRule.exclude = /node_modules/
    predefinedVariables.staticUrl = `(url => ${settings.STATIC_URL} + url)`
} else {
    predefinedVariables.staticUrl = `(url => ${settings.STATIC_URL} + url + "?v=" + ${transpile.VERSION})`
}

module.exports = { // eslint-disable-line no-undef
    mode: settings.DEBUG ? "development" : "production",
    devtool: settings.SOURCE_MAPS || false,
    module: {
        rules: [
            {
                test: /\.js$/,
                use: ["source-map-loader"],
                enforce: "pre"
            },
            {
                test: /\.(csljson)$/i,
                use: [
                    {
                        loader: "file-loader",
                    },
                ],
            },
            baseRule
        ]
    },
    output: {
        path: transpile.OUT_DIR,
        chunkFilename: "[id]-" + transpile.VERSION + ".js",
        publicPath: transpile.BASE_URL,
        crossOriginLoading: "anonymous"
    },
    plugins: [
        new webpack.DefinePlugin(predefinedVariables),
        new WorkboxPlugin.GenerateSW({
            clientsClaim: true,
            skipWaiting: true,
            inlineWorkboxRuntime: true,
            swDest: "sw.js",
            disableDevLogs: true,
            exclude: [
                "admin_console.js",
                "maintenance.js",
                "schema_export.js",
                "test_caret.js",
                "document_template_admin.js",
                "**/.*",
                "**/*.map",
                "**/*.gz"
            ],
            manifestTransforms: [
                manifestEntries => ({
                    manifest: manifestEntries.map((entry) => {
                        if (!entry.url.includes(String(transpile.VERSION))) {
                            entry.url += `?v=${transpile.VERSION}`
                        }
                        return entry
                    })
                })
            ],
            additionalManifestEntries: transpile.STATIC_FRONTEND_FILES.map(
                url => {
                    if (url.includes("/fonts/")) {
                        return {url, revision: transpile.VERSION.toString()}
                    } else {
                        return {url: `${url}?v=${transpile.VERSION}`, revision: null}
                    }
                }
            ).concat(
                [
                    "/",
                    "/api/jsi18n/",
                    "/manifest.json"
                ].map(
                    url => ({url, revision: transpile.VERSION.toString()})
                )
            ),
        }),
    ],
    entry: transpile.ENTRIES
}
<|endoftext|>


<commit_before>/**
 * 2017-09-15   Tong Yuehong
 */

var device =['/dev/console', '/dev/display'];

function open(dev){
    var index = - 1;
    index = device.indexOf(dev);
    if(index <0){
        console.log('dev is not exit');
    }
    driver[index].open();
    return index;
}

function read(fd){
    return driver[fd].read();
}

function write(fd, content){
    return driver[fd].write(content);
}

function close(fd){
    return driver[fd].close();
}

var driver = [{
    type : '/dev/console',
    open : function (){
        console.log('console is open');
    },

    read : function (){
        console.log('console is read');
    },

    write : function (content){
        console.log(`console ${content}`);
    },

    close : function (){
        console.log('console is close');
    }
},{
    type : '/dev/display',
    open : function (){
        console.log('display is open');
    },

    read : function (){
        console.log('display is open');
    },

    write : function (content){
        console.log(`display ${content}`);
    },

    close : function (){
        console.log('display is close');
    }
}];

var fd = open('/dev/display');
write(fd, 'www');
close(fd);

var fd = open('/dev/console');
write(fd, 'hello');
close(fd);
<commit_msg>驱动（完善）<commit_after>/**
 * 2017-09-15   Tong Yuehong
 */

var device =['/dev/console', '/dev/display'];

function open(dev){
    var index = - 1;
    index = device.indexOf(dev);
    if(index <0){
        console.log(`${dev} is not exit`);
    }
    else{
    driver[index].open();
    return index;
    }
}

function read(fd){
    return driver[fd].read();
}

function write(fd, content){
    return driver[fd].write(content);
}

function close(fd){
    return driver[fd].close();
}

var driver = [{
    type : '/dev/console',
    open : function (){
        console.log('console is open');
    },

    read : function (){
        console.log('console is read');
    },

    write : function (content){
        console.log(`console ${content}`);
    },

    close : function (){
        console.log('console is close');
    }
},{
    type : '/dev/display',
    open : function (){
        console.log('display is open');
    },

    read : function (){
        console.log('display is open');
    },

    write : function (content){
        console.log(`display ${content}`);
    },

    close : function (){
        console.log('display is close');
    }
}];

var fd = open('/dev/display');
if(fd >= 0){
write(fd, 'www');
close(fd);
}

var fd = open('/dev/consol');
if(fd >= 0){
write(fd, 'hello');
close(fd);
}
<|endoftext|>


<commit_before>/* jshint esnext: true */
var data;

var margin = {top: 0, right: 0, bottom: 0, left: 100};
var width = 960 - margin.left - margin.right;
var height = 600 - margin.top - margin.bottom;

var dataMargin = {top: 10, right: 6, bottom: 50, left: 0};
var dataWidth = width - dataMargin.left - dataMargin.right;
var dataHeight = height - dataMargin.top - dataMargin.bottom;

var x_min = 0;
var x_max = 10;
var current_x_min = x_min;

var discrete_mode = false; // this is a kludge to fix centerOn bug

var x = d3.scaleLinear()
  .domain([x_min, x_max])
  .range([dataMargin.left, dataWidth]);

var y = d3.scaleLinear()
  .domain([1, 30])
  .range([dataMargin.top, dataHeight]);

var line = d3.line()
  .curve(d3.curveMonotoneX)
  .x(d => x(d.week))
  .y(d => y(d.rank));

var voronoi = d3.voronoi()
  .x(d => x(d.week))
  .y(d => y(d.rank))
  .size([3200, height]);

var format = d3.format(".01f");

window.onload = function() {
  d3.json('api/rankings/2016', function(error, json) {
    if (error) {
      return console.warn(error);
    }
    data = json.results;
    $('#spinner-container').css('display', 'none');

    var allPoints = [];
    data.forEach(function(d){
      allPoints = allPoints.concat(d.rankings);
    });

    var voronoiData = voronoi.polygons(allPoints);

    // find initial rankings for greensock
    var start_rankings = new Array(30);
    data.forEach(function(team) {
      let rank = team.rankings[0].rank;
      start_rankings[rank - 1] = '.' + team.slug;
    });
    start_rankings.reverse();

    /*
     * D3.js Code
     */
    var outer = d3.select(".chart").append("svg")
        .attr("style", "border: 1px solid black;")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom);

    var inner = outer
      .append("g")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
      .append("svg")
        .attr("width", dataWidth + dataMargin.left + dataMargin.right)
        .attr("height", dataHeight + dataMargin.top + dataMargin.bottom)
      .append('g')
        .attr("transform", `translate(${dataMargin.left}, ${dataMargin.top})`);

    var xAxis = d3.axisBottom(x);

    var gX = outer.append('g')
      .attr('transform', `translate(${margin.left + dataMargin.left}, ${height - margin.bottom - dataMargin.bottom + 5})`)
      .call(xAxis);

    var gY = outer.append('g')
        .attr('transform', `translate(${margin.left}, ${margin.top + dataMargin.top})`);

    var labels = gY.selectAll('.team-label')
      .data(data)
      .enter().append('text')
        .attr('class', d => `${d.slug} team-label`)
        .attr('text-anchor', 'end')
        .attr('transform', d => `translate(0, ${y(d.rankings[current_x_min].rank)})`)
        .text(d => d.name);

    var team = inner.selectAll('.team')
      .data(data)
      .enter().append('g')
        .attr('class', d => `${d.slug} team`)
      .append('path')
        .attr('d', d => line(d.rankings))
        .style('fill', 'none')
        .style('stroke-width', 1.5)
        .style('stroke', d => d.color)
        .attr('natural-color', d => d.color)
        .attr('team', d => d.slug);

    var zoom = d3.zoom()
      .on('zoom', zoomed)
      .on('end', centerOnNearestBase)
      .translateExtent([[0,0], [3200, height + margin.top + margin.bottom]])
      .scaleExtent([1,1]);

    var zoomHandle = inner.append('rect')
      .attr('width', width)
      .attr('height', height)
      .attr('class', 'zoom-handle')
      .call(zoom);

    var voronoiPoly = inner.selectAll('.voronoi')
      .data(voronoiData)
      .enter().append('g')
        .attr('class', d => 'voronoi')
      .append('path')
        .attr('d', d => d ? "M" + d.join("L") + "Z" : null)
        .on('mouseover', highlight(team))
        .on('mouseout', highlightAll);

    function zoomed() {
      team.attr('transform', d3.event.transform);
      voronoiPoly.attr('transform', d3.event.transform);
      gX.call(xAxis.scale(d3.event.transform.rescaleX(x)));

      var x_min = format(x.invert(-d3.event.transform.x));
      var xFloor = Math.floor(x_min);
      var xCeil = Math.ceil(x_min);
      var percent = d3.easeCubic(x_min % 1);

      labels.attr('transform', function(d) {
        var floor = y(d.rankings[xFloor].rank);
        var ceil = y(d.rankings[xCeil].rank);
        var travel = ceil - floor;
        var newY = floor + ( travel * percent );
        return 'translate(0, ' + newY + ')';
      });
    }

    /*
     * Panning Logic
     */
    function centerOnNearestBase() {
      if (discrete_mode) {
        // there's a bug here where if you hit the pan buttons too fast
        // we get into an infinite loop trying to center while another
        // zoom event is happening
        return;
      }
      var base = format(x.invert(-d3.event.transform.x)); // where the left hand of the axis lies
      var roundedBase = format(Math.round(base));
      if (Math.abs(x(roundedBase - base)) > 1)  {
        // if we're more than 1 pixel off
        centerOn(roundedBase);
      }
    }

    function centerOn(base) {
      var mX = x(base);
      var t = d3.zoomIdentity.translate(-mX, 0);
      zoomHandle
        .transition()
        .duration(200)
        .call(zoom.transform, t);
    }

    // Desktop Panning Controls
    var leftButton = d3.select('#left')
      .on('click', function() {
        discrete_mode = true;
        if (current_x_min > 0) {
          current_x_min--;
          console.log('moving to ' + current_x_min);
          centerOn(current_x_min);
        }
      });
    var rightButton = d3.select('#right')
      .on('click', function() {
        discrete_mode = true;
        current_x_min++;
        console.log('moving to ' + current_x_min);
        centerOn(current_x_min);
      });

    // Animate all this garbage in
    TweenMax.staggerFrom(start_rankings, 1, {opacity: 0}, 0.025);

  });

  function highlight(team) {
    return function(team) {
      if (team) {
        var slug = team.data.slug;
        TweenMax.staggerTo($('.team path'), 0, {
          cycle: {
            'stroke': (i, elem) => (slug === elem.getAttribute('team')) ? elem.getAttribute('natural-color') : 'gray',
            'stroke-width': (i, elem) => (slug === elem.getAttribute('team')) ? 3 : 1
          }
        }, 0.001);
      }
    };
  }

  function highlightAll() {
    TweenMax.staggerTo($('.team path'), 0, {
      cycle: {
        'stroke': (i, elem) => elem.getAttribute('natural-color'),
      },
      'stroke-width': 1
    });
  }

};
<commit_msg>adding bezier voronoi highlighting<commit_after>/* jshint esnext: true */
var data;

var margin = {top: 0, right: 0, bottom: 0, left: 100};
var width = 960 - margin.left - margin.right;
var height = 600 - margin.top - margin.bottom;

var dataMargin = {top: 10, right: 6, bottom: 50, left: 0};
var dataWidth = width - dataMargin.left - dataMargin.right;
var dataHeight = height - dataMargin.top - dataMargin.bottom;

var x_min = 0;
var x_max = 10;
var current_x_min = x_min;

var discrete_mode = false; // this is a kludge to fix centerOn bug
var pinned = false;

var x = d3.scaleLinear()
  .domain([x_min, x_max])
  .range([dataMargin.left, dataWidth]);

var y = d3.scaleLinear()
  .domain([1, 30])
  .range([dataMargin.top, dataHeight]);

var line = d3.line()
  .curve(d3.curveMonotoneX)
  .x(d => x(d.week))
  .y(d => y(d.rank));

var voronoi = d3.voronoi()
  .x(d => d.x)
  .y(d => d.y)
  .size([3200, height]);

var format = d3.format(".01f");

window.onload = function() {
  d3.json('api/rankings/2016', function(error, json) {
    if (error) {
      return console.warn(error);
    }
    data = json.results;
    $('#spinner-container').css('display', 'none');

    // find initial rankings for greensock
    var start_rankings = new Array(30);
    data.forEach(function(team) {
      let rank = team.rankings[0].rank;
      start_rankings[rank - 1] = '.' + team.slug;
    });
    start_rankings.reverse();

    /*
     * D3.js Code
     */
    var outer = d3.select(".chart").append("svg")
        .attr("style", "border: 1px solid black;")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom);

    var inner = outer
      .append("g")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
      .append("svg")
        .attr("width", dataWidth + dataMargin.left + dataMargin.right)
        .attr("height", dataHeight + dataMargin.top + dataMargin.bottom)
      .append('g')
        .attr("transform", `translate(${dataMargin.left}, ${dataMargin.top})`);

    var xAxis = d3.axisBottom(x);

    var gX = outer.append('g')
      .attr('transform', `translate(${margin.left + dataMargin.left}, ${height - margin.bottom - dataMargin.bottom + 5})`)
      .call(xAxis);

    var gY = outer.append('g')
        .attr('transform', `translate(${margin.left}, ${margin.top + dataMargin.top})`);

    var labels = gY.selectAll('.team-label')
      .data(data)
      .enter().append('text')
        .attr('class', d => `${d.slug} team-label`)
        .attr('text-anchor', 'end')
        .attr('transform', d => `translate(0, ${y(d.rankings[current_x_min].rank)})`)
        .text(d => d.name);

    var team = inner.selectAll('.team')
      .data(data)
      .enter().append('g')
        .attr('class', d => `${d.slug} team`)
      .append('path')
        .attr('d', d => line(d.rankings))
        .style('fill', 'none')
        .style('stroke-width', 1.5)
        .style('stroke', d => d.color)
        .attr('natural-color', d => d.color)
        .attr('team', d => d.slug);

    var zoom = d3.zoom()
      .on('zoom', zoomed)
      .on('end', centerOnNearestBase)
      .translateExtent([[0,0], [3200, height + margin.top + margin.bottom]])
      .scaleExtent([1,1]);

    var zoomHandle = inner.append('rect')
      .attr('width', width)
      .attr('height', height)
      .attr('class', 'zoom-handle')
      .call(zoom);

    var allPoints = generateVoronoiPoints($('.team path'));

    var voronoiData = voronoi.polygons(allPoints);

    var voronoiPoly = inner.selectAll('.voronoi')
      .data(voronoiData)
      .enter().append('g')
        .attr('class', d => 'voronoi')
      .append('path')
        .attr('d', d => d ? "M" + d.join("L") + "Z" : null)
        .on('click', pin(team))
        .on('mouseover', highlight(team))
        .on('mouseout', highlightAll);

    function zoomed() {
      team.attr('transform', d3.event.transform);
      voronoiPoly.attr('transform', d3.event.transform);
      gX.call(xAxis.scale(d3.event.transform.rescaleX(x)));

      var x_min = format(x.invert(-d3.event.transform.x));
      var xFloor = Math.floor(x_min);
      var xCeil = Math.ceil(x_min);
      var percent = d3.easeCubic(x_min % 1);

      labels.attr('transform', function(d) {
        var floor = y(d.rankings[xFloor].rank);
        var ceil = y(d.rankings[xCeil].rank);
        var travel = ceil - floor;
        var newY = floor + ( travel * percent );
        return `translate(0, ${newY})`;
      });
    }

    /*
     * Panning Logic
     */
    function centerOnNearestBase() {
      if (discrete_mode) {
        // there's a bug here where if you hit the pan buttons too fast
        // we get into an infinite loop trying to center while another
        // zoom event is happening
        return;
      }
      var base = format(x.invert(-d3.event.transform.x)); // where the left hand of the axis lies
      var roundedBase = format(Math.round(base));
      if (Math.abs(x(roundedBase - base)) > 1)  {
        // if we're more than 1 pixel off
        centerOn(roundedBase);
      }
    }

    function centerOn(base) {
      var mX = x(base);
      var t = d3.zoomIdentity.translate(-mX, 0);
      zoomHandle
        .transition()
        .duration(200)
        .call(zoom.transform, t);
    }

    // Desktop Panning Controls
    var leftButton = d3.select('#left')
      .on('click', function() {
        discrete_mode = true;
        if (current_x_min > 0) {
          current_x_min--;
          centerOn(current_x_min);
        }
      });
    var rightButton = d3.select('#right')
      .on('click', function() {
        discrete_mode = true;
        current_x_min++;
        centerOn(current_x_min);
      });

    // Animate all this garbage in
    TweenMax.staggerFrom(start_rankings, 1, {opacity: 0}, 0.025);

  });

  function pin(team) {
    pinned = true;
  }

  function highlight(team) {
    return function(team) {
      if (team) {
        var slug = team.data.slug;
        console.log();
        TweenMax.staggerTo($('.team path'), 0, {
          cycle: {
            'stroke': (i, elem) => (slug === elem.getAttribute('team')) ? elem.getAttribute('natural-color') : 'gray',
            'stroke-width': (i, elem) => (slug === elem.getAttribute('team')) ? 3 : 1
          }
        }, 0.001);
      }
    };
  }

  function highlightAll() {
    TweenMax.staggerTo($('.team path'), 0, {
      cycle: {
        'stroke': (i, elem) => elem.getAttribute('natural-color'),
      },
      'stroke-width': 1.5
    });
  }

  function samplePath(pathNode, precision) {
    var pathLength = pathNode.getTotalLength();
    var samples = [];
    for (let sample, sampleLength = 0; sampleLength <= pathLength; sampleLength += precision) {
      sample = pathNode.getPointAtLength(sampleLength);
      samples.push({
        x: sample.x,
        y: sample.y,
        slug: pathNode.__data__.slug // there is surely a better way to get this
      });
    }
    return samples;
  }

  function generateVoronoiPoints(paths) {
    var allPoints = [];
    for (var path of paths) {
      allPoints = allPoints.concat( samplePath(path, 10) );
    }
    return allPoints;
  }

};
<|endoftext|>


<commit_before>/*
 * This file is part of the Soletta Project
 *
 * Copyright (C) 2015 Intel Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var fs = require( "fs" ),
	path = require( "path" );

// List containing the names of source files for the bindings we wish to include.
// Paths are relative to the location of nodejs-bindings-sources.gyp (generated below).
var sources = [
	"main.cc",
	"../src/data.cc",
	"../src/functions/sol-platform-monitors.cc",
	"../src/functions/simple.cc",
	"../src/hijack.cc",
	"../src/sol-uv-integration.c",
	"../src/structures/js-handle.cc"
];

// List containing the names of the header files in which to search for constants and enums
var headers = [
	"sol-platform.h"
];

var oneVariable, match;
for ( oneVariable in process.env ) {

	// If it's an environment variable starting with SOL_CONFIG_ then examine its value
	match = oneVariable.match( /^SOL_CONFIG_(.*)$/ ) ? process.env[ oneVariable ] : null;

	// If the value is "y" then add files based on the name of the variable, removing the prefix
	match = match && ( match === "y" ) ? oneVariable.replace( /^SOL_CONFIG_/, "" ) : null;

	switch( match ) {
		case "OIC":
            /* FIXME: uncomment when the bindings get up-to-date with
             * the API again --

			sources = sources.concat( [
				"../src/functions/oic-client-common.cc",
				"../src/functions/oic-client-discovery.cc",
				"../src/functions/oic-client-resource-ops.cc",
				"../src/functions/oic-server.cc",
				"../src/structures/device-id.cc",
				"../src/structures/oic-client.cc",
				"../src/structures/oic-map.cc"
			] );
			headers = headers.concat( [
				"sol-oic-client.h",
				"sol-oic.h"
			] );

            */
			break;
		case "NETWORK":
			sources = sources.concat( [
				"../src/functions/sol-network.cc",
				"../src/structures/network.cc"
			] );
			headers = headers.concat( [
				"sol-coap.h",
				"sol-network.h"
			] );
			break;
		case "USE_GPIO":
			sources = sources.concat( [
				"../src/functions/gpio.cc",
				"../src/structures/sol-js-gpio.cc"
			] );
			headers = headers.concat( [
				"sol-gpio.h"
			] );
			break;
		case "USE_AIO":
			sources = sources.concat( [
				"../src/functions/aio.cc",
			] );
			headers = headers.concat( [
				"sol-aio.h"
			] );
			break;
		case "USE_UART":
			/* FIXME: Remove this comment once uart bindings are fixed !
                          sources = sources.concat( [
				"../src/functions/uart.cc",
				"../src/structures/sol-js-uart.cc"
			] );
			headers = headers.concat( [
				"sol-uart.h"
			] );*/
			break;
		case "USE_PWM":
			sources = sources.concat( [
				"../src/functions/pwm.cc",
				"../src/structures/sol-js-pwm.cc"
			] );
			headers = headers.concat( [
				"sol-pwm.h"
			] );
			break;
		case "USE_SPI":
			sources = sources.concat( [
				"../src/functions/spi.cc",
				"../src/structures/sol-js-spi.cc"
			] );
			headers = headers.concat( [
				"sol-spi.h"
			] );
			break;
		case "USE_I2C":
			sources = sources.concat( [
				"../src/functions/i2c.cc"
			] );
			headers = headers.concat( [
				"sol-i2c.h"
			] );
			break;
		default:
			break;
	}
}

fs.writeFileSync( path.join( __dirname, "generated", "header-files-list" ), headers.join( "\n" ) );

fs.writeFileSync( path.join( __dirname, "generated", "nodejs-bindings-sources.gyp" ),
	JSON.stringify( { sources: sources } ) );
<commit_msg>Node.js bindings: Enable UART JS bindings.<commit_after>/*
 * This file is part of the Soletta Project
 *
 * Copyright (C) 2015 Intel Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var fs = require( "fs" ),
	path = require( "path" );

// List containing the names of source files for the bindings we wish to include.
// Paths are relative to the location of nodejs-bindings-sources.gyp (generated below).
var sources = [
	"main.cc",
	"../src/data.cc",
	"../src/functions/sol-platform-monitors.cc",
	"../src/functions/simple.cc",
	"../src/hijack.cc",
	"../src/sol-uv-integration.c",
	"../src/structures/js-handle.cc"
];

// List containing the names of the header files in which to search for constants and enums
var headers = [
	"sol-platform.h"
];

var oneVariable, match;
for ( oneVariable in process.env ) {

	// If it's an environment variable starting with SOL_CONFIG_ then examine its value
	match = oneVariable.match( /^SOL_CONFIG_(.*)$/ ) ? process.env[ oneVariable ] : null;

	// If the value is "y" then add files based on the name of the variable, removing the prefix
	match = match && ( match === "y" ) ? oneVariable.replace( /^SOL_CONFIG_/, "" ) : null;

	switch( match ) {
		case "OIC":
            /* FIXME: uncomment when the bindings get up-to-date with
             * the API again --

			sources = sources.concat( [
				"../src/functions/oic-client-common.cc",
				"../src/functions/oic-client-discovery.cc",
				"../src/functions/oic-client-resource-ops.cc",
				"../src/functions/oic-server.cc",
				"../src/structures/device-id.cc",
				"../src/structures/oic-client.cc",
				"../src/structures/oic-map.cc"
			] );
			headers = headers.concat( [
				"sol-oic-client.h",
				"sol-oic.h"
			] );

            */
			break;
		case "NETWORK":
			sources = sources.concat( [
				"../src/functions/sol-network.cc",
				"../src/structures/network.cc"
			] );
			headers = headers.concat( [
				"sol-coap.h",
				"sol-network.h"
			] );
			break;
		case "USE_GPIO":
			sources = sources.concat( [
				"../src/functions/gpio.cc",
				"../src/structures/sol-js-gpio.cc"
			] );
			headers = headers.concat( [
				"sol-gpio.h"
			] );
			break;
		case "USE_AIO":
			sources = sources.concat( [
				"../src/functions/aio.cc",
			] );
			headers = headers.concat( [
				"sol-aio.h"
			] );
			break;
		case "USE_UART":
			sources = sources.concat( [
				"../src/functions/uart.cc",
				"../src/structures/sol-js-uart.cc"
			] );
			headers = headers.concat( [
				"sol-uart.h"
			] );
			break;
		case "USE_PWM":
			sources = sources.concat( [
				"../src/functions/pwm.cc",
				"../src/structures/sol-js-pwm.cc"
			] );
			headers = headers.concat( [
				"sol-pwm.h"
			] );
			break;
		case "USE_SPI":
			sources = sources.concat( [
				"../src/functions/spi.cc",
				"../src/structures/sol-js-spi.cc"
			] );
			headers = headers.concat( [
				"sol-spi.h"
			] );
			break;
		case "USE_I2C":
			sources = sources.concat( [
				"../src/functions/i2c.cc"
			] );
			headers = headers.concat( [
				"sol-i2c.h"
			] );
			break;
		default:
			break;
	}
}

fs.writeFileSync( path.join( __dirname, "generated", "header-files-list" ), headers.join( "\n" ) );

fs.writeFileSync( path.join( __dirname, "generated", "nodejs-bindings-sources.gyp" ),
	JSON.stringify( { sources: sources } ) );
<|endoftext|>


<commit_before>/*
Copyright (c) 2011, Ideyatech, Inc. All rights reserved.
Code licensed under the BSD License
 */

/**
 * The global namespace.
 */
var IDEYATECH = {};

/**
 * for our widget class
 */
IDEYATECH.widgets = {};

/**
 * Safe javascript logging to Firebug. Copied from:
 * http://www.mario.net.au/blog/better-firebug-and-jquery-logging.html
 *
 */
jQuery.fn.log = function() {
	if (window.console && window.console.log) {
		if (arguments.length) {
			console.log("%o args: %o", this, arguments);
		} else {
			console.log(this);
		}
	}
	return this;
};

/**
 * For adding inline labels on text boxes
 */
jQuery.fn.watermark = function(label) {
    if (IDEYATECH.util.isEmpty(this.val())) {
        this.val(label);
    }
    this.blur(function() {
        if (IDEYATECH.util.isEmpty($(this).val())) {
            $(this).val(label);
        }
    });
    this.focus(function() {
       if ($(this).val() == label) {
           $(this).val('');
       }
    });
};

/**
 * For removing watermark, called before submission of form.
 */
jQuery.fn.cleanmark = function(label) {
    if (this.val() == label) {
        this.val('');
    }
};

/**
 * Provides common utility functions.
 *
 * @class util
 * @namespace IDEYATECH
 */

IDEYATECH.util = function() {

	/**
	 * Private method that replaces response text. This is generally used for
	 * multipart form.
	 *
	 * @param str -
	 *            string response Text
	 * @return newResponseText string
	 */
	var __hackResponse = function(str) {
		/*
		 * hack tags, we use [] instead of <> because of its limitation (the
		 * response text automatically append a closing tag when seeing a tag
		 * inside it
		 */
		str = str.replace(/\[multipart_tr(.*?)\]/gi, "
");
		str = str.replace(/\[\/multipart_tr\]/gi, "
");
		str = str.replace(/\[multipart_td(.*?)\]/gi, "");
		str = str.replace(/\[\/multipart_td\]/gi, "	");
		/* you may need to add another tag replacement here */
		return str;
	};

	/**
	 * Private helper to replace the div with the HTML response args[0] {String}
	 * element to replace args[1] {function} callback function args[2] {boolean}
	 * should javascript be executed
	 */
	var __replace = function(response, args) {
		/*
		 * Notice that when using yConnect.setForm(formObject, true); the
		 * responseText returned by a callback strips improper tags (e.g)
Hello

		 * will become Hello This method will hack the response text, replacing
		 * your customize tags with proper HTML tags Prerequisite: you need to
		 * map your customize tags to our str replace... {o} object response
		 */
		var str = __hackResponse(response);
		var userCallback = args[1];
		IDEYATECH.util.updateInnerHTML(args[0], str);
		if (typeof userCallback == 'function') {
			try {
				userCallback.call();
			} catch (err) {
			}
		}
		if (args[2])
		  	__evaluateJS(str);

	};

	/**
	 * Private helper to append the response as sibling of the div o.argument[0]
	 * {String} element to append o.argument[1] {function} callback function
	 * o.argument[2] {boolean} should javascript be executed
	 */
	var __append = function(response, args) {
		var str = __hackResponse(response);

		var rootId = __getFirstElementId(str, "tr");

		if (IDEYATECH.util.isEmpty(rootId)) {
            //   if no tr with that id, try div
            rootId = __getFirstElementId(str, "div");
        }

		if (!IDEYATECH.util.isEmpty(rootId) && $('#' + rootId).length == 0) {
			var parent = document.getElementById(args[0]);
			var userCallback = args[1];
			if (parent != null)
				IDEYATECH.util.updateInnerHTML(parent.id, parent.innerHTML + str);
			if (typeof userCallback == 'function') {
				try {
					userCallback.call();
				} catch (err) {
				}
			}
			if (args[2])
	  			__evaluateJS(response);
		} else {
			if (!IDEYATECH.util.isEmpty(rootId))
				args[0] = rootId;
			__replace(response, args);
		}
	};

	/**
	 * Private helper to retrieve the first element id in the string
	 */
	var __getFirstElementId = function(str, tag) {
		var matchExp = new RegExp('<' + tag + '[^>]+id="(.\*?)"[^>]*>', 'img');
		var matches = matchExp.exec(str) || [];
		return matches[1];
	};

	/**
	 * Private helper that will evaluate the ajax response
	 */
	var __evaluateJS = function(response) {
		var script = IDEYATECH.util.extractScripts(response);
		eval(script || '');
	};

	var __failure = function(o) {
		IDEYATECH.util.log('Connection failed :: ' + o.statusText);
	};

	return {

		/**
		 * Failsafe logging of messages to firebug console.
		 * @message - message to log
		 */
		log : function(message) {
		    if (window.console && window.console.log) {
		        console.log(message);
		    }
		},

		/**
		 * Work around for innerHTML - replace value of an element
		 *
		 * @id - id of the element
		 * @replacement - new value that will be placed in the element of the
		 *              given id
		 */
		updateInnerHTML : function(id, replacement) {
			// TODO: Verify if this works in IE when replacing tr element
			$('#' + id).html(replacement);
		},

		/**
		 * Checks if a given variable is empty
		 *
		 * @method isEmpty
		 * @param {object}
		 *            variable to check
		 *
		 */
		isEmpty : function(obj) {
			if (obj == null || typeof (obj) == "undefined" || obj.length == 0
					|| obj == "") {
				return true;
			} else
				return false;
		},
		/**
		 * Any spaces entered by the user will be removed
		 *
		 * @method removeSpaces
		 * @param str -
		 *            string to evaluate
		 */
		removeSpaces : function(str) {
			return str.split(' ').join('');
		},
		/**
		 * Extracts the script from a set of result
		 *
		 * @method extractScripts
		 * @param {String}
		 *            string to extract for script
		 */
		extractScripts : function(result) {
			var matchAll = new RegExp('


<commit_before>define([
  'text!missile_command/missile_command.html'
], function(html) {
  "use strict";

  var nuke_launcher = '/pa/units/land/nuke_launcher/nuke_launcher.json'

  var originalSelection = handlers.selection
  handlers.selection = function(payload) {
    var si = payload.spec_ids
    if (Object.keys(si).length == 1) {
      if (si[nuke_launcher] && si[nuke_launcher].length == 1) {
        console.log(si[nuke_launcher])
      }
    }
    originalSelection(payload)
  }

  return {
    ready: function() {
      var container = $(html)
      container.appendTo('body')
      ko.applyBindings(model, container[0])
    }
  }
})
<commit_msg>capture group<commit_after>define([
  'text!missile_command/missile_command.html'
], function(html) {
  "use strict";

  var nuke_launcher = '/pa/units/land/nuke_launcher/nuke_launcher.json'

  var registry = []

  var originalSelection = handlers.selection
  handlers.selection = function(payload) {
    var si = payload.spec_ids
    if (Object.keys(si).length == 1) {
      if (si[nuke_launcher] && si[nuke_launcher].length == 1) {
        var id = si[nuke_launcher][0]
        console.log(id)
        if (!registry.some(function(r) {return r.id == id})) {
          console.log('unknown')
          api.select.captureGroup(id)
          registry.push({id: id})
          console.log(registry)
        }
      }
    }
    originalSelection(payload)
  }

  return {
    ready: function() {
      var container = $(html)
      container.appendTo('body')
      ko.applyBindings(model, container[0])
    }
  }
})
<|endoftext|>


<commit_before>/* ========================================================
 * bootstrap-progressbar v0.2.0
 * ========================================================
 * Copyright 2012 minddust.com
 *
 * bootstrap-progressbar is published under Apache License,
 * Version 2.0 (see LICENSE file).
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 * ======================================================== */

!function( $ ){

    "use strict"

    /* PROGRESSBAR CLASS DEFINITION
     * ============================ */

    var Progressbar = function ( element, options ) {
        this.element = $(element)
        this.options = $.extend({}, $.fn.progressbar.defaults, options)
        this.transition()
    };

    Progressbar.prototype = {

        constructor: Progressbar

        , transition: function () {
            var $this = this.element
                , options = this.options
                , percentage = $this.attr('data-percentage')
                , callback

            if ( !percentage ) return

            if ( options.callback && typeof(options.callback) == 'function' ) callback = options.callback
            else callback = $.fn.progressbar.defaults.callback

            setTimeout(function() {
                $this.css('width', percentage+'%')

                var current_percentage
                    , parent_width

                var progress = setInterval(function() {
                    parent_width = $this.parent().width()
                    current_percentage = Math.round(100 * $this.width() / parent_width)

                    if ( options.display_text ) $this.text(current_percentage +'%')
                    if ( current_percentage >= percentage ) clearInterval(progress)

                    callback(current_percentage)
                }, options.refresh_speed)

            }, options.transition_delay)
        }
    }

    /* PROGRESSBAR PLUGIN DEFINITION
     * ============================= */

    $.fn.progressbar = function ( option ) {
        return this.each(function () {
            var $this = $(this)
                , data = $this.data('progressbar')
                , options = typeof option == 'object' && option
            if (!data) $this.data('progressbar', (data = new Progressbar(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    $.fn.progressbar.defaults = {
        transition_delay: 300
        ,   refresh_speed: 50
        ,   display_text: true
        ,   callback: $.noop
    }

    $.fn.progressbar.Constructor = Progressbar

}( window.jQuery );<commit_msg>added display text switch<commit_after>/* ========================================================
 * bootstrap-progressbar v0.2.0
 * ========================================================
 * Copyright 2012 minddust.com
 *
 * bootstrap-progressbar is published under Apache License,
 * Version 2.0 (see LICENSE file).
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 * ======================================================== */

!function( $ ){

    "use strict"

    /* PROGRESSBAR CLASS DEFINITION
     * ============================ */

    var Progressbar = function ( element, options ) {
        this.element = $(element)
        this.options = $.extend({}, $.fn.progressbar.defaults, options)
        this.transition()
    };

    Progressbar.prototype = {

        constructor: Progressbar

        , transition: function () {
            var $this = this.element
                , options = this.options
                , percentage = $this.attr('data-percentage')
                , amount_part = $this.attr('data-amount-part')
                , amount_total = $this.attr('data-amout-total')
                , callback

            if ( options.use_percentage && !percentage ) return
            else if ( !options.use_percentage ) {
                if ( !amount_part && !amount_total )
                    return
                else {
                    percentage = Math.round(100 * amount_part / amount_total)
                }
            }

            if ( options.callback && typeof(options.callback) == 'function' ) callback = options.callback
            else callback = $.fn.progressbar.defaults.callback

            setTimeout(function() {
                $this.css('width', percentage+'%')

                var current_percentage
                    , parent_width

                var progress = setInterval(function() {
                    parent_width = $this.parent().width()
                    current_percentage = Math.round(100 * $this.width() / parent_width)

                    if ( options.display_text ) {
                        if ( options.use_percentage )
                            $this.text(current_percentage +'%')
                        else
                            $this.text(amount_part + ' / ' + amount_total)
                    }
                    if ( current_percentage >= percentage ) clearInterval(progress)

                    callback(current_percentage)
                }, options.refresh_speed)

            }, options.transition_delay)
        }
    }

    /* PROGRESSBAR PLUGIN DEFINITION
     * ============================= */

    $.fn.progressbar = function ( option ) {
        return this.each(function () {
            var $this = $(this)
                , data = $this.data('progressbar')
                , options = typeof option == 'object' && option
            if (!data) $this.data('progressbar', (data = new Progressbar(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    $.fn.progressbar.defaults = {
        transition_delay: 300
        ,   refresh_speed: 50
        ,   display_text: true
        ,   use_percentage: true
        ,   callback: $.noop
    }

    $.fn.progressbar.Constructor = Progressbar

}( window.jQuery );<|endoftext|>