<commit_before>function launch(prefix, containerId) {
    var deps = [
        "element-factory.js",
        "animation.js",
    ];
    var loaded = 0;
    for (var i = 0; i < deps.length; i++) {
        var elem = document.createElement('script');
        elem.src = prefix + deps[i];
        elem.onload = function() {
            if (++loaded == deps.length) {
                var container = document.getElementById(containerId);
                var gewgaw = new KolakoskiKurve();

                var canvas = yoob.makeCanvas(container, 800, 600);
                yoob.makeLineBreak(container);
                yoob.makeCheckbox(
                    container, true, "opaque", function(bool) {
                        gewgaw.ctx.strokeStyle = bool ? "black" : "rgba(0,0,0,0.1)";
                    }
                );
                yoob.makeCheckbox(
                    container, false, "xor", function(bool) {
                        gewgaw.ctx.globalCompositeOperation = bool ? "xor" : "source-over";
                    }
                );
                yoob.makeLineBreak(container);
                var button = yoob.makeButton(container, 'Reset', function() {
                    gewgaw.reset();
                });
                gewgaw.init(canvas);
            }
        };
        document.body.appendChild(elem);
    }
}

KolakoskiKurve = function() {
    this.init = function(canvas) {
        this.canvas = canvas;
        this.ctx = this.canvas.getContext('2d');

        this.ctx.lineWidth = 2;
        this.ctx.strokeStyle = "black";
        //this.ctx.strokeStyle = "rgba(0,0,0,0.1)";
        this.ctx.globalCompositeOperation = 'source-over';
        //this.ctx.globalCompositeOperation = 'xor';
        this.dist = 5;

        this.startIndex = 0;
        this.endIndex = 10000;
        this.delay = -1;
        this.delayCounter = 0;
        this.stepSize = 10;
        this.sequence = this.generate(this.endIndex);
        this.reset();
    };

    this.reset = function() {
        this.ctx.fillStyle = 'white';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        this.x = this.canvas.width / 2;
        this.y = this.canvas.height - 10;
        this.y = this.canvas.height / 2;
        this.theta = 0;

        this.index = this.startIndex;
        if (this.animation) this.animation.stop();
        this.animation = (new yoob.Animation()).init({ object: this });
        this.animation.start();
    };

    this.step = function() {
        if (this.index >= this.endIndex) return;

        var num = this.sequence[this.index];

        if (num === 1) {
            // FD 10
            var rad = (this.theta / 360) * (Math.PI * 2);

            var dx = this.dist * Math.cos(rad);
            var dy = this.dist * Math.sin(rad);

            var newX = this.x + dx;
            var newY = this.y + dy;

            this.ctx.beginPath();
            this.ctx.moveTo(this.x, this.y);
            this.ctx.lineTo(newX, newY);
            this.ctx.stroke();

            this.x = newX;
            this.y = newY;
        } else if (num === 2) {
            // RT 90
            this.theta += 90;
            while (this.theta >= 360) this.theta -= 360;
        } else {
            alert('wtf');
        }

        this.index++;
    };

    this.draw = function() {
        if (this.index >= this.endIndex) {
            this.animation.stop();
            return;
        }

        for (var j = 0; j < this.stepSize; j++) {
            this.step();
        }
    };

    this.update = function() {
    };

    /*
     * Generate at least n values of the Kolakoski sequence, starting at the beginning.
     */
    this.generate = function(n) {
        var sequence = [1, 2, 2];
        for (var i = 3; sequence.length < n; i++) {
            var newValue = i % 2 === 1 ? 1 : 2;
            sequence.push(newValue);
            if (sequence[i - 1] === 2) {
                sequence.push(newValue);
            }
        }
        return sequence;
    };
};
<commit_msg>Allow to change segment length.<commit_after>function launch(prefix, containerId) {
    var deps = [
        "element-factory.js",
        "animation.js",
    ];
    var loaded = 0;
    for (var i = 0; i < deps.length; i++) {
        var elem = document.createElement('script');
        elem.src = prefix + deps[i];
        elem.onload = function() {
            if (++loaded == deps.length) {
                var container = document.getElementById(containerId);
                var gewgaw = new KolakoskiKurve();

                var canvas = yoob.makeCanvas(container, 800, 600);
                yoob.makeLineBreak(container);
                yoob.makeSliderPlusTextInput(container, "Segment length:", 2, 25, (2), 5, function(v) {
                    gewgaw.dist = v;
                });
                yoob.makeLineBreak(container);
                yoob.makeCheckbox(
                    container, true, "opaque", function(bool) {
                        gewgaw.ctx.strokeStyle = bool ? "black" : "rgba(0,0,0,0.1)";
                    }
                );
                yoob.makeCheckbox(
                    container, false, "xor", function(bool) {
                        gewgaw.ctx.globalCompositeOperation = bool ? "xor" : "source-over";
                    }
                );
                yoob.makeLineBreak(container);
                var button = yoob.makeButton(container, 'Reset', function() {
                    gewgaw.reset();
                });
                gewgaw.init(canvas);
            }
        };
        document.body.appendChild(elem);
    }
}

KolakoskiKurve = function() {
    this.init = function(canvas) {
        this.canvas = canvas;
        this.ctx = this.canvas.getContext('2d');

        this.ctx.lineWidth = 2;
        this.ctx.strokeStyle = "black";
        this.ctx.globalCompositeOperation = 'source-over';
        this.dist = 5;

        this.startIndex = 0;
        this.endIndex = 10000;
        this.delay = -1;
        this.delayCounter = 0;
        this.stepSize = 10;
        this.sequence = this.generate(this.endIndex);
        this.reset();
    };

    this.reset = function() {
        this.ctx.fillStyle = 'white';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        this.x = this.canvas.width / 2;
        this.y = this.canvas.height - 10;
        this.y = this.canvas.height / 2;
        this.theta = 0;

        this.index = this.startIndex;
        if (this.animation) this.animation.stop();
        this.animation = (new yoob.Animation()).init({ object: this });
        this.animation.start();
    };

    this.step = function() {
        if (this.index >= this.endIndex) return;

        var num = this.sequence[this.index];

        if (num === 1) {
            // FD 10
            var rad = (this.theta / 360) * (Math.PI * 2);

            var dx = this.dist * Math.cos(rad);
            var dy = this.dist * Math.sin(rad);

            var newX = this.x + dx;
            var newY = this.y + dy;

            this.ctx.beginPath();
            this.ctx.moveTo(this.x, this.y);
            this.ctx.lineTo(newX, newY);
            this.ctx.stroke();

            this.x = newX;
            this.y = newY;
        } else if (num === 2) {
            // RT 90
            this.theta += 90;
            while (this.theta >= 360) this.theta -= 360;
        } else {
            alert('wtf');
        }

        this.index++;
    };

    this.draw = function() {
        if (this.index >= this.endIndex) {
            this.animation.stop();
            return;
        }

        for (var j = 0; j < this.stepSize; j++) {
            this.step();
        }
    };

    this.update = function() {
    };

    /*
     * Generate at least n values of the Kolakoski sequence, starting at the beginning.
     */
    this.generate = function(n) {
        var sequence = [1, 2, 2];
        for (var i = 3; sequence.length < n; i++) {
            var newValue = i % 2 === 1 ? 1 : 2;
            sequence.push(newValue);
            if (sequence[i - 1] === 2) {
                sequence.push(newValue);
            }
        }
        return sequence;
    };
};
<|endoftext|>


<commit_before>import path from 'path';
import webpack from 'webpack';
import express from 'express';
import WebpackDevServer from 'webpack-dev-server';
import historyApiFallback from 'connect-history-api-fallback';
import githubHookHandler from 'github-webhook-handler';
import chalk from 'chalk';
import cors from 'cors';
import webpackConfig from '../webpack.config';
import config from './config';

require('babel-polyfill');

const handler = githubHookHandler({ path: '/github', secret: 'test1234' });
if (config.env === 'development') {
  const gitCallbackServer = express();
  gitCallbackServer.use(cors());
  gitCallbackServer.use((req, _res, next) => {
    console.log('req.url', req.url);
    handler(req, _res, (err) => {
      const res = _res;
      res.statusCode = 404;
      res.end('no such location');
    });
    next();
  });
  gitCallbackServer.listen(4000, () => console.log(chalk.green('gitCallbackServer is listening on port 4000')));

  const server = new WebpackDevServer(webpack(webpackConfig), {
    contentBase: '/build/',
    hot: true,
    historyApiFallback: true,
  });
  server.use(cors());
  // Serve static resources
  // server.use('/', express.static(path.join(__dirname, '../build')));
  server.use('/doc', express.static(path.join(__dirname, '../documentation/html')));
  server.listen(config.port, () => console.log(chalk.green(`Server is listening on port ${config.port}`)));
} else if (config.env === 'production') {
  // Launch Relay by creating a normal express server
  const server = express();
  server.use(cors());
  server.use(historyApiFallback());
  server.use('/', express.static(path.join(__dirname, '../build')));
  server.use('/doc', express.static(path.join(__dirname, '../documentation/html')));
  server.listen(config.port, () => console.log(chalk.green(`Server is listening on port ${config.port}`)));
}
<commit_msg>add github push event handler<commit_after>import path from 'path';
import webpack from 'webpack';
import express from 'express';
import WebpackDevServer from 'webpack-dev-server';
import historyApiFallback from 'connect-history-api-fallback';
import githubHookHandler from 'github-webhook-handler';
import chalk from 'chalk';
import cors from 'cors';
import webpackConfig from '../webpack.config';
import config from './config';

require('babel-polyfill');

const handler = githubHookHandler({ path: '/github', secret: 'test1234' });
if (config.env === 'development') {
  const gitCallbackServer = express();
  gitCallbackServer.use(cors());
  gitCallbackServer.use((req, _res, next) => {
    console.log('req.url', req.url);
    handler(req, _res, (err) => {
      const res = _res;
      res.statusCode = 404;
      res.end('no such location');
    });
    next();
  });
  handler.on('push', (event) => {
    console.log('Received a push event', event);
  });
  gitCallbackServer.listen(4000, () => console.log(chalk.green('gitCallbackServer is listening on port 4000')));

  const server = new WebpackDevServer(webpack(webpackConfig), {
    contentBase: '/build/',
    hot: true,
    historyApiFallback: true,
  });
  server.use(cors());
  // Serve static resources
  // server.use('/', express.static(path.join(__dirname, '../build')));
  server.use('/doc', express.static(path.join(__dirname, '../documentation/html')));
  server.listen(config.port, () => console.log(chalk.green(`Server is listening on port ${config.port}`)));
} else if (config.env === 'production') {
  // Launch Relay by creating a normal express server
  const server = express();
  server.use(cors());
  server.use(historyApiFallback());
  server.use('/', express.static(path.join(__dirname, '../build')));
  server.use('/doc', express.static(path.join(__dirname, '../documentation/html')));
  server.listen(config.port, () => console.log(chalk.green(`Server is listening on port ${config.port}`)));
}
<|endoftext|>


<commit_before>import Vue from 'vue'
import VueCustomElement from 'vue-custom-element'
import LibCrowdsViewer from 'libcrowds-viewer'
import Template from '@/components/Template'

Vue.config.ignoredElements = [
  'project-iiif-mark-template',
  'project-iiif-mark-tutorial',
  'project-iiif-mark-results'
]

Vue.use(VueCustomElement)
vue.use(LibCrowdsViewer)
Vue.customElement('project-iiif-mark-template', Template)
<commit_msg>Fix typo<commit_after>import Vue from 'vue'
import VueCustomElement from 'vue-custom-element'
import LibCrowdsViewer from 'libcrowds-viewer'
import Template from '@/components/Template'

Vue.config.ignoredElements = [
  'project-iiif-mark-template',
  'project-iiif-mark-tutorial',
  'project-iiif-mark-results'
]

Vue.use(VueCustomElement)
Vue.use(LibCrowdsViewer)
Vue.customElement('project-iiif-mark-template', Template)
<|endoftext|>


<commit_before>var fortune = require('fortune'),
	express = require('express');

var app = fortune ({
    db: 'techreadytweets'
  })
  .resource('tweet', {
    author: String,
    message: String,
    timestamp: Number
  });

app.use('/app', express.static(__dirname + '/../client/dist'));

app.listen(1337);
<commit_msg>serve ember app at localhost:1337<commit_after>var fortune = require('fortune'),
	express = require('express');

var app = fortune ({
    db: 'techreadytweets'
  })
  .resource('tweet', {
    author: String,
    message: String,
    timestamp: Number
  });

app.use(express.static(__dirname + '/../client/dist'));

app.listen(1337);
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var should = chai.should();
var expect = chai.expect;
var nock = require('nock');

var chat = require('./../lib/slack/chat');
var errors = require('../lib/errors');
var Cache = require('../lib/cache');
var slackTypes = require('./../lib/slack/types');

describe('chat', function () {

    before(function () {
        var cache = Cache;
        cache.data = {};
        cache.data.user = {};
        cache.data.user.name = 'bot';
        cache.data.users = [{ id: 'U0A1B2C3D4', name: 'phillip' }];
        cache.data.ims = {};
        cache.data.ims = [{ id: 'D0BN0UDLG',
                            is_im: true,
                            user: 'U0A1B2C3D4'}];
        cache.data.hostname = 'slack.com';

    });

    // function (method, params, callback)
    describe('#deleteMessage', function () {

        it('exists as method on chat', function (done) {
            expect(typeof chat.deleteMessage).to.equal('function');
            done();
        });

        it('should return an error to callback if missing required arguments', function (done) {
            chat.deleteMessage(null, null, function (err, result) {
                expect(err).to.not.equal(null);
                expect(err.message).to.equal('must supply valid argument(s)');
                done();
            });

        });

        it('should return an api response', function (done) {
              var slackResponse = {
                ok: true,
                channel: 'C0BCBJYTS',
                ts: '1445172744.000006'
                };

            var scope = nock('https://slack.com')
                .post('/api/chat.delete')
                .reply(200, slackResponse);

            chat.deleteMessage('string', 'string', function (err, result) {
                expect(result).to.be.an('object');
                expect(result.ok).to.equal(true);
                expect(result.ts).to.equal('1445172744.000006');
            });
            done();
        });

        it('should return an api error response', function (done) {
            var slackResponse = {
                ok: false,
                error: 'message_not_found'
            };

            var scope = nock('https://slack.com')
                .post('/api/chat.delete')
                .reply(200, slackResponse);

            chat.deleteMessage('string', 'string', function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('message_not_found');
                done();
            });
        });

    });

    // function (method, params, callback)
    describe('#postMessage', function () {

        it('exists as method on chat', function (done) {
            expect(typeof chat.postMessage).to.equal('function');
            done();
        });

        it('should return an error to callback if missing required arguments', function (done) {
            chat.postMessage(null, null, function (err, result) {
                expect(err).to.not.equal(null);
                expect(err.message).to.equal('must supply valid argument(s)');
                done();
            });

        });

        it('should return an api response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.postMessage')
                .reply(200, {
                    ok: true
                });
            chat.postMessage('general', 'message', function (err, result) {
                expect(result).to.be.an('object');
                expect(result.ok).to.equal(true);
            });
            done();

        });

        it('should return an api error response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.postMessage')
                .reply(200, {
                    ok: false,
                    error: 'msg_too_long'
                });
            chat.postMessage('general', 'message', function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('msg_too_long');
                done();
            });
        });
    });

    // function (method, params, callback)
    describe('#postDirectMessage', function () {

        it('exists as method on chat', function (done) {
            expect(typeof chat.postDirectMessage).to.equal('function');
            done();
        });

        it('should return an error to callback if missing required arguments', function (done) {
            chat.postDirectMessage(null, null, function (err, result) {
                expect(err).to.not.equal(null);
                expect(err.message).to.equal('must supply valid argument(s)');
            });
            done();
        });

        it('should return an api response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.postMessage')
                .reply(200, {
                    ok: true,
                });
            chat.postDirectMessage('phillip', 'message', function (err, result) {
                expect(result).to.be.an('object');
                expect(result.ok).to.equal(true);
            });
            done();
        });
        it('should return an api error response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.postMessage')
                .reply(200, {
                    ok: false,
                    error: 'channel_not_found'
                });
            chat.postDirectMessage('phillip', 'message', function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('channel_not_found');
                done();
            });
        });
    });

    // function (method, params, callback)
    describe('#updateMessage', function () {

        it('exists as method on chat', function (done) {
            expect(typeof chat.updateMessage).to.equal('function');
            done();
        });

        it('should return an error to callback if missing required arguments', function (done) {
            chat.updateMessage(null,null,null,function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('must supply valid argument(s)');
                done();
            });

        });

        it('should return an api response', function (done) {
            var slackResponse = { ok: true,
                channel: 'C0BCBJYTS',
                ts: '1445389812.000011'
            };
            var scope = nock('https://slack.com')
                .post('/api/chat.update')
                .reply(200, slackResponse);
            chat.updateMessage('string', 'string', 'string', function (err, result) {
                expect(result).to.be.an('object');
                expect(result.ok).to.equal(true);
            });
            done();
        });
        it('should return an api error response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.update')
                .reply(200, {
                    ok: false,
                    error: 'channel_not_found'
                });
            chat.updateMessage('string', 'string','string', function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('channel_not_found');
                done();
            });
        });
    });
});<commit_msg>semicolon<commit_after>'use strict';

var chai = require('chai');
var should = chai.should();
var expect = chai.expect;
var nock = require('nock');

var chat = require('./../lib/slack/chat');
var errors = require('../lib/errors');
var Cache = require('../lib/cache');
var slackTypes = require('./../lib/slack/types');

describe('chat', function () {

    before(function () {
        var cache = Cache;
        cache.data = {};
        cache.data.user = {};
        cache.data.user.name = 'bot';
        cache.data.users = [{ id: 'U0A1B2C3D4', name: 'phillip' }];
        cache.data.ims = {};
        cache.data.ims = [{ id: 'D0BN0UDLG',
                            is_im: true,
                            user: 'U0A1B2C3D4'}];
        cache.data.hostname = 'slack.com';

    });

    // function (method, params, callback)
    describe('#deleteMessage', function () {

        it('exists as method on chat', function (done) {
            expect(typeof chat.deleteMessage).to.equal('function');
            done();
        });

        it('should return an error to callback if missing required arguments', function (done) {
            chat.deleteMessage(null, null, function (err, result) {
                expect(err).to.not.equal(null);
                expect(err.message).to.equal('must supply valid argument(s)');
                done();
            });

        });

        it('should return an api response', function (done) {
              var slackResponse = {
                ok: true,
                channel: 'C0BCBJYTS',
                ts: '1445172744.000006'
                };

            var scope = nock('https://slack.com')
                .post('/api/chat.delete')
                .reply(200, slackResponse);

            chat.deleteMessage('string', 'string', function (err, result) {
                expect(result).to.be.an('object');
                expect(result.ok).to.equal(true);
                expect(result.ts).to.equal('1445172744.000006');
            });
            done();
        });

        it('should return an api error response', function (done) {
            var slackResponse = {
                ok: false,
                error: 'message_not_found'
            };

            var scope = nock('https://slack.com')
                .post('/api/chat.delete')
                .reply(200, slackResponse);

            chat.deleteMessage('string', 'string', function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('message_not_found');
                done();
            });
        });

    });

    // function (method, params, callback)
    describe('#postMessage', function () {

        it('exists as method on chat', function (done) {
            expect(typeof chat.postMessage).to.equal('function');
            done();
        });

        it('should return an error to callback if missing required arguments', function (done) {
            chat.postMessage(null, null, function (err, result) {
                expect(err).to.not.equal(null);
                expect(err.message).to.equal('must supply valid argument(s)');
                done();
            });

        });

        it('should return an api response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.postMessage')
                .reply(200, {
                    ok: true
                });
            chat.postMessage('general', 'message', function (err, result) {
                expect(result).to.be.an('object');
                expect(result.ok).to.equal(true);
            });
            done();

        });

        it('should return an api error response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.postMessage')
                .reply(200, {
                    ok: false,
                    error: 'msg_too_long'
                });
            chat.postMessage('general', 'message', function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('msg_too_long');
                done();
            });
        });
    });

    // function (method, params, callback)
    describe('#postDirectMessage', function () {

        it('exists as method on chat', function (done) {
            expect(typeof chat.postDirectMessage).to.equal('function');
            done();
        });

        it('should return an error to callback if missing required arguments', function (done) {
            chat.postDirectMessage(null, null, function (err, result) {
                expect(err).to.not.equal(null);
                expect(err.message).to.equal('must supply valid argument(s)');
            });
            done();
        });

        it('should return an api response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.postMessage')
                .reply(200, {
                    ok: true
                });
            chat.postDirectMessage('phillip', 'message', function (err, result) {
                expect(result).to.be.an('object');
                expect(result.ok).to.equal(true);
            });
            done();
        });
        it('should return an api error response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.postMessage')
                .reply(200, {
                    ok: false,
                    error: 'channel_not_found'
                });
            chat.postDirectMessage('phillip', 'message', function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('channel_not_found');
                done();
            });
        });
    });

    // function (method, params, callback)
    describe('#updateMessage', function () {

        it('exists as method on chat', function (done) {
            expect(typeof chat.updateMessage).to.equal('function');
            done();
        });

        it('should return an error to callback if missing required arguments', function (done) {
            chat.updateMessage(null,null,null,function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('must supply valid argument(s)');
                done();
            });

        });

        it('should return an api response', function (done) {
            var slackResponse = { ok: true,
                channel: 'C0BCBJYTS',
                ts: '1445389812.000011'
            };
            var scope = nock('https://slack.com')
                .post('/api/chat.update')
                .reply(200, slackResponse);
            chat.updateMessage('string', 'string', 'string', function (err, result) {
                expect(result).to.be.an('object');
                expect(result.ok).to.equal(true);
            });
            done();
        });
        it('should return an api error response', function (done) {
            var scope = nock('https://slack.com')
                .post('/api/chat.update')
                .reply(200, {
                    ok: false,
                    error: 'channel_not_found'
                });
            chat.updateMessage('string', 'string','string', function (err, result) {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('channel_not_found');
                done();
            });
        });
    });
});<|endoftext|>


<commit_before>var DEBUG = true;

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// PREPARE LEVELS

function createDefaultLevel(id, error) {
	error = error || '';
	// TODO check map existance
	var geometryId = id + "_geo";
	var background = id;
	var bgcolor = 0;
	if (!getMap(geometryId)) return console.error(error + ': No geometry found for level ' + id);
	if (!getMap(background)) { background = geometryId; bgcolor = 10; }
	// if only geo exist, create a default for rendering
	var level = { "name": "", "background": background, "geometry": geometryId, "bgcolor": bgcolor, "doors": ["", "", ""] };
	assets.levels[id] = level;
	if (error) console.error();
	return true;
}

var levels = assets.levels;
var doors  = assets.doors;

for (var id in levels) {
	var level = levels[id];
	if (!level.background) level.background = id;
	if (!level.geometry)   level.geometry   = id + '_geo';
	level.doors = ['', '', ''];
}

for (var i = 0; i < doors.length; i++) {
	var door = doors[i];

	var doorA = door[0];
	var doorB = door[1];

	var doorAsplit = doorA.split(':');
	var doorBsplit = doorB.split(':');

	var levelA = doorAsplit[0];
	var levelB = doorBsplit[0];

	var doorIdA = doorAsplit[1] - 1;
	var doorIdB = doorBsplit[1] - 1;

	if (!levels[levelA] && createDefaultLevel(levelA, 'Level does not exist for this door: ' + door)) continue;
	if (!levels[levelB] && createDefaultLevel(levelB, 'Level does not exist for this door: ' + door)) continue;

	levels[levelA].doors[doorIdA] = levelB + ':' + doorIdB;
	levels[levelB].doors[doorIdB] = levelA + ':' + doorIdA;
}

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// PREPARE CUTSCENES

var CUTSCENES_ANIMATIONS = {
	intro:             require('./cutscenes/intro.js'),
	cloudFairy:        require('./cutscenes/cloudFairy.js'),
	waterFairy:        require('./cutscenes/waterFairy.js'),
	fireFairy:         require('./cutscenes/fireFairy.js'),
	beforeLastBattle:  require('./cutscenes/beforeLastBattle.js'),
	afterLastBattle:   require('./cutscenes/afterLastBattle.js')
};

var cutscenes = assets.cutscenes;

for (var i = 0; i < cutscenes.length; i++) {
	var cutscene   = cutscenes[i];
	var levelId    = cutscene.level;
	var cutsceneId = cutscene.cutsceneId;
	if (!CUTSCENES_ANIMATIONS[cutsceneId]) {
		console.error('Cut scene is not included in build:' + cutsceneId, cutscene);
		continue;
	}
	var level = levels[levelId];
	if (!level && createDefaultLevel(levelId, 'Level does not exist for this cutscene: ' + cutsceneId)) continue;
	level.cutscene = CUTSCENES_ANIMATIONS[cutsceneId];
}

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
var gameController = require('./GameController.js');

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// DEBUGGING FUNCTIONS

if (DEBUG) {
	window.controller = gameController;
	window.bob        = gameController.bob;
	window.level      = gameController.level;

	// load cutscene from console
	window.cutscene = function (id) {
		var cutscene = CUTSCENES_ANIMATIONS[id];
		if (!cutscene) return console.error('cutscene does not exist: ' + id);
		gameController.startCutScene(cutscene(gameController));
	}

	// load level from console
	window.loadLevel = function (id) {
		// let's try to create the level if it does't exist
		if (!assets.levels[id]) createDefaultLevel(id);
		gameController.loadLevel(id);
		gameController.saveState();
	};

	// hack Bob abilities
	var bob = require('./Bob.js');
	bob.canDive       = true;
	bob.canDoubleJump = true;
	bob.canAttack     = true;
}

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// START GAME
gameController.loadLevel('inside');
gameController.saveState();

// start intro
if (!DEBUG) gameController.startCutScene(CUTSCENES_ANIMATIONS.intro(gameController));

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// Update is called once per frame
exports.update = function () {
	gameController.update();
};
<commit_msg>debug<commit_after>var DEBUG = false;

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// PREPARE LEVELS

function createDefaultLevel(id, error) {
	error = error || '';
	// TODO check map existance
	var geometryId = id + "_geo";
	var background = id;
	var bgcolor = 0;
	if (!getMap(geometryId)) return console.error(error + ': No geometry found for level ' + id);
	if (!getMap(background)) { background = geometryId; bgcolor = 10; }
	// if only geo exist, create a default for rendering
	var level = { "name": "", "background": background, "geometry": geometryId, "bgcolor": bgcolor, "doors": ["", "", ""] };
	assets.levels[id] = level;
	if (error) console.error();
	return true;
}

var levels = assets.levels;
var doors  = assets.doors;

for (var id in levels) {
	var level = levels[id];
	if (!level.background) level.background = id;
	if (!level.geometry)   level.geometry   = id + '_geo';
	level.doors = ['', '', ''];
}

for (var i = 0; i < doors.length; i++) {
	var door = doors[i];

	var doorA = door[0];
	var doorB = door[1];

	var doorAsplit = doorA.split(':');
	var doorBsplit = doorB.split(':');

	var levelA = doorAsplit[0];
	var levelB = doorBsplit[0];

	var doorIdA = doorAsplit[1] - 1;
	var doorIdB = doorBsplit[1] - 1;

	if (!levels[levelA] && createDefaultLevel(levelA, 'Level does not exist for this door: ' + door)) continue;
	if (!levels[levelB] && createDefaultLevel(levelB, 'Level does not exist for this door: ' + door)) continue;

	levels[levelA].doors[doorIdA] = levelB + ':' + doorIdB;
	levels[levelB].doors[doorIdB] = levelA + ':' + doorIdA;
}

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// PREPARE CUTSCENES

var CUTSCENES_ANIMATIONS = {
	intro:             require('./cutscenes/intro.js'),
	cloudFairy:        require('./cutscenes/cloudFairy.js'),
	waterFairy:        require('./cutscenes/waterFairy.js'),
	fireFairy:         require('./cutscenes/fireFairy.js'),
	beforeLastBattle:  require('./cutscenes/beforeLastBattle.js'),
	afterLastBattle:   require('./cutscenes/afterLastBattle.js')
};

var cutscenes = assets.cutscenes;

for (var i = 0; i < cutscenes.length; i++) {
	var cutscene   = cutscenes[i];
	var levelId    = cutscene.level;
	var cutsceneId = cutscene.cutsceneId;
	if (!CUTSCENES_ANIMATIONS[cutsceneId]) {
		console.error('Cut scene is not included in build:' + cutsceneId, cutscene);
		continue;
	}
	var level = levels[levelId];
	if (!level && createDefaultLevel(levelId, 'Level does not exist for this cutscene: ' + cutsceneId)) continue;
	level.cutscene = CUTSCENES_ANIMATIONS[cutsceneId];
}

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
var gameController = require('./GameController.js');

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// DEBUGGING FUNCTIONS

if (DEBUG) {
	window.controller = gameController;
	window.bob        = gameController.bob;
	window.level      = gameController.level;

	// load cutscene from console
	window.cutscene = function (id) {
		var cutscene = CUTSCENES_ANIMATIONS[id];
		if (!cutscene) return console.error('cutscene does not exist: ' + id);
		gameController.startCutScene(cutscene(gameController));
	}

	// load level from console
	window.loadLevel = function (id) {
		// let's try to create the level if it does't exist
		if (!assets.levels[id]) createDefaultLevel(id);
		gameController.loadLevel(id);
		gameController.saveState();
	};

	// hack Bob abilities
	var bob = require('./Bob.js');
	bob.canDive       = true;
	bob.canDoubleJump = true;
	bob.canAttack     = true;
}

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// START GAME
gameController.loadLevel('inside');
gameController.saveState();

// start intro
if (!DEBUG) gameController.startCutScene(CUTSCENES_ANIMATIONS.intro(gameController));

//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
// Update is called once per frame
exports.update = function () {
	gameController.update();
};
<|endoftext|>


<commit_before>class Plasticine {

    /**
     * @param {(Object|Array|String)} template
     * @returns {{transform: (function(this:Plasticine)), validation: (function(this:Plasticine))}}
     */
    constructor(template) {
        this._regex = {
            and     : /\([\w-]+(?:&[\w-]+){1,}\)/,
            or      : /\([\w-]+(?:\|[\w-]+){1,}\)/,
            replace : /\(([\w-|&]+)\)/
        };

        this._store = {
            template: this._templatePreparation(template)
        };

        return {
            transform : this.transform.bind(this),
            validation: this.validation.bind(this)
        };
    }

    /**
     * @param {(Object|Array|String)} source
     * @returns {(Object|Array|String)}
     */
    transform(source) {
        this._store.root = null;

        return this._parser(source, this._store.template)
    }

    validation() {
        // @TODO:
    }

    /**
     * @param {(Object|Array|String)} source
     * @param {(Object|Array|String)} template
     * @returns {(Object|Array|String)}
     * @private
     */
    _parser(source, template) {
        let result = null;

        switch(this._type(source)) {
            case 'array':
                result = new Array(source.length);

                for(let i in source) {
                    result[i] = this._templateParser(source[i], template);
                }
                break;
            case 'object':
                result = this._templateParser(source, template);
                break;
            case 'string':
                try {
                    let json = JSON.parse(source);

                    result = JSON.stringify(this._parser(json, template));
                } catch (e) {
                    console.error('[Plasticine._parser] source string is not JSON!');
                }
                break;
        }

        return result;
    }

    _templatePreparation(template) {
        let result = null;

        switch(this._type(template)) {
            case 'array':
            case 'object':
                result = template;
                break;
            case 'string':
                try {
                    result = JSON.parse(template);
                } catch (e) {
                    console.error('[Plasticine._templatePreparation] template string is not JSON!');
                }
                break;
            default:
                console.error('[Plasticine._templatePreparation] template type', this._type(template));
        }

        return result;
    }

    /**
     * @param {Object} source
     * @param {(Object|Array|String)} template
     * @returns {(Object|Array)}
     * @private
     */
    _templateParser(source, template) {
        let result = null;

        switch(this._type(template)) {
            case 'array':
                result = template.map((key, index) => this._templateParser(source, template[index]));
                break;
            case 'object':
                result = {};

                let keys = Object.keys(template);

                for(let i in keys) {
                    result[keys[i]] = this._templateParser(source, template[keys[i]])
                }
                break;
            case 'string':
                let operators = template.split('.');

                result = this._sourceParser(source, operators);
                break;
            default:
                console.error('[Plasticine._templateParser] template type', this._type(template));
        }

        return result;
    }

    /**
     * @param {(Object|Array)} source
     * @param {Array} operators
     * @returns {(Object|Array)}
     * @private
     */
    _sourceParser(source, operators) {
        let result = null;

        switch(this._type(source)) {
            case 'array':
                result = source.map(item => {
                    this._store.root = item;

                    return this._sourceParser(item, operators.slice(0));
                });
                break;
            case 'object':
                if(this._store.root === null) {
                    this._store.root = source;
                }

                result = this._get(source, operators);
                break;
        }

        return result;
    }

    /**
     *
     * @param {(Object|Array)} source
     * @param {Array} operators
     * @returns {Array}
     * @private
     */
    _deep(source, operators) {
        let result = [];

        switch(this._type(source)) {
            case 'array':
                for(let i in source) {
                    if(source.hasOwnProperty(i)) {
                        let _deep = this._deep(source[i], operators);

                        if(_deep.length) {
                            result = [].concat(result, _deep);
                        }
                    }
                }
                break;
            case 'object':
                let _get = this._get(source, operators.slice(0));

                _get && result.push(_get);

                Object.keys(source).forEach(key => {
                    let _deep= this._deep(source[key], operators);

                    if(_deep.length) {
                        result = result.concat(_deep);
                    }
                });
                break;
        }

        return result;
    }

    /**
     * @param {Object} source
     * @param {Array} operators
     * @returns {(Object|Array)}
     * @private
     */
    _get(source, operators) {
        let operator= operators.shift(),
            result  = null;

        switch(operator) {
            case '$':
                result = this._store.root;
                break;
            case '*':
                result = Object.keys(source).map(key => operators.length ? this._get(source[key], operators.splice(0)) : source[key]);

                operators = [];
                break;
            case '':
                result = this._deep(source, operators.slice(0));
                operators = [];
                break;
            default:
                if(this._regex.and.test(operator)) {
                    let subOperators = operator.replace(this._regex.replace, '$1').split('&');

                    result = subOperators.map(key => {
                        let aKey = [key];

                        return this._get(source, operators.length ? aKey.concat(operators) : aKey);
                    });
                } else if(this._regex.or.test(operator)) {
                    let subOperators = operator.replace(this._regex.replace, '$1').split('|');

                    for(let i in subOperators) {
                        if(subOperators.hasOwnProperty(i)) {
                            let aKey = [subOperators[i]],
                                _get = this._get(source, operators.length ? aKey.concat(operators) : aKey);

                            if(_get) {
                                result = _get;
                                break;
                            }
                        }
                    }
                } else {
                    result = source[operator];
                }
        }

        if(operators.length  && result != undefined) {
            result = this._get(result, operators);
        }

        return result;
    }

    /**
     * @param {*} data
     * @returns {String}
     * @private
     */
    _type(data) {
        let _type = typeof data;

        if(_type == 'object' && Array.isArray(data)) {
            _type = 'array';
        }

        return _type;
    }

}

export default Plasticine;
<commit_msg>fix root<commit_after>class Plasticine {

    /**
     * @param {(Object|Array|String)} template
     * @returns {{transform: (function(this:Plasticine)), validation: (function(this:Plasticine))}}
     */
    constructor(template) {
        this._regex = {
            and     : /\([\w-]+(?:&[\w-]+){1,}\)/,
            or      : /\([\w-]+(?:\|[\w-]+){1,}\)/,
            replace : /\(([\w-|&]+)\)/
        };

        this._store = {
            template: this._templatePreparation(template)
        };

        return {
            transform : this.transform.bind(this),
            validation: this.validation.bind(this)
        };
    }

    /**
     * @param {(Object|Array|String)} source
     * @returns {(Object|Array|String)}
     */
    transform(source) {
        this._store.root = null;

        return this._parser(source, this._store.template)
    }

    validation() {
        // @TODO:
    }

    /**
     * @param {(Object|Array|String)} source
     * @param {(Object|Array|String)} template
     * @returns {(Object|Array|String)}
     * @private
     */
    _parser(source, template) {
        let result = null;

        switch(this._type(source)) {
            case 'array':
                result = new Array(source.length);

                for(let i in source) {
                    result[i] = this._templateParser(source[i], template);
                }
                break;
            case 'object':
                result = this._templateParser(source, template);
                break;
            case 'string':
                try {
                    let json = JSON.parse(source);

                    result = JSON.stringify(this._parser(json, template));
                } catch (e) {
                    console.error('[Plasticine._parser] source string is not JSON!');
                }
                break;
        }

        return result;
    }

    _templatePreparation(template) {
        let result = null;

        switch(this._type(template)) {
            case 'array':
            case 'object':
                result = template;
                break;
            case 'string':
                try {
                    result = JSON.parse(template);
                } catch (e) {
                    console.error('[Plasticine._templatePreparation] template string is not JSON!');
                }
                break;
            default:
                console.error('[Plasticine._templatePreparation] template type', this._type(template));
        }

        return result;
    }

    /**
     * @param {Object} source
     * @param {(Object|Array|String)} template
     * @returns {(Object|Array)}
     * @private
     */
    _templateParser(source, template) {
        let result = null;

        switch(this._type(template)) {
            case 'array':
                result = template.map((key, index) => this._templateParser(source, template[index]));
                break;
            case 'object':
                result = {};

                let keys = Object.keys(template);

                for(let i in keys) {
                    result[keys[i]] = this._templateParser(source, template[keys[i]])
                }
                break;
            case 'string':
                let operators = template.split('.');

                result = this._sourceParser(source, operators);
                break;
            default:
                console.error('[Plasticine._templateParser] template type', this._type(template));
        }

        return result;
    }

    /**
     * @param {(Object|Array)} source
     * @param {Array} operators
     * @returns {(Object|Array)}
     * @private
     */
    _sourceParser(source, operators) {
        let result = null;

        switch(this._type(source)) {
            case 'array':
                result = source.map(item => {
                    return this._sourceParser(item, operators.slice(0));
                });
                break;
            case 'object':
                this._store.root = source;

                result = this._get(source, operators);
                break;
        }

        return result;
    }

    /**
     *
     * @param {(Object|Array)} source
     * @param {Array} operators
     * @returns {Array}
     * @private
     */
    _deep(source, operators) {
        let result = [];

        switch(this._type(source)) {
            case 'array':
                for(let i in source) {
                    if(source.hasOwnProperty(i)) {
                        let _deep = this._deep(source[i], operators);

                        if(_deep.length) {
                            result = [].concat(result, _deep);
                        }
                    }
                }
                break;
            case 'object':
                let _get = this._get(source, operators.slice(0));

                _get && result.push(_get);

                Object.keys(source).forEach(key => {
                    let _deep= this._deep(source[key], operators);

                    if(_deep.length) {
                        result = result.concat(_deep);
                    }
                });
                break;
        }

        return result;
    }

    /**
     * @param {Object} source
     * @param {Array} operators
     * @returns {(Object|Array)}
     * @private
     */
    _get(source, operators) {
        let operator= operators.shift(),
            result  = null;

        switch(operator) {
            case '$':
                result = this._store.root;
                break;
            case '*':
                result = Object.keys(source).map(key => operators.length ? this._get(source[key], operators.splice(0)) : source[key]);

                operators = [];
                break;
            case '':
                result = this._deep(source, operators.slice(0));
                operators = [];
                break;
            default:
                if(this._regex.and.test(operator)) {
                    let subOperators = operator.replace(this._regex.replace, '$1').split('&');

                    result = subOperators.map(key => {
                        let aKey = [key];

                        return this._get(source, operators.length ? aKey.concat(operators) : aKey);
                    });
                } else if(this._regex.or.test(operator)) {
                    let subOperators = operator.replace(this._regex.replace, '$1').split('|');

                    for(let i in subOperators) {
                        if(subOperators.hasOwnProperty(i)) {
                            let aKey = [subOperators[i]],
                                _get = this._get(source, operators.length ? aKey.concat(operators) : aKey);

                            if(_get) {
                                result = _get;
                                break;
                            }
                        }
                    }
                } else {
                    result = source[operator];
                }
        }

        if(operators.length  && result != undefined) {
            result = this._get(result, operators);
        }

        return result;
    }

    /**
     * @param {*} data
     * @returns {String}
     * @private
     */
    _type(data) {
        let _type = typeof data;

        if(_type == 'object' && Array.isArray(data)) {
            _type = 'array';
        }

        return _type;
    }

}

export default Plasticine;
<|endoftext|>


<commit_before>module.exports.makeWorld = makeWorld;
module.exports.updateWorld = updateWorld;

function makeWorld(db, bots, THREE) {
	var world_map = [];
	var map_builder = db.getDummyMap();
	map_builder.forEach(function(sceneObj, index){
		var  type = sceneObj.type,
				object = db.getObject(type),
				scale = sceneObj.scale || object.scale,
				urlPrefix = "http://langenium.com/play/",
				loader =  new THREE.JSONLoader(),
				url = object.url;

		loader.load(urlPrefix + url, function(geometry, materials){
			var objMesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial( materials ) );
			objMesh.geometry.computeBoundingBox();

			objMesh.scale = new THREE.Vector3(scale,scale,scale);
			objMesh.position.x = sceneObj.position.x,
			objMesh.position.y = sceneObj.position.y,
			objMesh.position.z = sceneObj.position.z,
			objMesh.matrixAutoUpdate = true;
			objMesh.updateMatrix();
			objMesh.updateMatrixWorld();
			world_map.push(objMesh);
		});
	});

	var bot_builder = db.getDummyEnemies();
	bot_builder.forEach(function(obj, index){
		var 	type = obj.type,
				object = db.getObject(type),
				scale = obj.scale || object.scale,
				//urlPrefix = "http://localhost:8080/",
				urlPrefix = "http://langenium.com/play/",
				loader =  new THREE.JSONLoader(),
				url = object.url;

		loader.load(urlPrefix + url, function(geometry, materials){
			var bot = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial( materials ) );
			bot.geometry.computeBoundingBox();
			bot.scale = new THREE.Vector3(scale,scale,scale);
			bot.position.x = obj.position.x,
			bot.position.y = obj.position.y,
			bot.position.z = obj.position.z,
			bot.matrixAutoUpdate = true;
			bot.updateMatrix();
			bot.updateMatrixWorld();
			bot.username = obj.id;
			bot.movement_queue = [];
			bots.push(bot);
		});
	});
	return world_map;
};

function updateWorld(update_queue, bots, events, players_online, THREE, world_map) {
	updateBotsFromBuffer(update_queue, bots, events, players_online, THREE, world_map);
	time = new Date();
	players_online.forEach(function(player){
		var 	playerMovement,
				inputData;
		if (player.inputUpdates.length > 0) {
			inputData = player.inputUpdates.shift();
		}
		else {
			inputData = { d: 0, pZ: 0, pY: 0, rY: 0};
		}
		playerMovement = events.movePlayer(player.velocity, player.position, world_map, inputData);
		player.position.y += playerMovement.instruction.details.pY;
		player.position.x += playerMovement.instruction.details.pX;
		player.position.z += playerMovement.instruction.details.pZ;
		player.position.rotationY +=  playerMovement.instruction.details.rY;
		playerMovement.instruction.details.username = player.sessionId;
		update_queue.push(playerMovement);
		if (player.velocity > 0) {
			player.velocity -= .05;
		}
		if (player.velocity < 0) {
			player.velocity += .05;
		}
	});
	var update_buffer = [];
	update_queue.forEach(function(update, index){
		update_buffer.push(update);
		update_queue.splice(index, 1);
	});
	return update_buffer;
};

function updateBotsFromBuffer(update_queue, bots, events, players_online, THREE, world_map) {
	bots.forEach(function(bot, index){
		if (players_online.length > 0) {

			var 	fire = 0,
					radian = 0.01744444444444444444444444444444 * 4;

			if (bots[index].movement_buffer&&
			(getDistance(bots[index], players_online[0]) - bots[index].movement_buffer.distance < 250)&&
			(checkMovementBuffer(bots[index].movement_buffer) == true))

			{
				var 	tX = events.moveBot(bots[index].movement_buffer.xBuffer),
						tY = events.moveBot(bots[index].movement_buffer.yBuffer),
						tZ = events.moveBot(bots[index].movement_buffer.zBuffer),
						rY = 0;

				if  (
						(getTheta(bots[index], players_online[0]) > radian + bot.rotation.y)||
						(getTheta(bots[index], players_online[0]) < -radian + bot.rotation.y)
					)
				{
					bots[index].movement_buffer.xBuffer /= 1.5;
					bots[index].movement_buffer.yBuffer /= 1.5;
					bots[index].movement_buffer.zBuffer /= 1.5;

					if (bots[index].rotation.y  > getTheta(bots[index], players_online[0])) {
						if (bots[index].rotation.y - radian < getTheta(bots[index], players_online[0])) { }
						else { bots[index].rotation.y -= radian;	rY -= radian; }
					}
					else {
						if (bots[index].rotation.y + radian > getTheta(bots[index], players_online[0])) { }
						else { bots[index].rotation.y += radian;	rY+= radian; }
					}
				}
				else {
					if (bots[index].rotation.y  > getTheta(bots[index], players_online[0])) {
						if (bots[index].rotation.y - radian < getTheta(bots[index], players_online[0])) { }
						else { bots[index].rotation.y -= radian;	rY -= radian; }
					}
					else {
						if (bots[index].rotation.y + radian > getTheta(bots[index], players_online[0])) { }
						else { bots[index].rotation.y += radian;	rY+= radian; }
					}
					if (tX.instruction != 0) { bots[index].position.x += tX.instruction; bots[index].movement_buffer.xBuffer = tX.buffer; }
					if (tY.instruction != 0) { bots[index].position.y += tY.instruction * .7; bots[index].movement_buffer.yBuffer = tY.buffer + (tY.instruction * .3); }
					if (tZ.instruction != 0) { bots[index].position.z += tZ.instruction; bots[index].movement_buffer.zBuffer = tZ.buffer; }
				}

				if ((getDistance(bots[index], players_online[0]) < 2000) &&
						(
							(bots[index].rotation.y - getTheta(bots[index], players_online[0]) < .05)&&
							(bots[index].rotation.y - getTheta(bots[index], players_online[0]) > -.05)
						) &&
						(
							(players_online[0].position.y - bot.position.y < 50)&&
							(players_online[0].position.y - bot.position.y > -50)
						)
				) {
					fire = 1;
				}
				update_queue.push(
					{ instruction: { name: "move", type: "bot", details: { fire: fire, pX: tX.instruction, pY: tY.instruction * .7, pZ: tZ.instruction, rY: rY, username: bots[index].username } } }
				);
			}
			else {
				var destination = new THREE.Vector3(players_online[0].position.x, players_online[0].position.y, players_online[0].position.z);
				bots[index].movement_buffer = events.makeBotMovementBuffer(bots[index], destination, getAngle(bots[index], players_online[0]), getDistance(bots[index], players_online[0]));
			}
		}
		else {
			if ((bots[index].movement_buffer)&&
				((bots[index].movement_buffer.xBuffer != 0)||
				(bots[index].movement_buffer.yBuffer != 0)||
				(bots[index].movement_buffer.zBuffer != 0))) {
					bots[index].movement_buffer.xBuffer = 0;
					bots[index].movement_buffer.yBuffer = 0;
					bots[index].movement_buffer.zBuffer = 0;
			}
		}
	});
}

function getDistance(position1, position2) {
	return Math.sqrt(
		((position1.position.x - position2.position.x) * (position1.position.x - position2.position.x)) +
		((position1.position.y - position2.position.y) * (position1.position.y - position2.position.y)) +
		((position1.position.z - position2.position.z) * (position1.position.z - position2.position.z))
	);
}

function getAngle(position1, position2) {

	var angle = Math.atan2(-(position1.position.x - position2.position.x),
											(position1.position.z - position2.position.z));
	angle *= 180 / Math.PI;
	return -angle;
}

function getTheta(position1, position2) {
	var theta = Math.atan2(-(position1.position.x - position2.position.x),
											(position1.position.z - position2.position.z));
	return Math.min(-theta);
}

function checkMovementBuffer(bufferObject) {
	if ((bufferObject.xBuffer != 0)||
		(bufferObject.yBuffer != 0)||
		(bufferObject.zBuffer != 0) )
	{ return true; }
	else { return false; }
}

<commit_msg>Tweaking<commit_after>module.exports.makeWorld = makeWorld;
module.exports.updateWorld = updateWorld;

function makeWorld(db, bots, THREE) {
	var world_map = [];
	var map_builder = db.getDummyMap();
	map_builder.forEach(function(sceneObj, index){
		var  type = sceneObj.type,
				object = db.getObject(type),
				scale = sceneObj.scale || object.scale,
				urlPrefix = "http://langenium.com/play/",
				loader =  new THREE.JSONLoader(),
				url = object.url;

		loader.load(urlPrefix + url, function(geometry, materials){
			var objMesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial( materials ) );
			objMesh.geometry.computeBoundingBox();

			objMesh.scale = new THREE.Vector3(scale,scale,scale);
			objMesh.position.x = sceneObj.position.x,
			objMesh.position.y = sceneObj.position.y,
			objMesh.position.z = sceneObj.position.z,
			objMesh.matrixAutoUpdate = true;
			objMesh.updateMatrix();
			objMesh.updateMatrixWorld();
			world_map.push(objMesh);
		});
	});

	var bot_builder = db.getDummyEnemies();
	bot_builder.forEach(function(obj, index){
		var 	type = obj.type,
				object = db.getObject(type),
				scale = obj.scale || object.scale,
				//urlPrefix = "http://localhost:8080/",
				urlPrefix = "http://langenium.com/play/",
				loader =  new THREE.JSONLoader(),
				url = object.url;

		loader.load(urlPrefix + url, function(geometry, materials){
			var bot = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial( materials ) );
			bot.geometry.computeBoundingBox();
			bot.scale = new THREE.Vector3(scale,scale,scale);
			bot.position.x = obj.position.x,
			bot.position.y = obj.position.y,
			bot.position.z = obj.position.z,
			bot.matrixAutoUpdate = true;
			bot.updateMatrix();
			bot.updateMatrixWorld();
			bot.username = obj.id;
			bot.movement_queue = [];
			bots.push(bot);
		});
	});
	return world_map;
};

function updateWorld(update_queue, bots, events, players_online, THREE, world_map) {
	updateBotsFromBuffer(update_queue, bots, events, players_online, THREE, world_map);
	time = new Date();
	players_online.forEach(function(player){
		var 	playerMovement,
				inputData;
		if (player.inputUpdates.length > 0) {
			inputData = player.inputUpdates.shift();
		}
		else {
			inputData = { d: 0, pZ: 0, pY: 0, rY: 0};
		}
		playerMovement = events.movePlayer(player.velocity, player.position, world_map, inputData);
		player.position.y += playerMovement.instruction.details.pY;
		player.position.x += playerMovement.instruction.details.pX;
		player.position.z += playerMovement.instruction.details.pZ;
		player.position.rotationY +=  playerMovement.instruction.details.rY;
		playerMovement.instruction.details.username = player.sessionId;
		update_queue.push(playerMovement);
		if (player.velocity > 0) {
			player.velocity -= .05;
		}
		if (player.velocity < 0) {
			player.velocity += .05;
		}
	});
	var update_buffer = [];
	update_queue.forEach(function(update, index){
		update_buffer.push(update);
		update_queue.splice(index, 1);
	});
	return update_buffer;
};

function updateBotsFromBuffer(update_queue, bots, events, players_online, THREE, world_map) {
	bots.forEach(function(bot, index){
		if (players_online.length > 0) {

			var 	fire = 0,
					radian = 0.01744444444444444444444444444444 * 4;

			if (bots[index].movement_buffer&&
			(getDistance(bots[index], players_online[0]) - bots[index].movement_buffer.distance < 250)&&
			(checkMovementBuffer(bots[index].movement_buffer) == true))

			{
				var 	tX = events.moveBot(bots[index].movement_buffer.xBuffer),
						tY = events.moveBot(bots[index].movement_buffer.yBuffer),
						tZ = events.moveBot(bots[index].movement_buffer.zBuffer),
						rY = 0;

				if  (
						(getTheta(bots[index], players_online[0]) > radian + bot.rotation.y)||
						(getTheta(bots[index], players_online[0]) < -radian + bot.rotation.y)
					)
				{
					bots[index].movement_buffer.xBuffer *= .9;
					bots[index].movement_buffer.yBuffer *= .9;
					bots[index].movement_buffer.zBuffer *= .9;

					if (bots[index].rotation.y  > getTheta(bots[index], players_online[0])) {
						if (bots[index].rotation.y - radian < getTheta(bots[index], players_online[0])) { }
						else { bots[index].rotation.y -= radian;	rY -= radian; }
					}
					else {
						if (bots[index].rotation.y + radian > getTheta(bots[index], players_online[0])) { }
						else { bots[index].rotation.y += radian;	rY+= radian; }
					}
				}
				else {
					if (bots[index].rotation.y  > getTheta(bots[index], players_online[0])) {
						if (bots[index].rotation.y - radian < getTheta(bots[index], players_online[0])) { }
						else { bots[index].rotation.y -= radian;	rY -= radian; }
					}
					else {
						if (bots[index].rotation.y + radian > getTheta(bots[index], players_online[0])) { }
						else { bots[index].rotation.y += radian;	rY+= radian; }
					}
					if (tX.instruction != 0) { bots[index].position.x += tX.instruction; bots[index].movement_buffer.xBuffer = tX.buffer; }
					if (tY.instruction != 0) { bots[index].position.y += tY.instruction; bots[index].movement_buffer.yBuffer = tY.buffer; }
					if (tZ.instruction != 0) { bots[index].position.z += tZ.instruction; bots[index].movement_buffer.zBuffer = tZ.buffer; }
				}

				if ((getDistance(bots[index], players_online[0]) < 2000) &&
						(
							(bots[index].rotation.y - getTheta(bots[index], players_online[0]) < .05)&&
							(bots[index].rotation.y - getTheta(bots[index], players_online[0]) > -.05)
						) &&
						(
							(players_online[0].position.y - bot.position.y < 50)&&
							(players_online[0].position.y - bot.position.y > -50)
						)
				) {
					fire = 1;
				}
				update_queue.push(
					{ instruction: { name: "move", type: "bot", details: { fire: fire, pX: tX.instruction, pY: tY.instruction * .7, pZ: tZ.instruction, rY: rY, username: bots[index].username } } }
				);
			}
			else {
				var destination = new THREE.Vector3(players_online[0].position.x, players_online[0].position.y, players_online[0].position.z);
				bots[index].movement_buffer = events.makeBotMovementBuffer(bots[index], destination, getAngle(bots[index], players_online[0]), getDistance(bots[index], players_online[0]));
			}
		}
		else {
			if ((bots[index].movement_buffer)&&
				((bots[index].movement_buffer.xBuffer != 0)||
				(bots[index].movement_buffer.yBuffer != 0)||
				(bots[index].movement_buffer.zBuffer != 0))) {
					bots[index].movement_buffer.xBuffer = 0;
					bots[index].movement_buffer.yBuffer = 0;
					bots[index].movement_buffer.zBuffer = 0;
			}
		}
	});
}

function getDistance(position1, position2) {
	return Math.sqrt(
		((position1.position.x - position2.position.x) * (position1.position.x - position2.position.x)) +
		((position1.position.y - position2.position.y) * (position1.position.y - position2.position.y)) +
		((position1.position.z - position2.position.z) * (position1.position.z - position2.position.z))
	);
}

function getAngle(position1, position2) {

	var angle = Math.atan2(-(position1.position.x - position2.position.x),
											(position1.position.z - position2.position.z));
	angle *= 180 / Math.PI;
	return -angle;
}

function getTheta(position1, position2) {
	var theta = Math.atan2(-(position1.position.x - position2.position.x),
											(position1.position.z - position2.position.z));
	return Math.min(-theta);
}

function checkMovementBuffer(bufferObject) {
	if ((bufferObject.xBuffer != 0)||
		(bufferObject.yBuffer != 0)||
		(bufferObject.zBuffer != 0) )
	{ return true; }
	else { return false; }
}

<|endoftext|>


<commit_before>import assert from 'power-assert';
import Cmyk   from '../src/cmyk';

describe('Cmyk', () => {

  describe('.constructor(c, m, y, k)', () => {

    it('should create an instance', () => {
      let cmyk = new Cmyk(0.2, 0.4, 0.6, 0.8);
      assert(cmyk !== null);
      assert.deepEqual(cmyk.values(), [0.2, 0.4, 0.6, 0.8]);
    });

  });

  describe('.prototype.clone()', () => {

    it('should clone an instance', () => {
      let source = new Cmyk(0.2, 0.4, 0.6, 0.8);
      let cloned = source.clone();
      assert(cloned !== null);
      assert(cloned !== source);
      assert(cloned instanceof Cmyk);
      assert.deepEqual(cloned.entries(), source.entries());
    });

  });

});
<commit_msg>Added a new test suite for the Cmyk.prototype.isValid()<commit_after>import assert from 'power-assert';
import Cmyk   from '../src/cmyk';

describe('Cmyk', () => {

  describe('.constructor(c, m, y, k)', () => {

    it('should create an instance', () => {
      let cmyk = new Cmyk(0.2, 0.4, 0.6, 0.8);
      assert(cmyk !== null);
      assert.deepEqual(cmyk.values(), [0.2, 0.4, 0.6, 0.8]);
    });

  });

  describe('.prototype.clone()', () => {

    it('should clone an instance', () => {
      let source = new Cmyk(0.2, 0.4, 0.6, 0.8);
      let cloned = source.clone();
      assert(cloned !== null);
      assert(cloned !== source);
      assert(cloned instanceof Cmyk);
      assert.deepEqual(cloned.entries(), source.entries());
    });

  });

  describe('.prototype.isValid()', () => {
    const TESTS = Object.freeze([
      {args: [  0,   0,   0,   0], 'expected': true},
      {args: [0.2, 0.4, 0.6, 0.8], 'expected': true},
      {args: [  0,   0,   0,   1], 'expected': true},
      {args: [  1,   1,   1,   0], 'expected': true},
      {args: [NaN, 0.4, 0.6, 0.8], 'expected': false},
      {args: ['a', 0.4, 0.6, 0.8], 'expected': false},
      {args: [ -1, 0.4, 0.6, 0.8], 'expected': false},
      {args: [1.1, 0.4, 0.6, 0.8], 'expected': false},
    ]);

    TESTS.forEach((test) => {
      let args     = test.args;
      let expected = test.expected
      it(`should return ${expected} with [${args}]`, () => {
        let cmyk = new Cmyk(...args);
        assert(cmyk.isValid() === expected);
      });
    });

  });

});
<|endoftext|>


<commit_before>/*

 highlight v4

 Highlights arbitrary terms.

 <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

 MIT license.

 Johann Burkard
 <http://johannburkard.de>
 <mailto:jb@eaio.com>

 */

jQuery.fn.highlight = function(pat) {
    function innerHighlight(node, pat) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pat);
            if (pos >= 0) {
                var spannode = document.createElement('span');
                spannode.className = 'highlight';
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pat.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                skip = 1;
            }
        }
        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerHighlight(node.childNodes[i], pat);
            }
        }
        return skip;
    }
    return this.length && pat && pat.length ? this.each(function() {
        innerHighlight(this, pat.toUpperCase());
    }) : this;
};

jQuery.fn.removeHighlight = function() {
    return this.find("span.highlight").each(function() {
        this.parentNode.firstChild.nodeName;
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
        }
    }).end();
};
<commit_msg>MAJ jquery highligh accents sensitive<commit_after>/*

 highlight v4

 Highlights arbitrary terms.

 <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

 MIT license.

 Johann Burkard
 <http://johannburkard.de>
 <mailto:jb@eaio.com>

 */

function stripAccents(str) {
    var rExps=[
        {re:/[\xC0-\xC6]/g, ch:'A'},
        {re:/[\xE0-\xE6]/g, ch:'a'},
        {re:/[\xC8-\xCB]/g, ch:'E'},
        {re:/[\xE8-\xEB]/g, ch:'e'},
        {re:/[\xCC-\xCF]/g, ch:'I'},
        {re:/[\xEC-\xEF]/g, ch:'i'},
        {re:/[\xD2-\xD6]/g, ch:'O'},
        {re:/[\xF2-\xF6]/g, ch:'o'},
        {re:/[\xD9-\xDC]/g, ch:'U'},
        {re:/[\xF9-\xFC]/g, ch:'u'},
        {re:/[\xD1]/g, ch:'N'},
        {re:/[\xF1]/g, ch:'n'} ];
    for(var i=0, len=rExps.length; i<len; i++)
        str=str.replace(rExps[i].re, rExps[i].ch);
    return str;
};

jQuery.extend({
    highlight: function (node, re, nodeName, className) {
        if (node.nodeType === 3) {
            //var match = node.data.match(re);
            var match = stripAccents(node.data).match(re);
            if (match) {
                var highlight = document.createElement(nodeName || 'span');
                highlight.className = className || 'highlight';
                var wordNode = node.splitText(match.index);
                wordNode.splitText(match[0].length);
                var wordClone = wordNode.cloneNode(true);
                highlight.appendChild(wordClone);
                wordNode.parentNode.replaceChild(highlight, wordNode);
                return 1; //skip added node in parent
            }
        } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
            !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
            !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
            for (var i = 0; i < node.childNodes.length; i++) {
                i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
            }
        }
        return 0;
    }
});

jQuery.fn.unhighlight = function (options) {
    var settings = { className: 'highlight', element: 'span' };
    jQuery.extend(settings, options);

    return this.find(settings.element + "." + settings.className).each(function () {
        var parent = this.parentNode;
        parent.replaceChild(this.firstChild, this);
        parent.normalize();
    }).end();
};

jQuery.fn.highlight = function (words, options) {
    var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
    jQuery.extend(settings, options);

    if (words.constructor === String) {
        words = [words];
    }

    words = jQuery.map(words, function(word, i) {
        return stripAccents(word);
    });

    var flag = settings.caseSensitive ? "" : "i";
    var pattern = "(" + words.join("|") + ")";
    if (settings.wordsOnly) {
        pattern = "\\b" + pattern + "\\b";
    }

    var re = new RegExp(pattern, flag);

    return this.each(function () {
        jQuery.highlight(this, re, settings.element, settings.className);
    });
};<|endoftext|>


<commit_before>// Copyright 2011 Mark Cavage, Inc.  All rights reserved.

var test = require('tap').test;

var log4js = require('../lib/log4js_stub');
var Route = require('../lib/route');

///--- Tests

test('throws on missing options', function(t) {
  t.throws(function() {
    return new Route();
  }, new TypeError('options (Object) required'));
  t.end();
});

test('throws on missing log4js', function(t) {
  t.throws(function() {
    return new Route({});
  }, new TypeError('options.log4js (Object) required'));
  t.end();
});

test('throws on missing url', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js
    });
  }, new TypeError('url must be a String'));
  t.end();
});

test('throws on url wrong type', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js,
      url: 123
    });
  }, new TypeError('url must be a String'));
  t.end();
});

test('throws on setting url incorrectly', function(t) {
  var r = new Route({
    log4js: log4js,
    url: '/foo'
  });
  t.throws(function() {
    r.url = 123;
  }, new TypeError('url must be a String'));
  t.end();
});

test('throws on bad version', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js,
      url: '/foo/bar',
      version: 123
    });
  }, new TypeError('options.version must be a String'));
  t.end();
});

test('throws on bad handlers (not array)', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js,
      url: '/foo/bar',
      handlers: 123
    });
  }, new TypeError('options.handlers must be an Array of Functions'));
  t.end();
});

test('throws on bad handlers (not function)', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js,
      url: '/foo/bar',
      handlers: [123]
    });
  }, new TypeError('options.handlers must be an Array of Functions'));
  t.end();
});

test('construct with default method and name', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar'
  });
  t.ok(route);
  t.equal(route.method, 'GET');
  t.equal(route.url, '/foo/:bar');
  t.equal(route.name, 'GET /foo/:bar');
  t.end();
});

test('construct with explicit method and version', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'PUT',
    version: '1.2.3'
  });
  t.ok(route);
  t.ok(route.pattern);
  t.equal(route.method, 'PUT');
  t.equal(route.url, '/foo/:bar');
  t.equal(route.name, 'PUT /foo/:bar (1.2.3)');
  t.end();
});

test('construct with regex url and chain', function(t) {
  var route = new Route({
    log4js: log4js,
    url: /foo\/(\w+)/,
    method: 'PUT',
    name: 'PutFoo',
    handlers: [function(req, res, next) {}]
  });
  t.ok(route);
  t.ok(route.pattern);
  t.equal(route.method, 'PUT');
  t.equal(route.url, '/foo\\/(\\w+)/');
  t.equal(route.name, 'PutFoo');
  t.end();
});

test('test matches no params', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/bar',
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/bar'
  }), {});
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/boo'
  }));
  t.notOk(route.matches({
    method: 'PUT',
    path: '/foo/bar'
  }));
  t.end();
});

test('test matches params', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/car'
  }), { bar: 'car' });
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/boo/bar'
  }));
  t.notOk(route.matches({
    method: 'PUT',
    path: '/foo/bar'
  }));
  t.end();
});

test('test matches params url-encoded', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/a%40b.com'
  }), { bar: 'a@b.com' });
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/a@b.com'
  }), { bar: 'a@b.com' });
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/a%40b.com/bar'
  }));
  t.end();
});

test('test matches multiple params', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:one/bar/:two',
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/car/bar/chevy'
  }), { one: 'car', two: 'chevy' });
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/boo/bar'
  }));
  t.notOk(route.matches({
    method: 'PUT',
    path: '/foo/bar'
  }));
  t.end();
});

test('test matches regex', function(t) {
  var route = new Route({
    log4js: log4js,
    url: /^\/foo\/(\w+)$/,
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/car'
  }), {0: 'car'});
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/boo/bar'
  }));
  t.notOk(route.matches({
    method: 'PUT',
    path: '/foo/bar'
  }));
  t.end();
});

test('test matches version', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET',
    version: '1.2.3'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/car'
  }), { bar: 'car' });
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/car',
    version: '3.2.1'
  }));
  t.end();
});

test('run routes', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET'
  });
  t.ok(route);
  var invoked = 0;
  route.use([
    function(req, res, next) {
      invoked++;
      return next();
    },
    function(req, res, next) {
      invoked++;
      return next();
    },
    function(req, res, next) {
      return next(new Error('foo'));
    }
  ]);
  route.once('done', function() {
    t.equal(invoked, 2);
    t.end();
  });

  // Stub this out
  route.run({}, { send: function() {} });
});

test('toString', function(t) {
  t.equal(new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET'
  }).toString(), 'GET /foo/:bar');

  t.equal(new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET',
    version: '1.2.3'
  }).toString(), 'GET /foo/:bar (version=1.2.3)');

  t.equal(new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET',
    version: '1.2.3',
    name: 'GetFoo'
  }).toString(), 'GET /foo/:bar (version=1.2.3)');

  t.end();
});
<commit_msg>Added a couple of tests for Range Versioning<commit_after>// Copyright 2011 Mark Cavage, Inc.  All rights reserved.

var test = require('tap').test;

var log4js = require('../lib/log4js_stub');
var Route = require('../lib/route');

///--- Tests

test('throws on missing options', function(t) {
  t.throws(function() {
    return new Route();
  }, new TypeError('options (Object) required'));
  t.end();
});

test('throws on missing log4js', function(t) {
  t.throws(function() {
    return new Route({});
  }, new TypeError('options.log4js (Object) required'));
  t.end();
});

test('throws on missing url', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js
    });
  }, new TypeError('url must be a String'));
  t.end();
});

test('throws on url wrong type', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js,
      url: 123
    });
  }, new TypeError('url must be a String'));
  t.end();
});

test('throws on setting url incorrectly', function(t) {
  var r = new Route({
    log4js: log4js,
    url: '/foo'
  });
  t.throws(function() {
    r.url = 123;
  }, new TypeError('url must be a String'));
  t.end();
});

test('throws on bad version', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js,
      url: '/foo/bar',
      version: 123
    });
  }, new TypeError('options.version must be a String'));
  t.end();
});

test('throws on bad handlers (not array)', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js,
      url: '/foo/bar',
      handlers: 123
    });
  }, new TypeError('options.handlers must be an Array of Functions'));
  t.end();
});

test('throws on bad handlers (not function)', function(t) {
  t.throws(function() {
    return new Route({
      log4js: log4js,
      url: '/foo/bar',
      handlers: [123]
    });
  }, new TypeError('options.handlers must be an Array of Functions'));
  t.end();
});

test('construct with default method and name', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar'
  });
  t.ok(route);
  t.equal(route.method, 'GET');
  t.equal(route.url, '/foo/:bar');
  t.equal(route.name, 'GET /foo/:bar');
  t.end();
});

test('construct with explicit method and version', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'PUT',
    version: '1.2.3'
  });
  t.ok(route);
  t.ok(route.pattern);
  t.equal(route.method, 'PUT');
  t.equal(route.url, '/foo/:bar');
  t.equal(route.name, 'PUT /foo/:bar (1.2.3)');
  t.end();
});

test('construct with range versioning', function(t){
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    version: '>=1.2',
    rangeVersioning: true
  });
  t.ok(route);
  t.end();
});

test('bad version. Sent range instead', function(t){
  t.throws(function(){
    return new Route({
      log4js: log4js,
      url: '/foo/:bar',
      version: '>=1.2'
    });
  }, new Error('only semver versions are allowed'));
  t.end();
});

test('construct with regex url and chain', function(t) {
  var route = new Route({
    log4js: log4js,
    url: /foo\/(\w+)/,
    method: 'PUT',
    name: 'PutFoo',
    handlers: [function(req, res, next) {}]
  });
  t.ok(route);
  t.ok(route.pattern);
  t.equal(route.method, 'PUT');
  t.equal(route.url, '/foo\\/(\\w+)/');
  t.equal(route.name, 'PutFoo');
  t.end();
});

test('test matches no params', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/bar',
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/bar'
  }), {});
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/boo'
  }));
  t.notOk(route.matches({
    method: 'PUT',
    path: '/foo/bar'
  }));
  t.end();
});

test('test matches params', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/car'
  }), { bar: 'car' });
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/boo/bar'
  }));
  t.notOk(route.matches({
    method: 'PUT',
    path: '/foo/bar'
  }));
  t.end();
});

test('test matches params url-encoded', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/a%40b.com'
  }), { bar: 'a@b.com' });
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/a@b.com'
  }), { bar: 'a@b.com' });
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/a%40b.com/bar'
  }));
  t.end();
});

test('test matches multiple params', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:one/bar/:two',
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/car/bar/chevy'
  }), { one: 'car', two: 'chevy' });
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/boo/bar'
  }));
  t.notOk(route.matches({
    method: 'PUT',
    path: '/foo/bar'
  }));
  t.end();
});

test('test matches regex', function(t) {
  var route = new Route({
    log4js: log4js,
    url: /^\/foo\/(\w+)$/,
    method: 'GET'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/car'
  }), {0: 'car'});
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/boo/bar'
  }));
  t.notOk(route.matches({
    method: 'PUT',
    path: '/foo/bar'
  }));
  t.end();
});

test('test matches version', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET',
    version: '1.2.3'
  });
  t.ok(route);
  t.equivalent(route.matches({
    method: 'GET',
    path: '/foo/car'
  }), { bar: 'car' });
  t.notOk(route.matches({
    method: 'GET',
    path: '/foo/car',
    version: '3.2.1'
  }));
  t.end();
});

test('run routes', function(t) {
  var route = new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET'
  });
  t.ok(route);
  var invoked = 0;
  route.use([
    function(req, res, next) {
      invoked++;
      return next();
    },
    function(req, res, next) {
      invoked++;
      return next();
    },
    function(req, res, next) {
      return next(new Error('foo'));
    }
  ]);
  route.once('done', function() {
    t.equal(invoked, 2);
    t.end();
  });

  // Stub this out
  route.run({}, { send: function() {} });
});

test('toString', function(t) {
  t.equal(new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET'
  }).toString(), 'GET /foo/:bar');

  t.equal(new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET',
    version: '1.2.3'
  }).toString(), 'GET /foo/:bar (version=1.2.3)');

  t.equal(new Route({
    log4js: log4js,
    url: '/foo/:bar',
    method: 'GET',
    version: '1.2.3',
    name: 'GetFoo'
  }).toString(), 'GET /foo/:bar (version=1.2.3)');

  t.end();
});
<|endoftext|>


<commit_before>'use strict';

const Actor = require('cqrs').Actor
    , TopicModel = require('../model/Topic');

/**
 * Topic Actor
 * @class Topic
 * @extends {Actor}
 */
class Topic extends Actor {
    constructor(data) {
        let model = TopicModel(data);
        super(model);
    }
    top(data, service) {
        service.apply('top');
    }
    untop(data, service) {
        service.apply('untop');
    }
    fine(data, service) {
        service.apply('fine');
    }
    unfine(data, service) {
        service.apply('unfine');
    }
    access(data, service) {
        service.apply('access');
    }
    update(data, service) {
        service.apply('update', data);
    }
    when(event) {
        let eventName = event.name
            , data = this._data;
        switch (eventName) {
            case 'top':
                data.top = true;
                break;
            case 'untop':
                data.top = false;
                break;
            case 'fine':
                data.fine = true;
                break;
            case 'unfine':
                data.unfine = false;
                break;
            case 'access':
                ++data.accessNum;
                break;
            case 'update':
                data.title = event.data.title;
                data.content = event.data.content;
                data.updateTime = Date.now();
                break;
        }
    }
}

module.exports = Topic;
<commit_msg>unfine->fine<commit_after>'use strict';

const Actor = require('cqrs').Actor
    , TopicModel = require('../model/Topic');

/**
 * Topic Actor
 * @class Topic
 * @extends {Actor}
 */
class Topic extends Actor {
    constructor(data) {
        let model = TopicModel(data);
        super(model);
    }
    top(data, service) {
        service.apply('top');
    }
    untop(data, service) {
        service.apply('untop');
    }
    fine(data, service) {
        service.apply('fine');
    }
    unfine(data, service) {
        service.apply('unfine');
    }
    access(data, service) {
        service.apply('access');
    }
    update(data, service) {
        service.apply('update', data);
    }
    when(event) {
        let eventName = event.name
            , data = this._data;
        switch (eventName) {
            case 'top':
                data.top = true;
                break;
            case 'untop':
                data.top = false;
                break;
            case 'fine':
                data.fine = true;
                break;
            case 'unfine':
                data.fine = false;
                break;
            case 'access':
                ++data.accessNum;
                break;
            case 'update':
                data.title = event.data.title;
                data.content = event.data.content;
                data.updateTime = Date.now();
                break;
        }
    }
}

module.exports = Topic;
<|endoftext|>


<commit_before>/**
 * Created by tungtouch on 2/5/15.
 */

/*
* Listen UDP from Device: 128.199.126.250
* */

var dgram = require("dgram");
var colors = require('colors');
var FIFO = require('dequeue');
var async = require('async');
var redis = require("redis");
var rClient = redis.createClient();

//var ports = [4000, 4001, 4002, 3333, 4003, 4004, 4005, 4006, 4007, 4008, 4009, 4010, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 3011];
var ports = [4444];
var r = 0;

var client = dgram.createSocket('udp4');

rClient.on("error", function (err) {
    console.log("Error " + err);
});

fetcher();
for(var i=0; i < ports.length; i++){

    console.log("Start listen port ",i,":", ports[i]);

    client.on("error", function (err) {
        console.log("Server error:\n".red + err.stack);
        client.close();
    });

    client.on("message", function (msg, rinfo) {
        //console.log("Message:", msg);
        FIFO.push(msg);

    });

    client.bind(ports[i]);

}
function fetcher() {
    console.log("Fetcher Run:", FIFO);
    while (FIFO.length > 0)
    {
        var msg = FIFO.shift();
        console.log("Message: ", msg);
        process.nextTick(fetcher);
    }
    //setImmediate(fetcher); //make this function continuously run
}<commit_msg>Update UDPefef<commit_after>/**
 * Created by tungtouch on 2/5/15.
 */

/*
* Listen UDP from Device: 128.199.126.250
* */

var dgram = require("dgram");
var colors = require('colors');
var Dequeue = require('dequeue')
var async = require('async');
var redis = require("redis");
var rClient = redis.createClient();
var fifo = new Dequeue();
//var ports = [4000, 4001, 4002, 3333, 4003, 4004, 4005, 4006, 4007, 4008, 4009, 4010, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 3011];
var ports = [4444];
var r = 0;

var client = dgram.createSocket('udp4');

rClient.on("error", function (err) {
    console.log("Error " + err);
});

fetcher();
for(var i=0; i < ports.length; i++){

    console.log("Start listen port ",i,":", ports[i]);

    client.on("error", function (err) {
        console.log("Server error:\n".red + err.stack);
        client.close();
    });

    client.on("message", function (msg, rinfo) {
        //console.log("Message:", msg);
        fifo.push(msg);

    });

    client.bind(ports[i]);

}
function fetcher() {
    console.log("Fetcher Run:", FIFO);
    while (fifo.length > 0)
    {
        var msg = fifo.shift();
        console.log("Message: ", msg);
        process.nextTick(fetcher);
    }
    //setImmediate(fetcher); //make this function continuously run
}<|endoftext|>