<commit_before>"use strict";
var assert = require('assert');
var fs = require('fs');
var temp = require('temp');
var $S = require('suspend'), $R = $S.resume, $T = function(gen) { return function(done) { $S.run(gen, done); } };

var Nodalion = require('../nodalion.js');
var ns = Nodalion.namespace('/impred', ['testLocalStore', 'localStr', 'testNow', 'testUUID', 'testLocalQueue',
                                        'testBase64Encode', 'testBase64Decode', 'testLoadNamespace',
                                        'testLoadFile', 'testLoadFile2',
                                        'readSourceFile', 'task', 'assert', 'pred', 'retract']);

var nodalion = new Nodalion(__dirname + '/../../prolog/cedalion.pl', '/tmp/impred-ced.log');

describe('impred', function(){
    describe('local storage', function(){
        it('should allow storing and fetching local state', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testLocalStore(X), $R());
            assert.deepEqual(result, [ns.localStr('bar')]);
        }));
    });
    describe('local queue', function(){
        it('should allow enqueuing and dequeing data', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testLocalQueue(1, X), $R());
            assert.deepEqual(result, ['helloworld']);
        }));
        it('should allow checking if the queue is empty', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testLocalQueue(2, X), $R());
            assert.deepEqual(result, ['YNY']);
        }));

    });
    describe('now', function(){
        it('should return the current time', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testNow(X), $R());
            var list = result[0].meaning();
            assert(list[0] < list[1], list[0] + ' < ' + list[1]);
            assert(list[1] < list[2], list[1] + ' < ' + list[2]);
            assert(list[2] - list[0] < 1, (list[2] - list[0]) + ' < 1');
        }));
    });
    describe('uuid', function(){
        it('should return a unique ID each time it is called', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testUUID(X), $R());
            var list = result[0].meaning();
            assert.notEqual(list[0], list[1]);
            assert.notEqual(list[2], list[1]);
            list.forEach(function(id) {
                // Should be at least 128 bits
                assert(id.length * 6 > 128, (id.length * 6) + ' > 128');
            });
        }));
    });
    describe('base64Encode(Plain)', function(){
        it('should base64-encode the given Plain text', $T(function*(){
            var X = {var:'X'};
            var plain = "the quick brown fox and so on and so forth....";
            var result = yield nodalion.findAll(X, ns.testBase64Encode(plain, X), $R());
            var enc = result[0];
            var buf = new Buffer(Buffer.byteLength(plain));
            buf.write(plain);
            assert.equal(enc, buf.toString('base64'));
        }));
    });
    describe('base64Decode(Enc)', function(){
        it('should decode the given base64-encoded string', $T(function*(){
            var X = {var:'X'};
            var plain = "the quick brown fox and so on and so forth....";
            var buf = new Buffer(Buffer.byteLength(plain));
            buf.write(plain);
            var result = yield nodalion.findAll(X, ns.testBase64Decode(buf.toString('base64'), X), $R());
            var dec = result[0];
            assert.equal(dec, plain);
        }));
    });
    describe('loadCedalionImage(FileName, Prep, PrepIn, PrepOut)', function(){
        it('should load clauses from the given file', $T(function*(){
            var X = {var:'X'};
            var content = "'/impred#foo'(1):-'builtin#true'. '/impred#foo'(2):-'builtin#true'. '/impred#foo'(3):-'builtin#true'.";
            var file = yield temp.open({prefix: 'ced', suffix: '.pl'}, $R());
            yield fs.write(file.fd, content, $R());
            var result = yield nodalion.findAll(X, ns.testLoadNamespace(file.path, X), $R());
            assert.deepEqual(result, [1, 2, 3]);
        }));
        it.skip('should load containers when needed', function(done){
            this.timeout(7000);
            $S.callback(function*() {
                var hash = "QmdHZHRfuJ2QBXfvaMr3ksh3gKyoxc15LhRhKgEKrf4wnj";
                var X = {var:'X'};
                var nns = Nodalion.namespace('/nodalion', ['testContainer']);
                var result = yield nodalion.findAll(X, nns.testContainer(hash, X), $R());
                assert.deepEqual(result, ['cloudlog']);
            })(done);
        });
    });
    var writeFile = $S.callback(function*(content) {
            var file = yield temp.open({prefix: 'example', suffix: '.ced'}, $R());
            yield fs.write(file.fd, content, $R());
            return file.path;
    });
    describe('readSourceFile(FileName, NS)', () => {
        it('should return a list of the statements in a file', $T(function*() {
            var fileName = yield writeFile("hello(World).", $R());
            var X = {var:'X'};
            var res = yield nodalion.findAll(X, ns.task(ns.readSourceFile(fileName, '/foo'), X, {var:'T'}), $R());
            assert.equal(res.length, 1); // One result
            res = res[0].meaning();
            assert.equal(res.length, 1); // One statement
            res = res[0];
            assert.equal(res.name, 'builtin#loadedStatement');
            assert.equal(res.args.length, 3);
            assert.equal(res.args[0], fileName);
            assert.equal(res.args[1].name, '/foo#hello');
            var varNames = res.args[2].meaning();
            assert.equal(varNames.length, 1);
            assert.equal(varNames[0].args[1], 'World');
        }));
    });
    describe('assert(Statement)', () => {
        it('should add the statement to the logic  program', $T(function*() {
            // Add /foo:bar(3):-builtin:true to the program
            var builtin = Nodalion.namespace('builtin', ['true']);
            var foo = Nodalion.namespace('/foo', ['bar']);
            var statement = {name: ":-", args: [foo.bar(3), builtin.true()]};
            yield nodalion.findAll({var: '_'}, ns.task(ns.assert(statement), {var: '_X'}, {var: '_T'}), $R());
            // Query /foo:bar(X)
            var X = {var:'X'};
            var res = yield nodalion.findAll(X, ns.pred(foo.bar(X)), $R());
            assert.deepEqual(res, [3]);
        }));
    });
    describe('retract(Statement)', () => {
        it('should remove the statement from the logic  program', $T(function*() {
            // Add /foo2:bar(4):-builtin:true and /foo2:bar(5):-builtin:true to the program
            var builtin = Nodalion.namespace('builtin', ['true']);
            var foo = Nodalion.namespace('/foo2', ['bar']);
            yield nodalion.findAll({var: '_'}, ns.task(ns.assert({name: ":-", args: [foo.bar(4), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R());
            yield nodalion.findAll({var: '_'}, ns.task(ns.assert({name: ":-", args: [foo.bar(5), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R());
            // Remove /foo2:bar(4):-builtin:true
            yield nodalion.findAll({var: '_'}, ns.task(ns.retract({name: ":-", args: [foo.bar(4), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R());
            // Query /foo:bar(X)
            var X = {var:'X'};
            var res = yield nodalion.findAll(X, ns.pred(foo.bar(X)), $R());
            assert.deepEqual(res, [5]);
        }));
    });
    describe.skip('loadSourceFile(FileName, Prep, PrepIn, PrepOut)', () => {
        it('should load a cedalion source file on top of an image', $T(function*() {
            var X = {var:'X'};
            var imageContent = "'/impred#foo'(4):-'builtin#true'.";
            var imageFile = yield temp.open({prefix: 'ced', suffix: '.pl'}, $R());
            yield fs.write(imageFile.fd, imageContent, $R());
            var exampleContent = "foo(5):-builtin:true.";
            var exampleFile = yield temp.open({prefix: 'example', suffix: '.ced'}, $R());
            yield fs.write(exampleFile.fd, exampleContent, $R());
            var result = yield nodalion.findAll(X, ns.testLoadFile(imageFile.path, exampleFile.path, '/impred', X), $R());
            assert.deepEqual(result, [4, 5]);
        }))
        it('should support the loadedStatement() predicate', $T(function*() {
            var X = {var:'X'};
            var imageContent = "'/impred#foo'(6):-'builtin#true'.";
            var imageFile = yield temp.open({prefix: 'ced', suffix: '.pl'}, $R());
            yield fs.write(imageFile.fd, imageContent, $R());
            var exampleContent = "foo(7):-builtin:true.";
            var exampleFile = yield temp.open({prefix: 'example', suffix: '.ced'}, $R());
            yield fs.write(exampleFile.fd, exampleContent, $R());
            var result = yield nodalion.findAll(X, ns.testLoadFile2(imageFile.path, exampleFile.path, '/impred', X), $R());
            assert.deepEqual(result, [4, 5]);
        }))
    })
});
<commit_msg>loadSourceFile test<commit_after>"use strict";
var assert = require('assert');
var fs = require('fs');
var temp = require('temp');
var $S = require('suspend'), $R = $S.resume, $T = function(gen) { return function(done) { $S.run(gen, done); } };

var Nodalion = require('../nodalion.js');
var ns = Nodalion.namespace('/impred', ['testLocalStore', 'localStr', 'testNow', 'testUUID', 'testLocalQueue',
                                        'testBase64Encode', 'testBase64Decode', 'testLoadNamespace',
                                        'testLoadFile', 'testLoadFile2',
                                        'readSourceFile', 'task', 'assert', 'pred', 'retract']);

var nodalion = new Nodalion(__dirname + '/../../prolog/cedalion.pl', '/tmp/impred-ced.log');

describe('impred', function(){
    describe('local storage', function(){
        it('should allow storing and fetching local state', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testLocalStore(X), $R());
            assert.deepEqual(result, [ns.localStr('bar')]);
        }));
    });
    describe('local queue', function(){
        it('should allow enqueuing and dequeing data', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testLocalQueue(1, X), $R());
            assert.deepEqual(result, ['helloworld']);
        }));
        it('should allow checking if the queue is empty', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testLocalQueue(2, X), $R());
            assert.deepEqual(result, ['YNY']);
        }));

    });
    describe('now', function(){
        it('should return the current time', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testNow(X), $R());
            var list = result[0].meaning();
            assert(list[0] < list[1], list[0] + ' < ' + list[1]);
            assert(list[1] < list[2], list[1] + ' < ' + list[2]);
            assert(list[2] - list[0] < 1, (list[2] - list[0]) + ' < 1');
        }));
    });
    describe('uuid', function(){
        it('should return a unique ID each time it is called', $T(function*(){
            var X = {var:'X'};
            var result = yield nodalion.findAll(X, ns.testUUID(X), $R());
            var list = result[0].meaning();
            assert.notEqual(list[0], list[1]);
            assert.notEqual(list[2], list[1]);
            list.forEach(function(id) {
                // Should be at least 128 bits
                assert(id.length * 6 > 128, (id.length * 6) + ' > 128');
            });
        }));
    });
    describe('base64Encode(Plain)', function(){
        it('should base64-encode the given Plain text', $T(function*(){
            var X = {var:'X'};
            var plain = "the quick brown fox and so on and so forth....";
            var result = yield nodalion.findAll(X, ns.testBase64Encode(plain, X), $R());
            var enc = result[0];
            var buf = new Buffer(Buffer.byteLength(plain));
            buf.write(plain);
            assert.equal(enc, buf.toString('base64'));
        }));
    });
    describe('base64Decode(Enc)', function(){
        it('should decode the given base64-encoded string', $T(function*(){
            var X = {var:'X'};
            var plain = "the quick brown fox and so on and so forth....";
            var buf = new Buffer(Buffer.byteLength(plain));
            buf.write(plain);
            var result = yield nodalion.findAll(X, ns.testBase64Decode(buf.toString('base64'), X), $R());
            var dec = result[0];
            assert.equal(dec, plain);
        }));
    });
    describe('loadCedalionImage(FileName, Prep, PrepIn, PrepOut)', function(){
        it('should load clauses from the given file', $T(function*(){
            var X = {var:'X'};
            var content = "'/impred#foo'(1):-'builtin#true'. '/impred#foo'(2):-'builtin#true'. '/impred#foo'(3):-'builtin#true'.";
            var file = yield temp.open({prefix: 'ced', suffix: '.pl'}, $R());
            yield fs.write(file.fd, content, $R());
            var result = yield nodalion.findAll(X, ns.testLoadNamespace(file.path, X), $R());
            assert.deepEqual(result, [1, 2, 3]);
        }));
        it.skip('should load containers when needed', function(done){
            this.timeout(7000);
            $S.callback(function*() {
                var hash = "QmdHZHRfuJ2QBXfvaMr3ksh3gKyoxc15LhRhKgEKrf4wnj";
                var X = {var:'X'};
                var nns = Nodalion.namespace('/nodalion', ['testContainer']);
                var result = yield nodalion.findAll(X, nns.testContainer(hash, X), $R());
                assert.deepEqual(result, ['cloudlog']);
            })(done);
        });
    });
    var writeFile = $S.callback(function*(content) {
            var file = yield temp.open({prefix: 'example', suffix: '.ced'}, $R());
            yield fs.write(file.fd, content, $R());
            return file.path;
    });
    describe('readSourceFile(FileName, NS)', () => {
        it('should return a list of the statements in a file', $T(function*() {
            var fileName = yield writeFile("hello(World).", $R());
            var X = {var:'X'};
            var res = yield nodalion.findAll(X, ns.task(ns.readSourceFile(fileName, '/foo'), X, {var:'T'}), $R());
            assert.equal(res.length, 1); // One result
            res = res[0].meaning();
            assert.equal(res.length, 1); // One statement
            res = res[0];
            assert.equal(res.name, 'builtin#loadedStatement');
            assert.equal(res.args.length, 3);
            assert.equal(res.args[0], fileName);
            assert.equal(res.args[1].name, '/foo#hello');
            var varNames = res.args[2].meaning();
            assert.equal(varNames.length, 1);
            assert.equal(varNames[0].args[1], 'World');
        }));
    });
    describe('assert(Statement)', () => {
        it('should add the statement to the logic  program', $T(function*() {
            // Add /foo:bar(3):-builtin:true to the program
            var builtin = Nodalion.namespace('builtin', ['true']);
            var foo = Nodalion.namespace('/foo', ['bar']);
            var statement = {name: ":-", args: [foo.bar(3), builtin.true()]};
            yield nodalion.findAll({var: '_'}, ns.task(ns.assert(statement), {var: '_X'}, {var: '_T'}), $R());
            // Query /foo:bar(X)
            var X = {var:'X'};
            var res = yield nodalion.findAll(X, ns.pred(foo.bar(X)), $R());
            assert.deepEqual(res, [3]);
        }));
    });
    describe('retract(Statement)', () => {
        it('should remove the statement from the logic  program', $T(function*() {
            // Add /foo2:bar(4):-builtin:true and /foo2:bar(5):-builtin:true to the program
            var builtin = Nodalion.namespace('builtin', ['true']);
            var foo = Nodalion.namespace('/foo2', ['bar']);
            yield nodalion.findAll({var: '_'}, ns.task(ns.assert({name: ":-", args: [foo.bar(4), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R());
            yield nodalion.findAll({var: '_'}, ns.task(ns.assert({name: ":-", args: [foo.bar(5), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R());
            // Remove /foo2:bar(4):-builtin:true
            yield nodalion.findAll({var: '_'}, ns.task(ns.retract({name: ":-", args: [foo.bar(4), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R());
            // Query /foo:bar(X)
            var X = {var:'X'};
            var res = yield nodalion.findAll(X, ns.pred(foo.bar(X)), $R());
            assert.deepEqual(res, [5]);
        }));
    });
    describe('loadSourceFile(FileName, Prep, PrepIn, PrepOut)', () => {
        it('should load a cedalion source file on top of an image', $T(function*() {
            var X = {var:'X'};
            var imageContent = "'/impred#foo'(4):-'builtin#true'.";
            var imageFile = yield temp.open({prefix: 'ced', suffix: '.pl'}, $R());
            yield fs.write(imageFile.fd, imageContent, $R());
            var exampleContent = "foo(5):-builtin:true.";
            var exampleFile = yield temp.open({prefix: 'example', suffix: '.ced'}, $R());
            yield fs.write(exampleFile.fd, exampleContent, $R());
            var result = yield nodalion.findAll(X, ns.testLoadFile(imageFile.path, exampleFile.path, '/impred', X), $R());
            assert.deepEqual(result, [4, 5]);
        }))
        it('should support the loadedStatement() predicate', $T(function*() {
            var X = {var:'X'};
            var imageContent = "'/impred#foo'(6):-'builtin#true'.";
            var imageFile = yield temp.open({prefix: 'ced', suffix: '.pl'}, $R());
            yield fs.write(imageFile.fd, imageContent, $R());
            var exampleContent = "foo(7):-builtin:true.";
            var exampleFile = yield temp.open({prefix: 'example', suffix: '.ced'}, $R());
            yield fs.write(exampleFile.fd, exampleContent, $R());
            var result = yield nodalion.findAll(X, ns.testLoadFile2(imageFile.path, exampleFile.path, '/impred', X), $R());
            assert.deepEqual(result, [7]);
        }))
    })
});
<|endoftext|>


<commit_before>/*jslint node: true, vars: true, indent: 4 */
(function (module, __dirname) {
    "use strict";

    var debug = require("./debug"),
        hbars = require("handlebars"),
        connect = require("connect"),
        path = require("path"),
        fs = require("fs");

    function locate(localDir, publicDir, file, cb) {
        var localFile = path.join(localDir, file),
            publicFile = path.join(publicDir, file);

        return path.exists(localFile, function (exists) {
            return cb(exists ? localFile : publicFile);
        });
    }

    function assemble(module, res, source) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(source);
    }

    function indexMaker(module, templates, req, res, next) {
        if (req.url !== '/') {
            return next();
        }

        /*
         * Load the index file. Sites can specify their own index. The index
         * can either be the name of the file to load or a function that actually
         * load the file and returns the file. Functions have to return the data
         * using a callback function that works like the callback function of
         * fs.readFile.
         */
        var index = module.index || path.join(templates, "index.html"),
            indexLoader = (typeof index === "function") ? index : function (cb) {
                return fs.readFile(index, "utf8", cb);
            };

        return indexLoader(function (err, data) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'text/html'});
                res.end('
Internal Error
');
            }

            return assemble(module, res, data);
        });
    }

    function getIndexMaker(module, templates) {
        return function (req, res, next) {
            return indexMaker(module, templates, req, res, next);
        };
    }

    function Site(mod) {
        this.module = mod;
    }

    Site.prototype.start = function (app, cb) {
        var hostname = this.module.hostname;

        if (!hostname) {
            return cb(new Error("no hostname defined for module " + this.module));
        }

        var site = connect.createServer(),
            vhost = connect.vhost(hostname, site);

        app.use(vhost);

        var staticOpts = this.module.staticOptions || { /* maxAge: oneDay */ };

        /*
         * Load static files from the module
         */
        if (this.module.public) {
            site.use(connect.static(this.module.public, staticOpts));
        }

        /*
         * Global pub dir
         */
        var smhome = path.join(__dirname, ".."),
            templates = path.join(smhome, "templates"),
            pub = path.join(smhome, "public");

        /*
         * Fav icon
         */
        locate(this.module.public, pub, "favicon.ico", function (icon) {
            debug(hostname, "using", icon);
            app.use(connect.favicon(icon));
        });

        /*
         * Load static files from the site-manager
         */
        site.use(connect.static(pub, staticOpts));
        site.use(getIndexMaker(this.module, templates));
    };

    module.exports = function (app, mod, cb) {
        debug("starting", mod);
        var site = new Site(mod);

        return site.start(app, cb);
    };
})(module, __dirname);
<commit_msg>now executing the template<commit_after>/*jslint node: true, vars: true, indent: 4 */
(function (module, __dirname) {
    "use strict";

    var debug = require("./debug"),
        hbars = require("handlebars"),
        connect = require("connect"),
        path = require("path"),
        fs = require("fs");

    function locate(localDir, publicDir, file, cb) {
        var localFile = path.join(localDir, file),
            publicFile = path.join(publicDir, file);

        return path.exists(localFile, function (exists) {
            return cb(exists ? localFile : publicFile);
        });
    }

    function assemble(module, res, source) {
        var template = hbars.compile(source),
            result = template();

        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(result);
    }

    function indexMaker(module, templates, req, res, next) {
        if (req.url !== '/') {
            return next();
        }

        /*
         * Load the index file. Sites can specify their own index. The index
         * can either be the name of the file to load or a function that actually
         * load the file and returns the file. Functions have to return the data
         * using a callback function that works like the callback function of
         * fs.readFile.
         */
        var index = module.index || path.join(templates, "index.html"),
            indexLoader = (typeof index === "function") ? index : function (cb) {
                return fs.readFile(index, "utf8", cb);
            };

        return indexLoader(function (err, data) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'text/html'});
                res.end('
Internal Error
');
            }

            return assemble(module, res, data);
        });
    }

    function getIndexMaker(module, templates) {
        return function (req, res, next) {
            return indexMaker(module, templates, req, res, next);
        };
    }

    function Site(mod) {
        this.module = mod;
    }

    Site.prototype.start = function (app, cb) {
        var hostname = this.module.hostname;

        if (!hostname) {
            return cb(new Error("no hostname defined for module " + this.module));
        }

        var site = connect.createServer(),
            vhost = connect.vhost(hostname, site);

        app.use(vhost);

        var staticOpts = this.module.staticOptions || { /* maxAge: oneDay */ };

        /*
         * Load static files from the module
         */
        if (this.module.public) {
            site.use(connect.static(this.module.public, staticOpts));
        }

        /*
         * Global pub dir
         */
        var smhome = path.join(__dirname, ".."),
            templates = path.join(smhome, "templates"),
            pub = path.join(smhome, "public");

        /*
         * Fav icon
         */
        locate(this.module.public, pub, "favicon.ico", function (icon) {
            debug(hostname, "using", icon);
            app.use(connect.favicon(icon));
        });

        /*
         * Load static files from the site-manager
         */
        site.use(connect.static(pub, staticOpts));
        site.use(getIndexMaker(this.module, templates));
    };

    module.exports = function (app, mod, cb) {
        debug("starting", mod);
        var site = new Site(mod);

        return site.start(app, cb);
    };
})(module, __dirname);
<|endoftext|>


<commit_before>import ServiceLookup from '../../../shared/lib/service-lookup';

var Plugin = {};
Plugin.register = function(server, options, next) {
  server.ext('onPreResponse', function (request, reply) {
    if(ServiceLookup.getService() == 'true'){
      return reply.view('service-down');
    } else {
      reply.continue();
    }
  });
  next();
};

Plugin.register.attributes = {
  name: 'serviceUpDown',
  version: '0.1'
};

module.exports = Plugin;<commit_msg>check if request is static<commit_after>import ServiceLookup from '../../../shared/lib/service-lookup';

var Plugin = {};
Plugin.register = function(server, options, next) {
  server.ext('onPreResponse', function (request, reply) {
    if((ServiceLookup.getService() == 'true') && !(request.url.path.startsWith('/assets/'))){
      return reply.view('service-down');
    } else {
      reply.continue();
    }
  });
  next();
};

Plugin.register.attributes = {
  name: 'serviceUpDown',
  version: '0.1'
};

module.exports = Plugin;<|endoftext|>


<commit_before>;(function() {
    var PROTOCOL_PATTERN = /^(http|ws|wss|https):\/\//;

    if (!Function.prototype.bind) { // check if native implementation available
        Function.prototype.bind = function(){
            var fn = this;
            var args = Array.prototype.slice.call(arguments);
            var object = args.shift();

            return function() {
                return fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
            };
        };
    }

    function WebSocketClient(url) {
        this.onMessage = null;
        this.onError = null;
        this.errors = 0;

        var protocolMatch = PROTOCOL_PATTERN.exec(url)[1];

        if(protocolMatch === "https") {
            this.url = url.replace(PROTOCOL_PATTERN, "wss://");
        } else if(protocolMatch === "http") {
            this.url = url.replace(PROTOCOL_PATTERN, "ws://");
        } else {
            this.url = url;
        }

        this._init();
    }

    WebSocketClient.prototype = {
        type: 'websocket',
        onMessage: null,
        onError: null,
        errors: 0,
        url: null,
        queue: [],

        _init: function() {
            this._socket = new WebSocket(this.url);
            this._socket.onmessage = this._handleMessage.bind(this);
            this._socket.onerror = this._handleError.bind(this);
        },

        _handleMessage: function(message) {
            var json = null;

            try {
                json = JSON.parse(message.data);
            } catch(e) {
                if(this.onerror) {
                    this.onerror('receiveJunk', 'Received non-JSON message from the server');
                }
            }

            if(json) {
                if(json.type == 'message') {
                    this.onmessage(json.payload);
                } else if(json.type == 'error' && json.payload) {
                    this.onerror(json.payload.errorName, json.payload.message);
                } else {
                    this.onerror('receiveBadServerJSON', 'Received bad JSON message from the server');
                }
            }
        },

        _handleError: function(error) {
            // handle the error, then try to reconnect.
            if(this.onerror) {
                this.onerror('connect', 'Could not connect');
            }

            this.errors++;
            setTimeout(this._init, 1000 * this.errors * this.errors);
        },

        send: function(json) {
            var data = JSON.stringify(json);
            var self = this;

            var lazySend = function() {
                if(self._socket.readyState != self._socket.OPEN) {
                    setTimeout(lazySend, 1);
                } else {
                    self._socket.send(data);
                }
            };

            lazySend();
        },

        close: function() {
            this._socket.close();
        }
    };

    function LongPollingClient(url) {
        var protocolMatch = PROTOCOL_PATTERN.exec(url)[1];

        if(protocolMatch === "wss") {
            this.url = url.replace(PROTOCOL_PATTERN, "https://");
        } else if(protocolMatch === "ws") {
            this.url = url.replace(PROTOCOL_PATTERN, "http://");
        } else {
            this.url = url;
        }

        this._init();
    }

    LongPollingClient.prototype = {
        type: 'longpolling',
        clientId: null,
        errors: 0,

        _init: function() {
            // set up the long-polling mechanisms.
            var self = this;

            var connect = function() {
                var socket = self._createXHR();
                self._socket = socket;

                socket.onreadystatechange = function() {
                    // summary:
                    //          Handles the response for the long-polling
                    //          request.

                    if(socket.readyState == 4) {
                        if(socket.status >= 200 && socket.status <= 299) {
                            // Unlike for websockets, the longpolling responses
                            // come back as an array. Parse it here.
                            console.log('received' + socket.responseText);

                            var json = JSON.parse(socket.responseText);
                            var payload = json.payload;

                            // Iterate through the events and fire them all out.
                            if(self.onmessage) {
                                for(var i=0, len=payload.length; i<len; i++) {
                                    self.onmessage(payload[i]);
                                }
                            }

                            // Grab the lastEventId.
                            self.clientId = json.clientId;

                            // Reopen the connection immediately.
                            connect();
                        } else {
                            // handle the error, then try to reconnect.
                            if(self.onerror) self.onerror(socket);
                            self.errors++;
                            setTimeout(connect, 1000 * self.errors * self.errors);
                        }
                    }
                };

                // use the date/time suffix for anti-caching and use the
                // clientId to 'catch up' with events we missed.
                var time = (new Date()).getTime();

                if(self.clientId != null) {
                    var queryString = "?clientId=" + self.clientId + "&" + time;
                } else {
                    var queryString = "?" + time;
                }

                // start the connection.
                socket.open("GET", self.url + queryString, true);
                socket.send();
            };

            connect();
        },

        send: function(data) {
            var xhr = this._createXHR();

            xhr.onReadyStateChange = function() {
                if(xhr.readyState == 4 && (xhr.status < 200 || xhr.status > 299)) {
                    if(this.onerror) this.onerror(xhr);
                }
            }

            xhr.open("POST", this.url, true);
            xhr.setRequestHeader("Content-type","application/json");
            xhr.send(JSON.stringify(data));
        },

        close: function() {
            if(this._socket && this._socket.readyState != 4) {
                this._socket.abort();
            }
        },

        _createXHR: function() {
            // summary:
            //          creates an XHR object for AJAX...
            // return:
            //          In all normal browsers: XMLHttpRequest,
            //          IE6: ActiveXObject.

            if(window.XMLHttpRequest) {
                return new XMLHttpRequest();
            } else {
                try {
                    return new ActiveXObject("Msxml2.XMLHTTP");
                } catch(e) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
        }
    };

    function comet(url) {
        var cls = window.WebSocket ? WebSocketClient : LongPollingClient;
        return new cls(url);
    }

    this.comet = comet;
})(window);<commit_msg>Added documentation to client code<commit_after>;(function() {
    //Pattern for determing the protocol of a url
    var PROTOCOL_PATTERN = /^(http|ws|wss|https):\/\//;

    //Don't add the method to the function prototype if a native implementation
    //already exists. Based on the prototype.js implementation.
    if (!Function.prototype.bind) {
        //Exposes a mechanism for binding a function's scope to a specified
        //object
        Function.prototype.bind = function() {
            var fn = this;
            var args = Array.prototype.slice.call(arguments);
            var object = args.shift();

            return function() {
                return fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
            };
        };
    }

    //Comet implementation that uses websockets
    function WebSocketClient(url) {
        //Change the URL from http://... to ws://... if necessary
        var protocolMatch = PROTOCOL_PATTERN.exec(url)[1];

        if(protocolMatch === "https") {
            this.url = url.replace(PROTOCOL_PATTERN, "wss://");
        } else if(protocolMatch === "http") {
            this.url = url.replace(PROTOCOL_PATTERN, "ws://");
        } else {
            this.url = url;
        }

        this._init();
    }

    WebSocketClient.prototype = {
        type: 'websocket',
        onmessage: null,
        onerror: null,
        errors: 0,
        url: null,
        queue: [],

        //Creates a new websocket and adds event listeners
        _init: function() {
            this._socket = new WebSocket(this.url);
            this._socket.onmessage = this._handleMessage.bind(this);
            this._socket.onerror = this._handleError.bind(this);
        },

        //Called when a message is received from the websocket
        _handleMessage: function(message) {
            var json = null;

            //Try to parse the JSON and throw an error if it fails
            try {
                json = JSON.parse(message.data);
            } catch(e) {
                if(this.onerror) {
                    this.onerror('receiveJunk', 'Received non-JSON message from the server');
                }
            }

            if(json) {
                if(json.type == 'message') {
                    //Call the message event listener if it's a message
                    this.onmessage(json.payload);
                } else if(json.type == 'error' && json.payload) {
                    //Call the error event listener if it's an error
                    this.onerror(json.payload.errorName, json.payload.message);
                } else {
                    //The server-sent JSON does not follow expected standards
                    this.onerror('receiveBadServerJSON', 'Received bad JSON message from the server');
                }
            }
        },

        //Call the error listener, then try to reconnect
        _handleError: function(error) {
            if(this.onerror) {
                this.onerror('connect', 'Could not connect');
            }

            this.errors++;
            setTimeout(this._init, 1000 * this.errors * this.errors);
        },

        //Sends a message to the server
        send: function(json) {
            var data = JSON.stringify(json);
            var self = this;

            //Keep trying to send the message until we're connected to the
            //server
            var lazySend = function() {
                if(self._socket.readyState != self._socket.OPEN) {
                    setTimeout(lazySend, 1);
                } else {
                    self._socket.send(data);
                }
            };

            lazySend();
        },

        //Closes the connection
        close: function() {
            this._socket.close();
        }
    };

    //Comet implementation that uses long polling
    function LongPollingClient(url) {
        //If the user accidently sent a websocket url, change it back to http
        var protocolMatch = PROTOCOL_PATTERN.exec(url)[1];

        if(protocolMatch === "wss") {
            this.url = url.replace(PROTOCOL_PATTERN, "https://");
        } else if(protocolMatch === "ws") {
            this.url = url.replace(PROTOCOL_PATTERN, "http://");
        } else {
            this.url = url;
        }

        this._init();
    }

    LongPollingClient.prototype = {
        type: 'longpolling',
        clientId: null,
        errors: 0,

        //Sets up the long-polling mechanisms
        _init: function() {
            var self = this;

            //Connects to the server using xhr
            var connect = function() {
                var socket = self._createXHR();
                self._socket = socket;

                //Handles a response from the xhr object
                socket.onreadystatechange = function() {
                    if(socket.readyState == 4) {
                        if(socket.status >= 200 && socket.status <= 299) {
                            //Parse the response
                            var json = JSON.parse(socket.responseText);
                            var payload = json.payload;

                            // Iterate through the events and fire them all out.
                            if(self.onmessage) {
                                for(var i=0, len=payload.length; i<len; i++) {
                                    self.onmessage(payload[i]);
                                }
                            }

                            //Grab the client id
                            self.clientId = json.clientId;

                            //Reopen the connection immediately.
                            connect();
                        } else {
                            //Handle the error, then try to reconnect.
                            if(self.onerror) self.onerror(socket);
                            self.errors++;
                            setTimeout(connect, 1000 * self.errors * self.errors);
                        }
                    }
                };

                // use the date/time suffix for anti-caching and use the
                // clientId to 'catch up' with events we missed.
                var time = (new Date()).getTime();

                if(self.clientId != null) {
                    var queryString = "?clientId=" + self.clientId + "&" + time;
                } else {
                    var queryString = "?" + time;
                }

                // start the connection.
                socket.open("GET", self.url + queryString, true);
                socket.send();
            };

            connect();
        },

        //Sends a message to the server
        send: function(data) {
            var xhr = this._createXHR();

            //Handles a response from the xhr object
            xhr.onReadyStateChange = function() {
                if(xhr.readyState == 4 && (xhr.status < 200 || xhr.status > 299)) {
                    if(this.onerror) this.onerror(xhr);
                }
            }

            //Send the message
            xhr.open("POST", this.url, true);
            xhr.setRequestHeader("Content-type","application/json");
            xhr.send(JSON.stringify(data));
        },

        //Close the socket
        close: function() {
            if(this._socket && this._socket.readyState != 4) {
                this._socket.abort();
            }
        },

        //Creates an XHR object for AJAX
        _createXHR: function() {
            if(window.XMLHttpRequest) {
                return new XMLHttpRequest();
            } else {
                try {
                    return new ActiveXObject("Msxml2.XMLHTTP");
                } catch(e) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
        }
    };

    //Creates a comet connection based on the capabilities of the client
    function comet(url) {
        var cls = window.WebSocket ? WebSocketClient : LongPollingClient;
        return new cls(url);
    }

    this.comet = comet;
})(window);<|endoftext|>


<commit_before>import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/fromPromise'
import 'rxjs/add/operator/mergeMap'

global.self = global
require('imports?this=>global!exports?global.fetch!isomorphic-fetch')

export default function fetchJSON(url) {
  return Observable.fromPromise(fetch(url))
    .mergeMap(response => response.json())
}
<commit_msg>Handle non-json in authEndpoint (#553)<commit_after>import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/fromPromise'
import 'rxjs/add/operator/mergeMap'

global.self = global
require('imports?this=>global!exports?global.fetch!isomorphic-fetch')

export default function fetchJSON(url) {
  return Observable.fromPromise(fetch(url))
    .mergeMap(response => {
      const contentType = response.headers.get('content-type')
      if (contentType && contentType.indexOf('application/json') !== -1) {
        return response.json()
      } else {
        return response.text().then(resp => ({
          error: 'Response was not json',
          responseBody: resp,
        }))
      }
    })
}
<|endoftext|>


<commit_before>/*
 * This file is part of the Kreta package.
 *
 * (c) Beñat Espiña <benatespina@gmail.com>
 * (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import './../../../../scss/views/page/issue/_show.scss';

import React from 'react';
import $ from 'jquery';

import {Issue} from '../../../models/Issue.js';
import UserImage from '../../component/UserImage.js';
import IssueField from '../../component/IssueField.js';
import HelpText from '../../component/HelpText.js';
import Selector from '../../component/Selector.js';
import Button from '../../component/Button.js';
import {FormSerializerService} from '../../../service/FormSerializer.js';
import {NotificationService} from '../../../service/Notification.js';

export default React.createClass({
  propTypes: {
    issue: React.PropTypes.object.isRequired,
    project: React.PropTypes.object.isRequired
  },
  getInitialState() {
    return {
      issueChanged: false,
      issue: this.props.issue
    };
  },
  componentWillReceiveProps: function(nextProps) {
    this.setState({
      issue: nextProps.issue,
      issueChanged: false
    });
  },
  selectorChanged(value, name) {
    /*this.setState({
      issue: this.state.issue.set(name, {id: value}),
      issueChanged: true
    });*/
  },
  updateInput(ev) {
    this.setState({
      issue: this.state.issue.set(ev.target.name, ev.target.value),
      issueChanged: true
    });
  },
  doTransition(id) {
    this.state.issue.doTransition(id, {
      success : (data) => {
        this.setState({issue: this.state.issue.set(data)});
      }
    });
  },
  getProjectOptions() {
    var project = App.collection.project.get(this.props.project.id);
    if(!project) {
      return {
        asignee: [],
        priority: [],
        type: []
      };
    }
    var assignee = project.get('participants').map((p) => {
        let assignee = `${p.user.first_name} ${p.user.last_name}`;
        if ('' === p.user.first_name) {
          assignee = p.user.username;
        }

      return (
        <IssueField image={<UserImage user={p.user}/>}
                    key={p.user.id}
                    label="Assigned to"
                    text={assignee}
                    value={p.user.id}/>
      );

    }),
    priority = project.get('issue_priorities').map((p) => {
      return (
        <IssueField image={}
                    key={p.id}
                    label="Priority"
                    text={p.name}
                    value={p.id}/>
      );
    });

    return {assignee, priority};
  },
  save(ev) {
    ev.preventDefault();

    const issue = FormSerializerService.serialize(
      $(this.refs.form), Issue
    );

    this.setState({issueChanged: false});
    issue.save(null, {
      success: () => {
        NotificationService.showNotification({
          type: 'success',
          message: 'Issue edited successfully'
        });
      }, error: () => {
        NotificationService.showNotification({
          type: 'error',
          message: 'Error while editing this issue'
        });
      }
    });
  },
  render() {
    const issue = this.state.issue.toJSON();
    const options = this.getProjectOptions();
    let saveButton = <HelpText text="You can change issue details inline"/>;
    if(this.state.issueChanged) {
      saveButton = <Button color="green" type="submit">Done</Button>;
    }
    const allowedTransitions = this.state.issue.getAllowedTransitions().map((transition, index) => {
      return (
        <Button color="green"
                key={index}
                onClick={this.doTransition.bind(this, transition.id)}>
          {transition.name}
        </Button>
      );
    });
    return (
      <form className="issue-show"
            onSubmit={this.save}
            ref="form">
        <input name="id" type="hidden" value={issue.id}/>
        <input name="project" type="hidden" value={this.props.project.id}/>
        <input className="issue-show__title"
               name="title"
               onChange={this.updateInput}
               value={issue.title}/>

          {allowedTransitions}

          <Selector disabled={true}
                    name="assignee"
                    onChange={this.selectorChanged}
                    value={issue.assignee.id}>
            {options.assignee}
          </Selector>
          <Selector disabled={true}
                    name="priority"
                    onChange={this.selectorChanged}
                    value={issue.priority.id}>
            {options.priority}
          </Selector>

        <textarea className="issue-show__description"
                  name="description"
                  onChange={this.updateInput}
                  value={issue.description}/>

          {saveButton}

      </form>
    );
  }
});
<commit_msg>Replaced form by Form component in issue show page<commit_after>/*
 * This file is part of the Kreta package.
 *
 * (c) Beñat Espiña <benatespina@gmail.com>
 * (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import './../../../../scss/views/page/issue/_show.scss';

import React from 'react';

import {Issue} from '../../../models/Issue.js';
import Button from '../../component/Button.js';
import Form from '../../component/Form.js';
import HelpText from '../../component/HelpText.js';
import IssueField from '../../component/IssueField.js';
import Selector from '../../component/Selector.js';
import UserImage from '../../component/UserImage.js';

export default React.createClass({
  propTypes: {
    issue: React.PropTypes.object.isRequired,
    project: React.PropTypes.object.isRequired
  },
  getInitialState() {
    return {
      issueChanged: false,
      issue: this.props.issue
    };
  },
  componentWillReceiveProps: function(nextProps) {
    this.setState({
      issue: nextProps.issue,
      issueChanged: false
    });
  },
  selectorChanged(value, name) {
    /*this.setState({
      issue: this.state.issue.set(name, {id: value}),
      issueChanged: true
    });*/
  },
  updateInput(ev) {
    this.setState({
      issue: this.state.issue.set(ev.target.name, ev.target.value),
      issueChanged: true
    });
  },
  doTransition(id) {
    this.state.issue.doTransition(id, {
      success : (data) => {
        this.setState({issue: this.state.issue.set(data)});
      }
    });
  },
  getProjectOptions() {
    var project = App.collection.project.get(this.props.project.id);
    if(!project) {
      return {
        asignee: [],
        priority: [],
        type: []
      };
    }
    var assignee = project.get('participants').map((p) => {
        let assignee = `${p.user.first_name} ${p.user.last_name}`;
        if ('' === p.user.first_name) {
          assignee = p.user.username;
        }

      return (
        <IssueField image={<UserImage user={p.user}/>}
                    key={p.user.id}
                    label="Assigned to"
                    text={assignee}
                    value={p.user.id}/>
      );

    }),
    priority = project.get('issue_priorities').map((p) => {
      return (
        <IssueField image={}
                    key={p.id}
                    label="Priority"
                    text={p.name}
                    value={p.id}/>
      );
    });

    return {assignee, priority};
  },
  onIssueSaved() {
    this.setState({issueChanged: false});
  },
  render() {
    const issue = this.state.issue.toJSON();
    const options = this.getProjectOptions();
    let saveButton = <HelpText text="You can change issue details inline"/>;
    if(this.state.issueChanged) {
      saveButton = <Button color="green" type="submit">Done</Button>;
    }
    const allowedTransitions = this.state.issue.getAllowedTransitions().map((transition, index) => {
      return (
        <Button color="green"
                key={index}
                onClick={this.doTransition.bind(this, transition.id)}>
          {transition.name}
        </Button>
      );
    });
    return (
      <Form model={Issue}
            onSaveSuccess={this.onIssueSaved}>
        <input name="id" type="hidden" value={issue.id}/>
        <input name="project" type="hidden" value={this.props.project.id}/>
        <input className="issue-show__title"
               name="title"
               onChange={this.updateInput}
               value={issue.title}/>

          {allowedTransitions}

          <Selector disabled={true}
                    name="assignee"
                    onChange={this.selectorChanged}
                    value={issue.assignee.id}>
            {options.assignee}
          </Selector>
          <Selector disabled={true}
                    name="priority"
                    onChange={this.selectorChanged}
                    value={issue.priority.id}>
            {options.priority}
          </Selector>

        <textarea className="issue-show__description"
                  name="description"
                  onChange={this.updateInput}
                  value={issue.description}/>

          {saveButton}

      </Form>
    );
  }
});
<|endoftext|>


<commit_before>'use strict'

const Https = require('https')
const ParseString = require('xml2js').parseString

function run (msg, text) {
	msg.say('Lets play a word association game, tell me a word first.')
		.route('deviantart_response')
}

function DeviantArtResponse (msg) {
	// Make ajax request to deviant art random url
	var text = (msg.body.event && msg.body.event.text) || ''
	var url = 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?'
	console.log(url)
	Https.get(url, function(res) {
		res.setEncoding('utf8');
		let raw_data = '';
		res.on('data', (chunk) => { raw_data += chunk; });
		console.log('Here is raw data')
		// console.log(raw_data)
		res.on('end', () => {
			try {
				// console.log(raw_data)
				ParseString(raw_data, function (err, result) {
					console.log('Parsed raw_data')
					console.log(result)
				})
				// var parser = new DOMParser();
				// var xml_doc = parser.paserFromString(raw_data, 'text/xml')

				// console.log(xml_doc)

				// const parsed_data = JSON.parse(raw_data);
				// var page_id = Object.keys(parsed_data.query.pages)[0]
				// var title = parsed_data.query.pages[page_id].title
				// var extract = parsed_data.query.pages[page_id].extract
				// msg.say({
				// 	text: 'Tell me what you think of this random Wikipedia article:',
				// 		'attachments': [
				// 		{
				// 			"fallback": '',
				// 			"color": '',
				// 			"pretext": '',
				// 			"title": title,
				// 			"title_link": 'https://en.wikipedia.org/wiki?curid=' + page_id,
				// 			"text": extract.replace(/<(?:.|\n)*?>/gm, ''),
				// 		}]
				// 	})
				// 	.route('wikipedia_response')
			} catch (e) {
				console.error(e.message);
			}
		});
	}).on('error', function(e) {
		console.log('Got error: ' + e.message)
	})
	// Creature-bot returns the wikipedia page url in message
}

module.exports = {
	run: run,
	DeviantArtResponse:  DeviantArtResponse
}
<commit_msg>Attempting to traverse object.<commit_after>'use strict'

const Https = require('https')
const ParseString = require('xml2js').parseString

function run (msg, text) {
	msg.say('Lets play a word association game, tell me a word first.')
		.route('deviantart_response')
}

function DeviantArtResponse (msg) {
	// Make ajax request to deviant art random url
	var text = (msg.body.event && msg.body.event.text) || ''
	var url = 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?'
	console.log(url)
	Https.get(url, function(res) {
		res.setEncoding('utf8');
		let raw_data = '';
		res.on('data', (chunk) => { raw_data += chunk; });
		console.log('Here is raw data')
		// console.log(raw_data)
		res.on('end', () => {
			try {
				// console.log(raw_data)
				ParseString(raw_data, function (err, result) {
					console.log('Parsed raw_data')
					console.log(result.feed.entry[0])
				})
				// var parser = new DOMParser();
				// var xml_doc = parser.paserFromString(raw_data, 'text/xml')

				// console.log(xml_doc)

				// const parsed_data = JSON.parse(raw_data);
				// var page_id = Object.keys(parsed_data.query.pages)[0]
				// var title = parsed_data.query.pages[page_id].title
				// var extract = parsed_data.query.pages[page_id].extract
				// msg.say({
				// 	text: 'Tell me what you think of this random Wikipedia article:',
				// 		'attachments': [
				// 		{
				// 			"fallback": '',
				// 			"color": '',
				// 			"pretext": '',
				// 			"title": title,
				// 			"title_link": 'https://en.wikipedia.org/wiki?curid=' + page_id,
				// 			"text": extract.replace(/<(?:.|\n)*?>/gm, ''),
				// 		}]
				// 	})
				// 	.route('wikipedia_response')
			} catch (e) {
				console.error(e.message);
			}
		});
	}).on('error', function(e) {
		console.log('Got error: ' + e.message)
	})
	// Creature-bot returns the wikipedia page url in message
}

module.exports = {
	run: run,
	DeviantArtResponse:  DeviantArtResponse
}
<|endoftext|>


<commit_before>"usr strict";

const { run, extractSummary } = require("../../../testUtils");

test("array", () => {
	const { code, stdout, stderr } = run(__dirname, [
		"--config",
		"./webpack.config.js",
		"--target",
		"async-node",
		"--mode",
		"production"
	]);

	const summary = extractSummary(stdout);

	expect(code).toBe(0);
	expect(summary).toEqual(expect.anything());
	expect(summary).toContain("Child");
	expect(summary).toContain("entry-a.bundle.js");
	expect(summary).toContain("Child");
	expect(summary).toContain("entry-b.bundle.js");
	expect(stderr).toHaveLength(0);
});
<commit_msg>fix: change "usr strict" to "use strict"<commit_after>"use strict";

const { run, extractSummary } = require("../../../testUtils");

test("array", () => {
	const { code, stdout, stderr } = run(__dirname, [
		"--config",
		"./webpack.config.js",
		"--target",
		"async-node",
		"--mode",
		"production"
	]);

	const summary = extractSummary(stdout);

	expect(code).toBe(0);
	expect(summary).toEqual(expect.anything());
	expect(summary).toContain("Child");
	expect(summary).toContain("entry-a.bundle.js");
	expect(summary).toContain("Child");
	expect(summary).toContain("entry-b.bundle.js");
	expect(stderr).toHaveLength(0);
});
<|endoftext|>


<commit_before>/////////////////////////////////////////////////
// Map
// Initialise the map, set center, zoom, etc.
/////////////////////////////////////////////////
var map = L.map('map').setView([51.505, -0.09], 13);
var filterLibrariesMap = function () { };

L.tileLayer('http://{s}.tiles.mapbox.com/v3/librarieshacked.jefmk67b/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

//////////////////////////////////////////////////////
// Autocomplete address search
// Initial code to set up the autocomplete search box
//////////////////////////////////////////////////////
var placeSearch, autocomplete;

function initAutocomplete() {
    autocomplete = new google.maps.places.Autocomplete((document.getElementById('txtAddressSearch')), { types: ['geocode'] });
    autocomplete.addListener('place_changed', populateNearest);
}

function populateNearest() {
    $('#divNearest').show();
    $('#divNearest').empty();
    $('#divNearestAdditional').empty();
    var place = autocomplete.getPlace();
    var lat = place.geometry.location.lat();
    var lng = place.geometry.location.lng();
    SomersetMobiles.setCurrentDistances(lat, lng);
    var nearest = SomersetMobiles.getNearest();
    var nearestStop = SomersetMobiles.data[nearest];
    $('#divNearest').html('Nearest stop ' + nearestStop.Location + ', ' + nearestStop.Town + '.  Arriving in ' + nearestStop.Due + ' (' + moment(nearestStop.DueSystem).format('DD/MM/YYYY hh:mm') + ')');
}

//////////////////////////////////////////////////
// Following relies on jQuery etc so wait for page to complete
//////////////////////////////////////////////////
$(function () {
    //////////////////////////////////////////////////
    // Load Data
    //
    /////////////////////////////////////////////////
    SomersetMobiles.loadData(function () {

        var setCurrentPositions = function () {
            // Set current positions.
            var tauntonCurrent = SomersetMobiles.getCurrentLocation('Taunton');
            var tauntonNext = SomersetMobiles.getNextLocation('Taunton');
            if (tauntonCurrent != null) {
                $('#spTauntonCurrentPosition').html('Currently at ' + SomersetMobiles.data[tauntonCurrent]['Location'] + ', ' + SomersetMobiles.data[tauntonCurrent]['Town'] + ' for another ' + moment(SomersetMobiles.data[tauntonCurrent]['DepartingSystem']).diff(moment(), 'minutes') + ' minutes');
            } else {
                $('#spTauntonCurrentPosition').html('Arriving at ' + SomersetMobiles.data[tauntonNext]['Location'] + ', ' + SomersetMobiles.data[tauntonNext]['Town'] + ' ' + SomersetMobiles.data[tauntonNext]['Due'] + '');
            }
            var wellsCurrent = SomersetMobiles.getCurrentLocation('Wells');
            var wellsNext = SomersetMobiles.getNextLocation('Wells');
            if (wellsCurrent != null) {
                $('#spWellsCurrentPosition').html('Currently at ' + SomersetMobiles.data[wellsCurrent]['Location'] + ', ' + SomersetMobiles.data[wellsCurrent]['Town'] + ' for another ' + moment(SomersetMobiles.data[wellsCurrent]['DepartingSystem']).diff(moment(), 'minutes') + ' minutes');
            } else {
                $('#spWellsCurrentPosition').html('Arriving at ' + SomersetMobiles.data[wellsNext]['Location'] + ', ' + SomersetMobiles.data[wellsNext]['Town'] + ' ' + SomersetMobiles.data[wellsNext]['Due'] + '');
            }
        };
        setCurrentPositions();
        var markersArrays = {};
        var markerGroups = {};
        var markersBounds = {};
        $.each(SomersetMobiles.data, function (key, val) {
            // Add items to the map.
            if (val.Lat && val.Lat != 'TODO') {
                var popup = L.popup({
                    maxWidth: 160,
                    maxHeight: 140,
                    closeButton: false,
                    className: ''
                }).setContent('
' + val.Location + ', ' + val.Town + '
Date ' + moment(val.DueSystem).format('DD MMM YYYY hh:mm') + '');
                var className = 'taunton';

                // Set up the associative arrays for layers and bounds
                if (!markersArrays[val.RouteId]) markersArrays[val.RouteId] = [];
                if (!markersBounds[val.RouteId]) markersBounds[val.RouteId] = [];

                if (val.Library == 'Taunton') className = 'wells';
                var stopIcon = L.divIcon({ html: '
' + val.Route + '
', className: "marker-cluster marker-cluster-" + className, iconSize: new L.Point(20, 20) });
                markersArrays[val.RouteId].push(L.marker([val.Lat, val.Lng], { icon: stopIcon }).bindPopup(popup));
                markersBounds[val.RouteId].push([val.Lat, val.Lng]);
            }
        });
        // Add marker groups for all the routes (and overall library)
        $.each(SomersetMobiles.data, function (key, val) {
            // Add the library marker group
            if (!markerGroups[val.Library]) {
                markerGroups[val.Library] = L.featureGroup($.map(markersArrays, function (v, k) {
                    if (k.indexOf(val.Library) != -1) return v;
                }));
            }
            // Add the route marker group
            if (!markerGroups[val.RouteId]) {
                markerGroups[val.RouteId] = L.featureGroup($.map(markersArrays, function (v, k) {
                    if (k == val.RouteId) return v;
                }));
                if (val.Library == 'Taunton') $('#ulTauntonFilter').append('
' + val.Library + ' ' + val.Route + '
');
                if (val.Library == 'Wells') $('#ulWellsFilter').append('
' + val.Library + ' ' + val.Route + '
');
            }
        });
        // Initial setup - Add Taunton and Wells and the overall bounds.
        map.addLayer(markerGroups['Taunton']);
        map.addLayer(markerGroups['Wells']);
        map.fitBounds($.map(markersBounds, function (val, key) {
            return val;
        }));
        var currentFilter = 'All';

        // Set the stop counts
        $('#spTauntonStopCount').text($.map(markersArrays, function (v, k) { if (k.indexOf('Taunton') != -1) return v; }).length);
        $('#spWellsStopCount').text($.map(markersArrays, function (v, k) { if (k.indexOf('Wells') != -1) return v; }).length);
        $('#spStopCount').text($.map(markersArrays, function (v, k) { return v; }).length);

        // Set up the option to show either set of library stops
        filterLibrariesMap = function (filter) {
            if (currentFilter == 'All' && filter == 'Taunton') {
                map.removeLayer(markerGroups['Wells']);
                map.fitBounds($.map(markersBounds, function (val, key) {
                    if (key.indexOf('Taunton') != -1) return val;
                }));
            }
            if (currentFilter == 'All' && filter == 'Wells') {
                map.removeLayer(markerGroups['Taunton']);
                map.fitBounds($.map(markersBounds, function (val, key) {
                    if (key.indexOf('Wells') != -1) return val;
                }));
            }
            if (currentFilter == 'Wells' && filter == 'Taunton') {
                map.removeLayer(markerGroups['Wells']);
                map.addLayer(markerGroups['Taunton']);
                map.fitBounds($.map(markersBounds, function (val, key) {
                    if (key.indexOf('Taunton') != -1) return val;
                }));
            }
            if (currentFilter == 'Taunton' && filter == 'Wells') {
                map.removeLayer(markerGroups['Taunton']);
                map.addLayer(markerGroups['Wells']);
                map.fitBounds($.map(markersBounds, function (val, key) {
                    if (key.indexOf('Wells') != -1) return val;
                }));
            }
            if (currentFilter == 'Wells' && filter == 'All') {
                map.addLayer(markerGroups['Taunton']);
                map.fitBounds($.map(markersBounds, function (val, key) {
                    return val;
                }));
            }
            if (currentFilter == 'Taunton' && filter == 'All') {
                map.addLayer(markerGroups['Wells']);
                map.fitBounds($.map(markersBounds, function (val, key) {
                    return val;
                }));
            }
            currentFilter = filter;
            return false;
        };

        // Set up DataTable
        var table = $('#tblFullTimetable').dataTable(
                {
                    processing: true,
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'print',
                            text: 'Print',
                            className: 'btn-sm'
                        },
                        {
                            extend: 'excelHtml5',
                            text: 'Export Excel',
                            className: 'btn-sm'
                        }
                    ],
                    deferRender: true,
                    data: SomersetMobiles.getDataTable(),
                    // We're expecting Mobile,Route,Day,Town,Location,Postcode,Due,Duration
                    columns: [
                        { title: "Library" },
                        { title: "RouteID", visible: false },
                        { title: "Route" },
                        { title: "Day" },
                        { title: "Town" },
                        { title: "Location" },
                        { title: "Postcode" },
                        { title: "Due" },
                        { title: "DueSystem", visible: false },
                        { title: "Duration" }
                    ],
                    order: [[8, 'asc']],
                    drawCallback: function (settings) {
                        var api = this.api();
                        var rows = api.rows({ page: 'current' }).nodes();
                        var last = null;
                        api.column(7, { page: 'current' }).data().each(function (group, i) {
                            if (group != '' && last !== group) {
                                $(rows).eq(i).before(
                                    '
Due ' + group + '
'
                                );
                                last = group;
                            }
                        });
                    }
                });
        // Set an interval to refresh all the page data (that we want to refresh).
        setInterval(function () {
            setCurrentPositions();
            // table.fnDraw();
        }, 5000);

    });
});<commit_msg>Map filters working<commit_after>/////////////////////////////////////////////////
// Map
// Initialise the map, set center, zoom, etc.
/////////////////////////////////////////////////
var map = L.map('map').setView([51.505, -0.09], 13);
var filterLibrariesMap = function () { };

L.tileLayer('http://{s}.tiles.mapbox.com/v3/librarieshacked.jefmk67b/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

//////////////////////////////////////////////////////
// Autocomplete address search
// Initial code to set up the autocomplete search box
//////////////////////////////////////////////////////
var placeSearch, autocomplete;

function initAutocomplete() {
    autocomplete = new google.maps.places.Autocomplete((document.getElementById('txtAddressSearch')), { types: ['geocode'] });
    autocomplete.addListener('place_changed', populateNearest);
}

function populateNearest() {
    $('#divNearest').show();
    $('#divNearest').empty();
    $('#divNearestAdditional').empty();
    var place = autocomplete.getPlace();
    var lat = place.geometry.location.lat();
    var lng = place.geometry.location.lng();
    SomersetMobiles.setCurrentDistances(lat, lng);
    var nearest = SomersetMobiles.getNearest();
    var nearestStop = SomersetMobiles.data[nearest];
    $('#divNearest').html('Nearest stop ' + nearestStop.Location + ', ' + nearestStop.Town + '.  Arriving in ' + nearestStop.Due + ' (' + moment(nearestStop.DueSystem).format('DD/MM/YYYY hh:mm') + ')');
}

//////////////////////////////////////////////////
// Following relies on jQuery etc so wait for page to complete
//////////////////////////////////////////////////
$(function () {
    //////////////////////////////////////////////////
    // Load Data
    //
    /////////////////////////////////////////////////
    SomersetMobiles.loadData(function () {

        var setCurrentPositions = function () {
            // Set current positions.
            var tauntonCurrent = SomersetMobiles.getCurrentLocation('Taunton');
            var tauntonNext = SomersetMobiles.getNextLocation('Taunton');
            if (tauntonCurrent != null) {
                $('#spTauntonCurrentPosition').html('Currently at ' + SomersetMobiles.data[tauntonCurrent]['Location'] + ', ' + SomersetMobiles.data[tauntonCurrent]['Town'] + ' for another ' + moment(SomersetMobiles.data[tauntonCurrent]['DepartingSystem']).diff(moment(), 'minutes') + ' minutes');
            } else {
                $('#spTauntonCurrentPosition').html('Arriving at ' + SomersetMobiles.data[tauntonNext]['Location'] + ', ' + SomersetMobiles.data[tauntonNext]['Town'] + ' ' + SomersetMobiles.data[tauntonNext]['Due'] + '');
            }
            var wellsCurrent = SomersetMobiles.getCurrentLocation('Wells');
            var wellsNext = SomersetMobiles.getNextLocation('Wells');
            if (wellsCurrent != null) {
                $('#spWellsCurrentPosition').html('Currently at ' + SomersetMobiles.data[wellsCurrent]['Location'] + ', ' + SomersetMobiles.data[wellsCurrent]['Town'] + ' for another ' + moment(SomersetMobiles.data[wellsCurrent]['DepartingSystem']).diff(moment(), 'minutes') + ' minutes');
            } else {
                $('#spWellsCurrentPosition').html('Arriving at ' + SomersetMobiles.data[wellsNext]['Location'] + ', ' + SomersetMobiles.data[wellsNext]['Town'] + ' ' + SomersetMobiles.data[wellsNext]['Due'] + '');
            }
        };
        setCurrentPositions();
        var markersArrays = {};
        var markerGroups = {};
        var markersBounds = {};
        $.each(SomersetMobiles.data, function (key, val) {
            // Add items to the map.
            if (val.Lat && val.Lat != 'TODO') {
                var popup = L.popup({
                    maxWidth: 160,
                    maxHeight: 140,
                    closeButton: false,
                    className: ''
                }).setContent('
' + val.Location + ', ' + val.Town + '
Date ' + moment(val.DueSystem).format('DD MMM YYYY hh:mm') + '');
                var className = 'taunton';

                // Set up the associative arrays for layers and bounds
                if (!markersArrays[val.RouteId]) markersArrays[val.RouteId] = [];
                if (!markersBounds[val.RouteId]) markersBounds[val.RouteId] = [];

                if (val.Library == 'Taunton') className = 'wells';
                var stopIcon = L.divIcon({ html: '
' + val.Route + '
', className: "marker-cluster marker-cluster-" + className, iconSize: new L.Point(20, 20) });
                markersArrays[val.RouteId].push(L.marker([val.Lat, val.Lng], { icon: stopIcon }).bindPopup(popup));
                markersBounds[val.RouteId].push([val.Lat, val.Lng]);
            }
        });
        // Add marker groups for all the routes (and overall library)
        $.each(SomersetMobiles.data, function (key, val) {
            // Add the library marker group
            if (!markerGroups[val.Library]) {
                markerGroups[val.Library] = L.featureGroup($.map(markersArrays, function (v, k) {
                    if (k.indexOf(val.Library) != -1) return v;
                }));
            }
            // Add the route marker group
            if (!markerGroups[val.RouteId]) {
                markerGroups[val.RouteId] = L.featureGroup($.map(markersArrays, function (v, k) {
                    if (k == val.RouteId) return v;
                }));
                if (val.Library == 'Taunton') $('#ulTauntonFilter').append('
Route ' + val.Route + '
');
                if (val.Library == 'Wells') $('#ulWellsFilter').append('
Route ' + val.Route + '
');
            }
        });
        // Initial setup - Add Taunton and Wells and the overall bounds.
        map.addLayer(markerGroups['Taunton']);
        map.addLayer(markerGroups['Wells']);
        map.fitBounds($.map(markersBounds, function (val, key) {
            return val;
        }));
        var currentFilter = 'All';

        // Set the stop counts
        $('#spTauntonStopCount').text($.map(markersArrays, function (v, k) { if (k.indexOf('Taunton') != -1) return v; }).length);
        $('#spWellsStopCount').text($.map(markersArrays, function (v, k) { if (k.indexOf('Wells') != -1) return v; }).length);
        $('#spStopCount').text($.map(markersArrays, function (v, k) { return v; }).length);

        // Set up the option to show either set of library stops
        filterLibrariesMap = function (filter) {
            this.event.preventDefault();
            if (currentFilter == filter) return false;
            if (currentFilter == 'All') {
                map.removeLayer(markerGroups['Taunton']);
                map.removeLayer(markerGroups['Wells']);
            } else {
                map.removeLayer(markerGroups[currentFilter]);
            }
            if (filter == 'All') {
                map.addLayer(markerGroups['Taunton']);
                map.addLayer(markerGroups['Wells']);
                map.fitBounds($.map(markersBounds, function (val, key) {
                    return val;
                }));
            } else {
                map.addLayer(markerGroups[filter]);
                if (filter == 'Taunton' || filter == 'Wells') {
                    map.fitBounds($.map(markersBounds, function (val, key) {
                        if (key.indexOf(filter) != -1) return val;
                    }));
                } else {
                    map.fitBounds($.map(markersBounds, function (val, key) {
                        if (key == filter) return val;
                    }));
                }
            }
            currentFilter = filter;
            return false;
        };

        // Set up DataTable
        var table = $('#tblFullTimetable').dataTable(
                {
                    processing: true,
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'print',
                            text: 'Print',
                            className: 'btn-sm'
                        },
                        {
                            extend: 'excelHtml5',
                            text: 'Export Excel',
                            className: 'btn-sm'
                        }
                    ],
                    deferRender: true,
                    data: SomersetMobiles.getDataTable(),
                    // We're expecting Mobile,Route,Day,Town,Location,Postcode,Due,Duration
                    columns: [
                        { title: "Library" },
                        { title: "RouteID", visible: false },
                        { title: "Route" },
                        { title: "Day" },
                        { title: "Town" },
                        { title: "Location" },
                        { title: "Postcode" },
                        { title: "Due" },
                        { title: "DueSystem", visible: false },
                        { title: "Duration" }
                    ],
                    order: [[8, 'asc']],
                    drawCallback: function (settings) {
                        var api = this.api();
                        var rows = api.rows({ page: 'current' }).nodes();
                        var last = null;
                        api.column(7, { page: 'current' }).data().each(function (group, i) {
                            if (group != '' && last !== group) {
                                $(rows).eq(i).before(
                                    '
Due ' + group + '
'
                                );
                                last = group;
                            }
                        });
                    }
                });
        // Set an interval to refresh all the page data (that we want to refresh).
        setInterval(function () {
            setCurrentPositions();
            // table.fnDraw();
        }, 5000);

    });
});<|endoftext|>


<commit_before>// Copyright 2017, University of Colorado Boulder

/**
 * Parametric IO Type wrapper that adds support for null values in toStateObject/fromStateObject. This type is to
 * prevent the propagation of null handling, mainly in to/fromStateObject, in each type. This also makes null
 * explicit for phet-io.
 * Sample usage:
 *
 *  this.ageProperty = new Property( null, {
 *    tandem: tandem.createTandem( 'ageProperty' ),
 *    phetioType: PropertyIO( NullableIO( NumberIO ) ) // signifies that the Property can be Number or null
 * } );
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var ObjectIO = require( 'PHET_IO/types/ObjectIO' );

  /**
   * Parametric type constructor function, do not use `new`
   * @param {function} ioType - an IO type (constructor function)
   * @returns {function} - the IO type that supports null
   * @constructor
   */
  function NullableIO( ioType ) {

    // Instantiate the concrete IO type using the specified type parameter
    var NullableIOImpl = function NullableIOImpl( property, phetioID ) {
      ObjectIO.call( this, property, phetioID );
    };

    return phetioInherit( ObjectIO, 'NullableIO', NullableIOImpl, {}, {

        // Signify parameterTypes to phetioInherit
        parameterTypes: [ ioType ],

        // Signify documentation, used in documentation wrappers
        documentation: 'A wrapper to wrap another IOType, adding support for null.',

        /**
         * Converts the instance to a state object for serialization.
         * @param {Object|null} instanceOrNull - of type {ioType|null}
         * @returns {Object|null}
         * @public
         * @static
         */
        toStateObject: function( instanceOrNull ) {
          if ( instanceOrNull === null ) {
            return null;
          }
          else {
            return ioType.toStateObject( instanceOrNull );
          }
        },

        /**
         * Converts a state object to underlying type if it is non-null.
         * @param {Object|null} instanceOrNull
         * @returns {Object|null}
         * @public
         * @static
         */
        fromStateObject: function( instanceOrNull ) {
          if ( instanceOrNull === null ) {
            return null;
          }
          else {
            return ioType.fromStateObject( instanceOrNull );
          }
        }
      }
    );
  }

  phetioNamespace.register( 'NullableIO', NullableIO );
  return NullableIO;
} );<commit_msg>Improved NullableIO docs, see https://github.com/phetsims/phet-io/issues/1274<commit_after>// Copyright 2017, University of Colorado Boulder

/**
 * Parametric IO Type wrapper that adds support for null values in toStateObject/fromStateObject. This type is to
 * prevent the propagation of null handling, mainly in to/fromStateObject, in each type. This also makes null
 * explicit for phet-io.
 * Sample usage:
 *
 *  this.ageProperty = new Property( null, {
 *    tandem: tandem.createTandem( 'ageProperty' ),
 *    phetioType: PropertyIO( NullableIO( NumberIO ) ) // signifies that the Property can be Number or null
 * } );
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var ObjectIO = require( 'PHET_IO/types/ObjectIO' );

  /**
   * Parametric type constructor function, do not use `new`
   * @param {function} ioType - an IO type (constructor function)
   * @returns {function} - the IO type that supports null
   * @constructor
   */
  function NullableIO( ioType ) {

    // Instantiate the concrete IO type using the specified type parameter
    var NullableIOImpl = function NullableIOImpl( property, phetioID ) {
      ObjectIO.call( this, property, phetioID );
    };

    return phetioInherit( ObjectIO, 'NullableIO', NullableIOImpl, {}, {

        // Signify parameterTypes to phetioInherit
        parameterTypes: [ ioType ],

        // Signify documentation, used in documentation wrappers
        documentation: 'A wrapper to wrap another IOType, adding support for null.',

        /**
         * If the argument is null, returns null--otherwise converts the instance to a state object for serialization.
         * @param {Object|null} instanceOrNull - of type {ioType|null}
         * @returns {Object|null}
         * @public
         * @static
         */
        toStateObject: function( instanceOrNull ) {
          if ( instanceOrNull === null ) {
            return null;
          }
          else {
            return ioType.toStateObject( instanceOrNull );
          }
        },

        /**
         * If the argument is null, returns null--otherwise converts a state object to underlying type.
         * @param {Object|null} instanceOrNull
         * @returns {Object|null}
         * @public
         * @static
         */
        fromStateObject: function( instanceOrNull ) {
          if ( instanceOrNull === null ) {
            return null;
          }
          else {
            return ioType.fromStateObject( instanceOrNull );
          }
        }
      }
    );
  }

  phetioNamespace.register( 'NullableIO', NullableIO );
  return NullableIO;
} );<|endoftext|>


<commit_before>'use strict'

const Https = require('https')
const ParseString = require('xml2js').parseString

function run (msg, text) {
	msg.say('Lets play a word association game, tell me a word first.')
		.route('deviantart_response')
}

function DeviantArtResponse (msg) {
	// Make ajax request to deviant art random url
	var text = (msg.body.event && msg.body.event.text) || ''
	var url = 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?'
	console.log(url)
	Https.get(url, function(res) {
		res.setEncoding('utf8');
		let raw_data = '';
		res.on('data', (chunk) => { raw_data += chunk; });
		console.log('Here is raw data')
		// console.log(raw_data)
		res.on('end', () => {
			try {
				// console.log(raw_data)
				ParseString(raw_data, function (err, result) {
					console.log('Parsed raw_data')
					// console.log(result.feed.entry[0].link[href])
					for (var prop in result.feed.entry[0].link)
					{
						console.log(prop)
						if (result.feed.entry[0].link.hasOwnProperty(prop))
						{
							console.log(result.feed.entry[0].link[prop])
						}
					}
				})
				// var parser = new DOMParser();
				// var xml_doc = parser.paserFromString(raw_data, 'text/xml')

				// console.log(xml_doc)

				// const parsed_data = JSON.parse(raw_data);
				// var page_id = Object.keys(parsed_data.query.pages)[0]
				// var title = parsed_data.query.pages[page_id].title
				// var extract = parsed_data.query.pages[page_id].extract
				// msg.say({
				// 	text: 'Tell me what you think of this random Wikipedia article:',
				// 		'attachments': [
				// 		{
				// 			"fallback": '',
				// 			"color": '',
				// 			"pretext": '',
				// 			"title": title,
				// 			"title_link": 'https://en.wikipedia.org/wiki?curid=' + page_id,
				// 			"text": extract.replace(/<(?:.|\n)*?>/gm, ''),
				// 		}]
				// 	})
				// 	.route('wikipedia_response')
			} catch (e) {
				console.error(e.message);
			}
		});
	}).on('error', function(e) {
		console.log('Got error: ' + e.message)
	})
	// Creature-bot returns the wikipedia page url in message
}

module.exports = {
	run: run,
	DeviantArtResponse:  DeviantArtResponse
}
<commit_msg>Console log based on prop array position.<commit_after>'use strict'

const Https = require('https')
const ParseString = require('xml2js').parseString

function run (msg, text) {
	msg.say('Lets play a word association game, tell me a word first.')
		.route('deviantart_response')
}

function DeviantArtResponse (msg) {
	// Make ajax request to deviant art random url
	var text = (msg.body.event && msg.body.event.text) || ''
	var url = 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?'
	console.log(url)
	Https.get(url, function(res) {
		res.setEncoding('utf8');
		let raw_data = '';
		res.on('data', (chunk) => { raw_data += chunk; });
		console.log('Here is raw data')
		// console.log(raw_data)
		res.on('end', () => {
			try {
				// console.log(raw_data)
				ParseString(raw_data, function (err, result) {
					console.log('Parsed raw_data')
					// console.log(result.feed.entry[0].link[href])

					for (var prop in result.feed.entry[0].link)
					{
						console.log(result.feed.entry[0].link[prop])
						// console.log(prop)
						// if (result.feed.entry[0].link.hasOwnProperty(prop))
						// {
						// 	console.log(result.feed.entry[0].link[prop])
						// }
					}
				})
				// var parser = new DOMParser();
				// var xml_doc = parser.paserFromString(raw_data, 'text/xml')

				// console.log(xml_doc)

				// const parsed_data = JSON.parse(raw_data);
				// var page_id = Object.keys(parsed_data.query.pages)[0]
				// var title = parsed_data.query.pages[page_id].title
				// var extract = parsed_data.query.pages[page_id].extract
				// msg.say({
				// 	text: 'Tell me what you think of this random Wikipedia article:',
				// 		'attachments': [
				// 		{
				// 			"fallback": '',
				// 			"color": '',
				// 			"pretext": '',
				// 			"title": title,
				// 			"title_link": 'https://en.wikipedia.org/wiki?curid=' + page_id,
				// 			"text": extract.replace(/<(?:.|\n)*?>/gm, ''),
				// 		}]
				// 	})
				// 	.route('wikipedia_response')
			} catch (e) {
				console.error(e.message);
			}
		});
	}).on('error', function(e) {
		console.log('Got error: ' + e.message)
	})
	// Creature-bot returns the wikipedia page url in message
}

module.exports = {
	run: run,
	DeviantArtResponse:  DeviantArtResponse
}
<|endoftext|>


<commit_before>/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import 'semantic-ui-css/components/dropdown';
import $ from 'jquery';

$.fn.extend({
  autoComplete() {
    this.each((idx, el) => {
      const element = $(el);
      const criteriaName = element.data('criteria-name');
      const choiceName = element.data('choice-name');
      const choiceValue = element.data('choice-value');
      const autocompleteValue = element.find('input.autocomplete').val();
      const loadForEditUrl = element.data('load-edit-url');

      element.dropdown({
        delay: {
          search: 250,
        },
        forceSelection: false,
        apiSettings: {
          dataType: 'JSON',
          cache: false,
          beforeSend(settings) {
            /* eslint-disable-next-line no-param-reassign */
            settings.data[criteriaName] = settings.urlData.query;

            return settings;
          },
          onResponse(response) {
            return {
              success: true,
              results: response.map(item => ({
                name: item[choiceName],
                value: item[choiceValue],
              })),
            };
          },
        },
      });

      if (autocompleteValue.split(',').filter(String).length > 0) {
        const menuElement = element.find('div.menu');

        menuElement.api({
          on: 'now',
          method: 'GET',
          url: loadForEditUrl,
          beforeSend(settings) {
            /* eslint-disable-next-line no-param-reassign */
            settings.data[choiceValue] = autocompleteValue.split(',').filter(String);

            return settings;
          },
          onSuccess(response) {
            response.forEach((item) => {
              menuElement.append((
                $(`<div class="item" data-value="${item[choiceValue]}">${item[choiceName]}</div>`)
              ));
            });

            element.dropdown('refresh');
            element.dropdown('set selected', element.find('input.autocomplete').val().split(',').filter(String));
          },
        });
      }
    });
  },
});
<commit_msg>bug #13734 [JS] add empty value to autocomplete selects (SirDomin)<commit_after>/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import 'semantic-ui-css/components/dropdown';
import $ from 'jquery';

$.fn.extend({
  autoComplete() {
    this.each((idx, el) => {
      const element = $(el);
      const criteriaName = element.data('criteria-name');
      const choiceName = element.data('choice-name');
      const choiceValue = element.data('choice-value');
      const autocompleteValue = element.find('input.autocomplete').val();
      const loadForEditUrl = element.data('load-edit-url');

      element.dropdown({
        delay: {
          search: 250,
        },
        forceSelection: false,
        apiSettings: {
          dataType: 'JSON',
          cache: false,
          beforeSend(settings) {
            /* eslint-disable-next-line no-param-reassign */
            settings.data[criteriaName] = settings.urlData.query;

            return settings;
          },
          onResponse(response) {
            let results = response.map(item => ({
              name: item[choiceName],
              value: item[choiceValue],
            }));

            results.unshift({
              name: ' ',
              value: '',
            });

            return {
              success: true,
              results: results,
            };
          },
        },
      });

      if (autocompleteValue.split(',').filter(String).length > 0) {
        const menuElement = element.find('div.menu');

        menuElement.api({
          on: 'now',
          method: 'GET',
          url: loadForEditUrl,
          beforeSend(settings) {
            /* eslint-disable-next-line no-param-reassign */
            settings.data[choiceValue] = autocompleteValue.split(',').filter(String);

            return settings;
          },
          onSuccess(response) {
            response.forEach((item) => {
              menuElement.append((
                $(`<div class="item" data-value="${item[choiceValue]}">${item[choiceName]}</div>`)
              ));
            });

            element.dropdown('refresh');
            element.dropdown('set selected', element.find('input.autocomplete').val().split(',').filter(String));
          },
        });
      }
    });
  },
});
<|endoftext|>


<commit_before>var config = require('./config/config_server');
var logger = require('./logger');

var moment = require('moment');
var monk = require('monk');
var cookieParser = require('cookie-parser');
var passportio = require('passport.socketio');

var db = monk(config.mongoURL);
var chats = db.get('history');
var socketManager = require('./socketManager');

var io;

module.exports = function(sio, passport, sessionStore) {
  io = sio;
  io.sockets.on('connection', onConnect);
  io.set('authorization', passportio.authorize({
    cookieParser : cookieParser,
    key: config.sessionKey,
    secret: config.sessionSecret,
    store: sessionStore,
    success: authSuccess,
    failure: authFailure
  }));
}

var onConnect = function (socket) {
  socketManager.register(socket);
  socket.emit('message', {
    message: 'Connected to chat. Displaying ' + config.displayRecent + ' most recent messages...',
    timestap: moment()
  });

  io.sockets.emit('active-users', {
    users: socketManager.activeUsers()
  });

  sendRecentHistory(socket);
  initializeListeners(socket);

  socket.on('disconnect', function() {
    socketManager.unregister(socket);
    logger.info('Socket disconnected. ID: ' + socket.id);
    io.sockets.emit('active-users', { users: socketManager.activeUsers() });
  });
}

var initializeListeners = function (socket) {
  socket.on('chat-send', function (data) {
    var targetSockets = [];
    var type = 'chat';
    if (data.recipients == undefined) {
      console.log("recipients is undefined");
      data.recipients = 'all';
      targetSockets = socketManager.getSocketsOfType(type);
    } else if (data.recipients.length == 0) {
      console.log("recipients is empty");
      data.recipients = 'all';
      targetSockets = socketManager.getSocketsOfType(type);
    } else {
      // get sockets for the recipients
      for (var i = 0; i < data.recipients.length; i++) {
        console.log(data.recipients[i]);
        targetSockets = targetSockets.concat(socketManager.getSocketsOfTypeForUser(type, data.recipients[i]));
      }
      // get sockets for the sender
      targetSockets = targetSockets.concat(socketManager.getSocketsOfTypeForUser(type, data.username));
    }
    for (var i = 0; i < targetSockets.length; i++) {
      var socket = targetSockets[i];
      logger.info("emitting message of type `" + type + "` to socket " + socket.id);
      socket.emit('message', data);
    }
        chats.insert(data);
  });

  socket.on('set-type', function(data) {
    socketManager.registerAsType(socket, data.type);
  });
}

var sendRecentHistory = function (socket) {
  chats.find({}, {limit: config.displayRecent, sort: {'timestamp': -1}}, function (err, doc){
    // work backwards to send recent history in chronological order
    for (var i = 1; i <= doc.length; i++) {
      socket.emit('message', doc[doc.length-i]);
    }
  });
}

var authSuccess = function(data, accept) {
  logger.info("Socket initiated by user " + data.user.username);
  accept(null, true);
}

var authFailure = function(data, message, error, accept) {
  if (error) throw new Error(message);
  logger.info("Socket auth failed: " + message);
  accept(null, false);
}
<commit_msg>server messages aren't PMs<commit_after>var config = require('./config/config_server');
var logger = require('./logger');

var moment = require('moment');
var monk = require('monk');
var cookieParser = require('cookie-parser');
var passportio = require('passport.socketio');

var db = monk(config.mongoURL);
var chats = db.get('history');
var socketManager = require('./socketManager');

var io;

module.exports = function(sio, passport, sessionStore) {
  io = sio;
  io.sockets.on('connection', onConnect);
  io.set('authorization', passportio.authorize({
    cookieParser : cookieParser,
    key: config.sessionKey,
    secret: config.sessionSecret,
    store: sessionStore,
    success: authSuccess,
    failure: authFailure
  }));
}

var onConnect = function (socket) {
  socketManager.register(socket);
  socket.emit('message', {
    message: 'Connected to chat. Displaying ' + config.displayRecent + ' most recent messages...',
    timestap: moment(),
    recipients: 'all'
  });

  io.sockets.emit('active-users', {
    users: socketManager.activeUsers()
  });

  sendRecentHistory(socket);
  initializeListeners(socket);

  socket.on('disconnect', function() {
    socketManager.unregister(socket);
    logger.info('Socket disconnected. ID: ' + socket.id);
    io.sockets.emit('active-users', { users: socketManager.activeUsers() });
  });
}

var initializeListeners = function (socket) {
  socket.on('chat-send', function (data) {
    var targetSockets = [];
    var type = 'chat';
    if (data.recipients == undefined) {
      console.log("recipients is undefined");
      data.recipients = 'all';
      targetSockets = socketManager.getSocketsOfType(type);
    } else if (data.recipients.length == 0) {
      console.log("recipients is empty");
      data.recipients = 'all';
      targetSockets = socketManager.getSocketsOfType(type);
    } else {
      // get sockets for the recipients
      for (var i = 0; i < data.recipients.length; i++) {
        console.log(data.recipients[i]);
        targetSockets = targetSockets.concat(socketManager.getSocketsOfTypeForUser(type, data.recipients[i]));
      }
      // get sockets for the sender
      targetSockets = targetSockets.concat(socketManager.getSocketsOfTypeForUser(type, data.username));
    }
    for (var i = 0; i < targetSockets.length; i++) {
      var socket = targetSockets[i];
      logger.info("emitting message of type `" + type + "` to socket " + socket.id);
      socket.emit('message', data);
    }
        chats.insert(data);
  });

  socket.on('set-type', function(data) {
    socketManager.registerAsType(socket, data.type);
  });
}

var sendRecentHistory = function (socket) {
  chats.find({}, {limit: config.displayRecent, sort: {'timestamp': -1}}, function (err, doc){
    // work backwards to send recent history in chronological order
    for (var i = 1; i <= doc.length; i++) {
      socket.emit('message', doc[doc.length-i]);
    }
  });
}

var authSuccess = function(data, accept) {
  logger.info("Socket initiated by user " + data.user.username);
  accept(null, true);
}

var authFailure = function(data, message, error, accept) {
  if (error) throw new Error(message);
  logger.info("Socket auth failed: " + message);
  accept(null, false);
}
<|endoftext|>