<commit_before>var env = process.env.NODE_ENV || 'development';

var defaultPort = 5000;

var configuration = {
  development: {
    port: defaultPort,
    cartoDB_USER: "",
    cartoDB_API_KEY: "",
    callbackURL: 'http://localhost:5000/callback',
    default_table: "jp",
    default_screen_name: "anonymous",
    default_profile_image_url: "http://japan.javierarce.com/img/avatar.png"
  },
  production: {
    port: defaultPort,
    cartoDB_USER: "",
    cartoDB_API_KEY: "",
    callbackURL: 'http://localhost:5000/callback',
    default_table: "jp",
    default_screen_name: "anonymous",
    default_profile_image_url: "http://japan.javierarce.com/img/avatar.png"
  }
};

var Config = configuration[env];
module.exports.Config = Config;
<commit_msg>Adds session secret<commit_after>var env = process.env.NODE_ENV || 'development';

var defaultPort = 5000;

var configuration = {
  development: {
    port: defaultPort,
    session_secret: 'my_little_dirty_secret',
    cartoDB_USER: "",
    cartoDB_API_KEY: "",
    callbackURL: 'http://localhost:5000/callback',
    default_table: "jp",
    default_screen_name: "anonymous",
    default_profile_image_url: "http://japan.javierarce.com/img/avatar.png"
  },
  production: {
    port: defaultPort,
    session_secret: 'my_little_dirty_secret',
    cartoDB_USER: "",
    cartoDB_API_KEY: "",
    callbackURL: 'http://localhost:5000/callback',
    default_table: "jp",
    default_screen_name: "anonymous",
    default_profile_image_url: "http://japan.javierarce.com/img/avatar.png"
  }
};

var Config = configuration[env];
module.exports.Config = Config;
<|endoftext|>


<commit_before>//Import dependencies
var assert = require("assert");
var keue = require("../index.js");

describe("keue", function () {
    it("should execute all provided tasks", function (done) {
        var executed1 = false;
        var executed2 = false;
        var k = keue();
        k.addTask("task1", function (next) {
            executed1 = true;
            return next(null);
        });
        k.addTask("task2", function (next) {
            executed2 = true;
            setTimeout(function () {
                return next();
            }, 100);
        });
        k.run("task1", "task2");
        k.on("finish", function () {
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            done();
        });
    });

    it("should stop the queue when a task emit an error", function (done) {
        var executed1 = false, executed2 = false, executed3 = false;
        var k = keue();
        k.addTask("task1", function (next) {
            executed1 = true;
            return next();
        });

        k.addTask("task2", function (next) {
            executed2 = true;
            return next(new Error("Aborting task"));
        });

        k.addTask("task3", function (next) {
            executed3 = true;
            return done(new Error("ERROR"));
        });
        k.on("finish", function () {
            return done(new Error("ERROR"));
        });
        k.on("error", function (error) {
            assert.notEqual(error, null);
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            assert.equal(executed3, false);
            return done();
        });
        k.run("task1", "task2", "task3");
    });

    it("should prevent executing a task twice", function (done) {
        var executed1 = false, executed2 = false;
        var k = new keue();
        k.addTask("task1", function (next) {
            if (executed1 === true) {
                return done(new Error("Running a finished task"));
            }
            executed1 = true;
            return next();
        });
        k.addTask("task2", function (next) {
            if (executed2 === true) {
                return done(new Error("Running a finished task"));
            }
            executed2 = true;
            return next();
        });
        k.on("error", function (error) {
            return done(error);
        });
        k.on("finish", function () {
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            return done();
        });
        k.run("task1", "task2", "task1")
    });

    it("should call all defined tasks in order", function (done) {
        var executed1 = false, executed2 = false, executed3 = false;
        var order = [];
        var k = keue();
        k.addTask("task1", function (next) {
            executed1 = true;
            return next();
        });

        k.addTask("task2", function (next) {
            executed2 = true;
            return next();
        });

        k.addTask("task3", function (next) {
            executed3 = true;
            return next();
        });
        k.on("task:start", function (name) {
            order.push(name.replace("task", ""));
        });
        k.on("finish", function () {
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            assert.equal(executed3, true);
            assert.equal(order[0], "1");
            assert.equal(order[1], "2");
            assert.equal(order[2], "3");
            return done();
        });
        k.on("error", function () {
            return done(new Error("ERROR"))
        });
        k.run();
    });

    it("should execute all task dependencies before running the wanted task", function (done) {
        let executed1 = false, executed2 = false, executed3 = false, executed4 = false;
        let order = [];
        let k = new keue();
        k.addTask("task1", function(next){
            executed1 = true;
            return next();
        });
        k.addTask("task2", "task1", function(next){
            executed2 = true;
            return next();
        });
        k.addTask("task3", function(next){
            executed3 = true;
            return next();
        });
        k.addTask("task4", ["task3", "task2", "task1"], function(next){
            executed4 = true;
            return next();
        });
        k.on("task:start", function (name) {
            order.push(name.replace("task", ""));
        });
        k.on("finish", function(){
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            assert.equal(executed3, true);
            assert.equal(executed4, true);
            assert.equal(order[0], "3");
            assert.equal(order[1], "1");
            assert.equal(order[2], "2");
            assert.equal(order[3], "4");
            return done();
        });
        k.on("error", function () {
            return done(new Error("ERROR"))
        });
        k.run("task4");
    });
});<commit_msg>Test if the module emits an error if recursive tasks are found<commit_after>//Import dependencies
var assert = require("assert");
var keue = require("../index.js");

describe("keue", function () {
    it("should execute all provided tasks", function (done) {
        var executed1 = false;
        var executed2 = false;
        var k = keue();
        k.addTask("task1", function (next) {
            executed1 = true;
            return next(null);
        });
        k.addTask("task2", function (next) {
            executed2 = true;
            setTimeout(function () {
                return next();
            }, 100);
        });
        k.run("task1", "task2");
        k.on("finish", function () {
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            done();
        });
    });

    it("should stop the queue when a task emit an error", function (done) {
        var executed1 = false, executed2 = false, executed3 = false;
        var k = keue();
        k.addTask("task1", function (next) {
            executed1 = true;
            return next();
        });

        k.addTask("task2", function (next) {
            executed2 = true;
            return next(new Error("Aborting task"));
        });

        k.addTask("task3", function (next) {
            executed3 = true;
            return done(new Error("ERROR"));
        });
        k.on("finish", function () {
            return done(new Error("ERROR"));
        });
        k.on("error", function (error) {
            assert.notEqual(error, null);
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            assert.equal(executed3, false);
            return done();
        });
        k.run("task1", "task2", "task3");
    });

    it("should prevent executing a task twice", function (done) {
        var executed1 = false, executed2 = false;
        var k = new keue();
        k.addTask("task1", function (next) {
            if (executed1 === true) {
                return done(new Error("Running a finished task"));
            }
            executed1 = true;
            return next();
        });
        k.addTask("task2", function (next) {
            if (executed2 === true) {
                return done(new Error("Running a finished task"));
            }
            executed2 = true;
            return next();
        });
        k.on("error", function (error) {
            return done(error);
        });
        k.on("finish", function () {
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            return done();
        });
        k.run("task1", "task2", "task1")
    });

    it("should call all defined tasks in order", function (done) {
        var executed1 = false, executed2 = false, executed3 = false;
        var order = [];
        var k = keue();
        k.addTask("task1", function (next) {
            executed1 = true;
            return next();
        });

        k.addTask("task2", function (next) {
            executed2 = true;
            return next();
        });

        k.addTask("task3", function (next) {
            executed3 = true;
            return next();
        });
        k.on("task:start", function (name) {
            order.push(name.replace("task", ""));
        });
        k.on("finish", function () {
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            assert.equal(executed3, true);
            assert.equal(order[0], "1");
            assert.equal(order[1], "2");
            assert.equal(order[2], "3");
            return done();
        });
        k.on("error", function () {
            return done(new Error("ERROR"))
        });
        k.run();
    });

    it("should execute all task dependencies before running the wanted task", function (done) {
        let executed1 = false, executed2 = false, executed3 = false, executed4 = false;
        let order = [];
        let k = new keue();
        k.addTask("task1", function(next){
            executed1 = true;
            return next();
        });
        k.addTask("task2", "task1", function(next){
            executed2 = true;
            return next();
        });
        k.addTask("task3", function(next){
            executed3 = true;
            return next();
        });
        k.addTask("task4", ["task3", "task2", "task1"], function(next){
            executed4 = true;
            return next();
        });
        k.on("task:start", function (name) {
            order.push(name.replace("task", ""));
        });
        k.on("finish", function(){
            assert.equal(executed1, true);
            assert.equal(executed2, true);
            assert.equal(executed3, true);
            assert.equal(executed4, true);
            assert.equal(order[0], "3");
            assert.equal(order[1], "1");
            assert.equal(order[2], "2");
            assert.equal(order[3], "4");
            return done();
        });
        k.on("error", function () {
            return done(new Error("ERROR"))
        });
        k.run("task4");
    });
    it("should emit an error if recursive tasks are found", function(done){
        let k = new keue();
        k.addTask("task1", "task2", function(){
            return done(new Error("ERROR"));
        });
        k.addTask("task2", "task1", function(){
            return done(new Error("ERROR"));
        });
        try{
            k.run();
        } catch(error) {
            return done();
        }
    });
});<|endoftext|>


<commit_before>/*global module, require*/
var path = require('path'),
    _ = require('underscore'),
    error = require('../error'),
    makeBufferedAccessor = require('../makeBufferedAccessor'),
    nextId = 1;

function Base(config) {
    _.extend(this, config);
    this.id = nextId;
    nextId += 1;
}

Base.prototype = {
    encoding: 'utf8', // Change to 'binary' in subclass for images etc.

    getOriginalSrc: makeBufferedAccessor('originalSrc', function (cb) {
        if (this.originalSrcProxy) {
            this.originalSrcProxy(cb);
        } else {
            cb(new Error("Don't know how to get the original asset src!"));
        }
    }),

    toString: function () {
        return "[" + this.type + "/" + this.id + "]";
    }
};

exports.Base = Base;
<commit_msg>Implemented default assets.Base.getOriginalRelations that yields [].<commit_after>/*global module, require*/
var path = require('path'),
    _ = require('underscore'),
    error = require('../error'),
    makeBufferedAccessor = require('../makeBufferedAccessor'),
    nextId = 1;

function Base(config) {
    _.extend(this, config);
    this.id = nextId;
    nextId += 1;
}

Base.prototype = {
    encoding: 'utf8', // Change to 'binary' in subclass for images etc.

    getOriginalSrc: makeBufferedAccessor('originalSrc', function (cb) {
        if (this.originalSrcProxy) {
            this.originalSrcProxy(cb);
        } else {
            cb(new Error("Don't know how to get the original asset src!"));
        }
    }),

    // Override in subclass if it supports relations
    getOriginalRelations: makeBufferedAccessor('originalRelations', function (cb) {
        process.nextTick(function () {
            cb(null, []);
        });
    }),

    toString: function () {
        return "[" + this.type + "/" + this.id + "]";
    }
};

exports.Base = Base;
<|endoftext|>


<commit_before>export function getMousePosition(e) {
  // https://stackoverflow.com/questions/8389156
  let el = e.target,
    x = 0,
    y = 0;

  while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
    x += el.offsetLeft - el.scrollLeft;
    y += el.offsetTop - el.scrollTop;
    el = el.offsetParent;
  }

  x = e.clientX - x;
  y = e.clientY - y;

  return { x: x, y: y };
}
<commit_msg>swap in a better getMousePosition-- old one did not work when scrolled down<commit_after>// export function getMousePosition(e) {
//   // https://stackoverflow.com/questions/8389156
//   let el = e.target,
//     x = 0,
//     y = 0;
//
//   // fixme -- scroll position seems to not be taken into account
//   while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
//     console.log(el.scrollTop)
//     x += el.offsetLeft - el.scrollLeft;
//     y += el.offsetTop - el.scrollTop;
//     el = el.offsetParent;
//   }
//
//   x = e.clientX - x;
//   y = e.clientY - y;
//
//   return { x: x, y: y };
// }

export function getMousePosition(e) {
  let el = e.target,
    el_left = 0,
    el_top = 0,
    x,
    y;

  while (el.offsetParent) {
    el_left += el.offsetLeft;
    el_top += el.offsetTop;
    el = el.offsetParent;
  }

  x = e.pageX;
  y = e.pageY;

  x -= el_left;
  y -= el_top;

  return { x, y };
}
<|endoftext|>


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

var _ = require('lodash');
var assert = require('assert');
var http = require('http');
var url = require('url');
var serverInit = require('./util/server-init');
var EventSource = require('eventsource');

describe('sse-channel', function() {
    this.timeout(5000);

    var port = process.env.TESTING_PORT || 6775;
    var host = 'http://localhost:' + port;
    var server, channel, es, path = '/sse';

    function initServer(opts) {
        var tmp = serverInit(_.merge({}, { port: port, path: path }, opts || {}));
        server = tmp.server;
        channel = tmp.channel;
    }

    afterEach(function(done) {
        if (es) {
            es.close();
        }

        if (server && server.close) {
            return server.close(done);
        }

        done();
    });

    it('can broadcast simple message', function(done) {
        initServer();

        var text = 'First event!';

        channel.on('connect', function() {
            channel.send(text);
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.data, text);
            done();
        };
    });

    it('represents messages without event name as "message"', function(done) {
        initServer();

        channel.on('connect', function() {
            channel.send('Moo');
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.type, 'message');
            done();
        };
    });

    it('can broadcast messages with ID and type', function(done) {
        initServer();

        var data = 'Reign in Citra';

        channel.on('connect', function() {
            channel.send({ event: 'drink', data: data, id: 1337 });
        });

        es = new EventSource(host + path);
        es.addEventListener('drink', function(e) {
            assert.equal(e.lastEventId, '1337');
            assert.equal(e.type, 'drink');
            assert.equal(e.data, data);
            done();
        }, false);
    });

    it('can tell clients how long they should wait before reconnecting', function(done) {
        initServer();

        channel.on('connect', function() {
            var disconnected;

            // Tell clients to reconnect after approx 750 milliseconds
            var retryTime = 75, threshold = retryTime / 7.5;
            channel.retry(retryTime);

            // Remove the 'connect'-listener (for testing purposes, since we re-apply it below)
            channel.removeAllListeners();

            // Add a new connect listener that we can use to assert with
            channel.on('connect', function() {
                var timeUsed = Date.now() - disconnected;
                assert.ok(
                    timeUsed > (retryTime - threshold) && timeUsed < retryTime + threshold,
                    'Client did not reconnect after ~' + retryTime + 'ms ' +
                    '(reconnected after ' + timeUsed + 'ms)'
                );

                done();
            });

            // Disconnect all clients on the channel
            disconnected = Date.now();
            channel.close();
        });

        es = new EventSource(host + path);
    });

    it('can provide a history of events if client is disconnected', function(done) {
        initServer();

        var id = 1337, msgCount = 0;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        es = new EventSource(host + path, { headers: { 'Last-Event-Id': '1337' } });
        es.onmessage = function(e) {
            if (++msgCount !== 6) { return; }

            // Data should correspond to the last message we sent
            assert.equal(e.data, 'Event #' + id);
            done();
        };
    });

    it('can provide a history of events through "evs_last_event_id"-query param', function(done) {
        initServer();

        var id = 1337, msgCount = 0;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        es = new EventSource(host + path + '?evs_last_event_id=1337');
        es.onmessage = function(e) {
            if (++msgCount !== 6) { return; }
            assert.equal(e.data, 'Event #' + id);
            done();
        };
    });

    it('can provide a history of events through "lastEventId"-query param', function(done) {
        initServer();

        var id = 1337, msgCount = 0;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        es = new EventSource(host + path + '?lastEventId=1337');
        es.onmessage = function(e) {
            if (++msgCount !== 6) { return; }
            assert.equal(e.data, 'Event #' + id);
            done();
        };
    });

    it('does not send history by default', function(done) {
        initServer();

        var id = 1337, msgCount = 0;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        es = new EventSource(host + path);
        es.onopen = function() {
            channel.send('Boom');
        };

        es.onmessage = function(e) {
            if (++msgCount === 1) {
                assert.equal(e.data, 'Boom');
                done();
            }
        };
    });

    it('sends the right slice of the history', function(done) {
        initServer();

        var id = 1337, msgCount = 0, lastMsg;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        var assertMsgCount = _.debounce(function() {
            assert.equal(msgCount, 4);
            assert.equal(lastMsg.data, 'Event #' + id);
            done();
        }, 25);

        es = new EventSource(host + path + '?lastEventId=1339');
        es.onmessage = function(e) {
            msgCount++;
            lastMsg = e;
            assertMsgCount();
        };
    });

    it('can be configured to a specific max history size', function(done) {
        initServer({ historySize: 5 });

        var id = 100, msgCount = 0, lastMsg;
        for (var i = 0; i < 100; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        var assertMsgCount = _.debounce(function() {
            assert.equal(msgCount, 5);
            assert.equal(lastMsg.data, 'Event #' + id);
            done();
        }, 25);

        es = new EventSource(host + path + '?lastEventId=110');
        es.onmessage = function(e) {
            msgCount++;
            lastMsg = e;
            assertMsgCount();
        };
    });

    it('provides a correct number of connections on channel', function(done) {
        initServer();

        var connections = channel.getConnectionCount();
        assert.equal(connections, 0, 'Initial connection count should be 0, got ' + connections);

        es = new EventSource(host + path);
        es.onopen = function() {
            connections = channel.getConnectionCount();
            assert.equal(connections, 1, 'Connection count after opening first connection should be 1, got ' + connections);

            process.nextTick(function() {
                var es2 = new EventSource(host + path);
                es2.onopen = function() {
                    connections = channel.getConnectionCount();
                    assert.equal(connections, 2, 'Connection count after opening second connection should be 2, got ' + connections);
                    es2.close();

                    setTimeout(function() {
                        connections = channel.getConnectionCount();
                        assert.equal(connections, 1, 'Connection count after disconnecting one session should be 1, got ' + connections);
                        done();
                    }, 25);
                };
            });
        };
    });

    it('sends automatic pings', function(done) {
        // We'll want to use some custom logic for the channel here
        var interval = 25;
        initServer({ pingInterval: interval });

        var opts = url.parse(host + path);
        opts.headers = { 'Accept': 'text/event-stream' };

        var req = http.request(opts, function(res) {
            var buf = '';
            res.on('data', function(chunk) {
                buf += chunk.toString();
            });

            setTimeout(function() {
                req.abort();
                assert.ok(
                    buf.match(/\:\n/g).length >= 5,
                    'Expected at least 5 pings within ' + (interval * 7) + 'ms'
                );
                done();
            }, interval * 7);
        });

        req.setNoDelay(true);
        req.end();
    });

    it('sends "preamble" if client requests it', function(done) {
        initServer();

        var opts = url.parse(host + path + '?evs_preamble=1');
        opts.headers = { 'Accept': 'text/event-stream' };

        var req = http.request(opts, function(res) {
            var buf = '';
            res.on('data', function(chunk) {
                buf += chunk.toString();

                if (buf.match(/\-{3}\n/)) {
                    assert.ok(
                        buf.match(/\:\-{2056,}/),
                        'Preamble of 2kb not present in response'
                    );

                    req.abort();
                    done();
                }
            });
        });

        req.setNoDelay(true);
        req.end();
    });

    it('auto-serializes objects/arrays as JSON by default', function(done) {
        initServer();

        channel.on('connect', function() {
            channel.send({ data: ['foo', 'bar'] });
            channel.send({ data: { 'foo': 'bar' } });
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            var data = JSON.parse(e.data);
            if (_.isArray(data)) {
                // Assume first message
                assert.equal(data[0], 'foo');
                assert.equal(data[1], 'bar');
            } else {
                // Assume object, second message
                assert.equal(data.foo, 'bar');
                done();
            }
        };
    });

    it('treats buffers as strings when autoSerialize is turned off', function(done) {
        initServer({ autoSerialize: false });

        var msg = 'Heard about this project called Imbo(.io)?';
        channel.on('connect', function() {
            channel.send({ data: new Buffer(msg) });
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.data, msg);
            done();
        };
    });

    it('treats missing data property as empty string', function(done) {
        initServer({ autoSerialize: false });

        channel.on('connect', function() {
            channel.send({ id: 1337 });
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.data, '');
            done();
        };
    });

    it('handles multi-line strings properly', function(done) {
        initServer();

        var text = [
            'Line 1',
            'Line 2',
            '',
            'Line 4',
            'Line 5\n\n\n',
            'Line ..9?'
        ].join('\n');

        channel.on('connect', function() {
            channel.send(text);
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.data, text);
            done();
        };
    });

    it('does not allow CORS by default', function(done) {
        initServer();

        es = new EventSource(host + path, {
            headers: {
                Origin: 'http://imbo.io'
            }
        });

        es.onerror = function(e) {
            assert.equal(e.status, 403);
            done();
        };
    });

    it('can be configured to allow CORS', function(done) {
        initServer({ cors: {
            origins: ['http://imbo.io']
        }});

        var opts = url.parse(host + path);
        opts.method = 'OPTIONS';
        opts.headers = {
            'Accept': 'text/event-stream',
            'Origin': 'http://imbo.io',
            'Last-Event-Id': '1337',
            'Access-Control-Request-Method': 'GET'
        };

        var req = http.request(opts, function(res) {
            assert.equal(res.headers['access-control-allow-origin'], 'http://imbo.io');
            assert.equal(res.headers['access-control-allow-headers'], 'Last-Event-ID');

            req.abort();
            done();
        });

        req.end();
    });

    it('sends initial retry-timeout if specified in channel config', function(done) {
        initServer({ retryTimeout: 3000 });

        var opts = url.parse(host + path);
        opts.headers = { 'Accept': 'text/event-stream' };

        var req = http.request(opts, function(res) {
            var buf = '';
            res.on('data', function(chunk) {
                buf += chunk.toString();

                if (buf.length >= 17) {
                    assert.ok(buf.indexOf('retry: 3000\n') > -1);
                    req.abort();
                    done();
                }
            });
        });

        req.setNoDelay(true);
        req.end();
    });

    it('single event can contain event name, retry time, id and data', function(done) {
        initServer();

        var opts = url.parse(host + path);
        opts.headers = { 'Accept': 'text/event-stream' };

        var req = http.request(opts, function(res) {
            var buf = '';
            res.on('data', function(chunk) {
                buf += chunk.toString();

                if (buf.indexOf('Citra') > -1) {
                    assert.ok(buf.indexOf('\nevent: drink\n') > -1);
                    assert.ok(buf.indexOf('\nretry: 1800\n') > -1);
                    assert.ok(buf.indexOf('\nid: 1337\n') > -1);
                    assert.ok(buf.indexOf('\ndata: Reign in Citra\n') > -1);
                    req.abort();
                    done();
                }
            });

            channel.send({ retry: 1800, id: 1337, event: 'drink', data: 'Reign in Citra' });
        });

        req.setNoDelay(true);
        req.end();
    });
});<commit_msg>Fixed reconnect test<commit_after>/* global afterEach, describe, it */
'use strict';

var _ = require('lodash');
var assert = require('assert');
var http = require('http');
var url = require('url');
var serverInit = require('./util/server-init');
var EventSource = require('eventsource');

describe('sse-channel', function() {
    this.timeout(5000);

    var port = process.env.TESTING_PORT || 6775;
    var host = 'http://localhost:' + port;
    var server, channel, es, path = '/sse';

    function initServer(opts) {
        var tmp = serverInit(_.merge({}, { port: port, path: path }, opts || {}));
        server = tmp.server;
        channel = tmp.channel;
    }

    afterEach(function(done) {
        if (es) {
            es.close();
        }

        if (server && server.close) {
            return server.close(done);
        }

        done();
    });

    it('can broadcast simple message', function(done) {
        initServer();

        var text = 'First event!';

        channel.on('connect', function() {
            channel.send(text);
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.data, text);
            done();
        };
    });

    it('represents messages without event name as "message"', function(done) {
        initServer();

        channel.on('connect', function() {
            channel.send('Moo');
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.type, 'message');
            done();
        };
    });

    it('can broadcast messages with ID and type', function(done) {
        initServer();

        var data = 'Reign in Citra';

        channel.on('connect', function() {
            channel.send({ event: 'drink', data: data, id: 1337 });
        });

        es = new EventSource(host + path);
        es.addEventListener('drink', function(e) {
            assert.equal(e.lastEventId, '1337');
            assert.equal(e.type, 'drink');
            assert.equal(e.data, data);
            done();
        }, false);
    });

    it('can tell clients how long they should wait before reconnecting', function(done) {
        initServer({ retryTimeout: 3000 });

        channel.on('connect', function() {
            var disconnected;

            // Tell clients to reconnect after approx 75 milliseconds
            var retryTime = 75;
            channel.retry(retryTime);

            // Remove the 'connect'-listener (for testing purposes, since we re-apply it below)
            channel.removeAllListeners();

            // Add a new connect listener that we can use to assert with
            channel.on('connect', function() {
                var timeUsed = Date.now() - disconnected;
                assert.ok(
                    timeUsed > (retryTime * 0.25) && timeUsed < (retryTime * 1.75),
                    'Client did not reconnect after ~' + retryTime + 'ms ' +
                    '(reconnected after ' + timeUsed + 'ms)'
                );

                done();
            });

            // Disconnect all clients on the channel
            disconnected = Date.now();
            channel.close();
        });

        es = new EventSource(host + path);
    });

    it('can provide a history of events if client is disconnected', function(done) {
        initServer();

        var id = 1337, msgCount = 0;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        es = new EventSource(host + path, { headers: { 'Last-Event-Id': '1337' } });
        es.onmessage = function(e) {
            if (++msgCount !== 6) { return; }

            // Data should correspond to the last message we sent
            assert.equal(e.data, 'Event #' + id);
            done();
        };
    });

    it('can provide a history of events through "evs_last_event_id"-query param', function(done) {
        initServer();

        var id = 1337, msgCount = 0;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        es = new EventSource(host + path + '?evs_last_event_id=1337');
        es.onmessage = function(e) {
            if (++msgCount !== 6) { return; }
            assert.equal(e.data, 'Event #' + id);
            done();
        };
    });

    it('can provide a history of events through "lastEventId"-query param', function(done) {
        initServer();

        var id = 1337, msgCount = 0;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        es = new EventSource(host + path + '?lastEventId=1337');
        es.onmessage = function(e) {
            if (++msgCount !== 6) { return; }
            assert.equal(e.data, 'Event #' + id);
            done();
        };
    });

    it('does not send history by default', function(done) {
        initServer();

        var id = 1337, msgCount = 0;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        es = new EventSource(host + path);
        es.onopen = function() {
            channel.send('Boom');
        };

        es.onmessage = function(e) {
            if (++msgCount === 1) {
                assert.equal(e.data, 'Boom');
                done();
            }
        };
    });

    it('sends the right slice of the history', function(done) {
        initServer();

        var id = 1337, msgCount = 0, lastMsg;
        for (var i = 0; i < 6; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        var assertMsgCount = _.debounce(function() {
            assert.equal(msgCount, 4);
            assert.equal(lastMsg.data, 'Event #' + id);
            done();
        }, 25);

        es = new EventSource(host + path + '?lastEventId=1339');
        es.onmessage = function(e) {
            msgCount++;
            lastMsg = e;
            assertMsgCount();
        };
    });

    it('can be configured to a specific max history size', function(done) {
        initServer({ historySize: 5 });

        var id = 100, msgCount = 0, lastMsg;
        for (var i = 0; i < 100; i++) {
            channel.send({ id: ++id, data: 'Event #' + id });
        }

        var assertMsgCount = _.debounce(function() {
            assert.equal(msgCount, 5);
            assert.equal(lastMsg.data, 'Event #' + id);
            done();
        }, 25);

        es = new EventSource(host + path + '?lastEventId=110');
        es.onmessage = function(e) {
            msgCount++;
            lastMsg = e;
            assertMsgCount();
        };
    });

    it('provides a correct number of connections on channel', function(done) {
        initServer();

        var connections = channel.getConnectionCount();
        assert.equal(connections, 0, 'Initial connection count should be 0, got ' + connections);

        es = new EventSource(host + path);
        es.onopen = function() {
            connections = channel.getConnectionCount();
            assert.equal(connections, 1, 'Connection count after opening first connection should be 1, got ' + connections);

            process.nextTick(function() {
                var es2 = new EventSource(host + path);
                es2.onopen = function() {
                    connections = channel.getConnectionCount();
                    assert.equal(connections, 2, 'Connection count after opening second connection should be 2, got ' + connections);
                    es2.close();

                    setTimeout(function() {
                        connections = channel.getConnectionCount();
                        assert.equal(connections, 1, 'Connection count after disconnecting one session should be 1, got ' + connections);
                        done();
                    }, 25);
                };
            });
        };
    });

    it('sends automatic pings', function(done) {
        // We'll want to use some custom logic for the channel here
        var interval = 25;
        initServer({ pingInterval: interval });

        var opts = url.parse(host + path);
        opts.headers = { 'Accept': 'text/event-stream' };

        var req = http.request(opts, function(res) {
            var buf = '';
            res.on('data', function(chunk) {
                buf += chunk.toString();
            });

            setTimeout(function() {
                req.abort();
                assert.ok(
                    buf.match(/\:\n/g).length >= 5,
                    'Expected at least 5 pings within ' + (interval * 7) + 'ms'
                );
                done();
            }, interval * 7);
        });

        req.setNoDelay(true);
        req.end();
    });

    it('sends "preamble" if client requests it', function(done) {
        initServer();

        var opts = url.parse(host + path + '?evs_preamble=1');
        opts.headers = { 'Accept': 'text/event-stream' };

        var req = http.request(opts, function(res) {
            var buf = '';
            res.on('data', function(chunk) {
                buf += chunk.toString();

                if (buf.match(/\-{3}\n/)) {
                    assert.ok(
                        buf.match(/\:\-{2056,}/),
                        'Preamble of 2kb not present in response'
                    );

                    req.abort();
                    done();
                }
            });
        });

        req.setNoDelay(true);
        req.end();
    });

    it('auto-serializes objects/arrays as JSON by default', function(done) {
        initServer();

        channel.on('connect', function() {
            channel.send({ data: ['foo', 'bar'] });
            channel.send({ data: { 'foo': 'bar' } });
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            var data = JSON.parse(e.data);
            if (_.isArray(data)) {
                // Assume first message
                assert.equal(data[0], 'foo');
                assert.equal(data[1], 'bar');
            } else {
                // Assume object, second message
                assert.equal(data.foo, 'bar');
                done();
            }
        };
    });

    it('treats buffers as strings when autoSerialize is turned off', function(done) {
        initServer({ autoSerialize: false });

        var msg = 'Heard about this project called Imbo(.io)?';
        channel.on('connect', function() {
            channel.send({ data: new Buffer(msg) });
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.data, msg);
            done();
        };
    });

    it('treats missing data property as empty string', function(done) {
        initServer({ autoSerialize: false });

        channel.on('connect', function() {
            channel.send({ id: 1337 });
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.data, '');
            done();
        };
    });

    it('handles multi-line strings properly', function(done) {
        initServer();

        var text = [
            'Line 1',
            'Line 2',
            '',
            'Line 4',
            'Line 5\n\n\n',
            'Line ..9?'
        ].join('\n');

        channel.on('connect', function() {
            channel.send(text);
        });

        es = new EventSource(host + path);
        es.onmessage = function(e) {
            assert.equal(e.data, text);
            done();
        };
    });

    it('does not allow CORS by default', function(done) {
        initServer();

        es = new EventSource(host + path, {
            headers: {
                Origin: 'http://imbo.io'
            }
        });

        es.onerror = function(e) {
            assert.equal(e.status, 403);
            done();
        };
    });

    it('can be configured to allow CORS', function(done) {
        initServer({ cors: {
            origins: ['http://imbo.io']
        }});

        var opts = url.parse(host + path);
        opts.method = 'OPTIONS';
        opts.headers = {
            'Accept': 'text/event-stream',
            'Origin': 'http://imbo.io',
            'Last-Event-Id': '1337',
            'Access-Control-Request-Method': 'GET'
        };

        var req = http.request(opts, function(res) {
            assert.equal(res.headers['access-control-allow-origin'], 'http://imbo.io');
            assert.equal(res.headers['access-control-allow-headers'], 'Last-Event-ID');

            req.abort();
            done();
        });

        req.end();
    });

    it('sends initial retry-timeout if specified in channel config', function(done) {
        initServer({ retryTimeout: 3000 });

        var opts = url.parse(host + path);
        opts.headers = { 'Accept': 'text/event-stream' };

        var req = http.request(opts, function(res) {
            var buf = '';
            res.on('data', function(chunk) {
                buf += chunk.toString();

                if (buf.length >= 17) {
                    assert.ok(buf.indexOf('retry: 3000\n') > -1);
                    req.abort();
                    done();
                }
            });
        });

        req.setNoDelay(true);
        req.end();
    });

    it('single event can contain event name, retry time, id and data', function(done) {
        initServer();

        var opts = url.parse(host + path);
        opts.headers = { 'Accept': 'text/event-stream' };

        var req = http.request(opts, function(res) {
            var buf = '';
            res.on('data', function(chunk) {
                buf += chunk.toString();

                if (buf.indexOf('Citra') > -1) {
                    assert.ok(buf.indexOf('\nevent: drink\n') > -1);
                    assert.ok(buf.indexOf('\nretry: 1800\n') > -1);
                    assert.ok(buf.indexOf('\nid: 1337\n') > -1);
                    assert.ok(buf.indexOf('\ndata: Reign in Citra\n') > -1);
                    req.abort();
                    done();
                }
            });

            channel.send({ retry: 1800, id: 1337, event: 'drink', data: 'Reign in Citra' });
        });

        req.setNoDelay(true);
        req.end();
    });
});<|endoftext|>


<commit_before>/**
 * `modules/analytics-4` data store: accounts tests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { STORE_NAME } from './constants';
import { createTestRegistry, unsubscribeFromAll, untilResolved } from 'tests/js/utils';
import * as fixtures from './__fixtures__';

describe( 'modules/analytics-4 accounts', () => {
	let registry;

	const accountSummariesEndpoint = /^\/google-site-kit\/v1\/modules\/analytics-4\/data\/account-summaries/;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
		// Receive empty settings to prevent unexpected fetch by resolver.
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'selectors', () => {
		describe( 'getAccountSummaries', () => {
			it( 'should use a resolver to make a network request', async () => {
				fetchMock.get( accountSummariesEndpoint, {
					body: fixtures.accountSummaries,
					status: 200,
				} );

				const initialProperties = registry.select( STORE_NAME ).getAccountSummaries();
				expect( initialProperties ).toBeUndefined();

				await untilResolved( registry, STORE_NAME ).getAccountSummaries();
				expect( fetchMock ).toHaveFetched( accountSummariesEndpoint );

				const properties = registry.select( STORE_NAME ).getAccountSummaries();
				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( properties ).toEqual( fixtures.accountSummaries );
				expect( properties ).toHaveLength( fixtures.accountSummaries.length );
			} );

			it( 'should not make a network request if properties for this account are already present', async () => {
				registry.dispatch( STORE_NAME ).receiveGetAccountSummaries( fixtures.accountSummaries );

				const properties = registry.select( STORE_NAME ).getAccountSummaries();
				await untilResolved( registry, STORE_NAME ).getAccountSummaries();

				expect( fetchMock ).not.toHaveFetched( accountSummariesEndpoint );
				expect( properties ).toEqual( fixtures.accountSummaries );
				expect( properties ).toHaveLength( fixtures.accountSummaries.length );
			} );

			it( 'should dispatch an error if the request fails', async () => {
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};

				fetchMock.getOnce( accountSummariesEndpoint, {
					body: response,
					status: 500,
				} );

				registry.select( STORE_NAME ).getAccountSummaries();
				await untilResolved( registry, STORE_NAME ).getAccountSummaries();
				expect( fetchMock ).toHaveFetchedTimes( 1 );

				const properties = registry.select( STORE_NAME ).getAccountSummaries();
				expect( properties ).toBeUndefined();
				expect( console ).toHaveErrored();
			} );
		} );
	} );
} );
<commit_msg>Rename wrong variable names in the accounts.test.js file.<commit_after>/**
 * `modules/analytics-4` data store: accounts tests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { STORE_NAME } from './constants';
import { createTestRegistry, unsubscribeFromAll, untilResolved } from 'tests/js/utils';
import * as fixtures from './__fixtures__';

describe( 'modules/analytics-4 accounts', () => {
	let registry;

	const accountSummariesEndpoint = /^\/google-site-kit\/v1\/modules\/analytics-4\/data\/account-summaries/;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
		// Receive empty settings to prevent unexpected fetch by resolver.
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'selectors', () => {
		describe( 'getAccountSummaries', () => {
			it( 'should use a resolver to make a network request', async () => {
				fetchMock.get( accountSummariesEndpoint, {
					body: fixtures.accountSummaries,
					status: 200,
				} );

				const initialAccountSummaries = registry.select( STORE_NAME ).getAccountSummaries();
				expect( initialAccountSummaries ).toBeUndefined();

				await untilResolved( registry, STORE_NAME ).getAccountSummaries();
				expect( fetchMock ).toHaveFetched( accountSummariesEndpoint );

				const accountSummaries = registry.select( STORE_NAME ).getAccountSummaries();
				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( accountSummaries ).toEqual( fixtures.accountSummaries );
				expect( accountSummaries ).toHaveLength( fixtures.accountSummaries.length );
			} );

			it( 'should not make a network request if properties for this account are already present', async () => {
				registry.dispatch( STORE_NAME ).receiveGetAccountSummaries( fixtures.accountSummaries );

				const accountSummaries = registry.select( STORE_NAME ).getAccountSummaries();
				await untilResolved( registry, STORE_NAME ).getAccountSummaries();

				expect( fetchMock ).not.toHaveFetched( accountSummariesEndpoint );
				expect( accountSummaries ).toEqual( fixtures.accountSummaries );
				expect( accountSummaries ).toHaveLength( fixtures.accountSummaries.length );
			} );

			it( 'should dispatch an error if the request fails', async () => {
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};

				fetchMock.getOnce( accountSummariesEndpoint, {
					body: response,
					status: 500,
				} );

				registry.select( STORE_NAME ).getAccountSummaries();
				await untilResolved( registry, STORE_NAME ).getAccountSummaries();
				expect( fetchMock ).toHaveFetchedTimes( 1 );

				const accountSummaries = registry.select( STORE_NAME ).getAccountSummaries();
				expect( accountSummaries ).toBeUndefined();
				expect( console ).toHaveErrored();
			} );
		} );
	} );
} );
<|endoftext|>


<commit_before>/** @jsx React.DOM */

var React = require('react');
var Table = require('reactlet-table');

var HtmlInput = require('reactlet-html-input');
var HtmlSelect = require('reactlet-html-select');
var HtmlForm = require('reactlet-html-form');

var app = app ||  window.app || {};

$().ready(function() {
    setup();
    testForm1();
});

function setup() {
    console.log('in common view page - module:', app.moduleName, ' id:', app.itemId);
    /*
    getModuleInfo(app.moduleName, function(moduleInfo) {
        getModuleItemData(app.moduleName, app.itemId, function(moduleItems) {
            //updateTableDisplay(moduleInfo, moduleItems);
        });
    });
    */
}

function getModuleInfo(moduleName, callback) {
    var moduleInfoUrl = '/data/modules/' + moduleName + '/info';
    $.get(moduleInfoUrl, function(data) {
        callback && callback( data.info);
    });
}

function getModuleItemData(moduleName, itemId, callback) {
    var moduleItemDataUrl = '/data/modules/' + moduleName + '/' + itemId;
    $.get(moduleItemDataUrl, function(data) {
        callback && callback(data.docs);
    });
}

function getColModel(moduleInfo) {
    var colModel = {
        name: { name:'name', text:'Name', width:'40%' },
        value: { name:'value', text:'Value', width:'60%' }
    };
    return colModel;
}

/*
function updateTableDisplay(moduleInfo, moduleItems) {
    var newItems = [];
    for ( var prop in moduleItems[0] ) {
        if ( prop != '_class' &&
             prop != 'create_by'  && prop != 'create_date' &&
             prop != 'edit_by'   && prop != 'edit_date' ) {
            var newObj = {};
            newObj.name = prop;
            newObj.value = moduleItems[0][prop];
            newItems.push(newObj);
        }
    }
    var colModel = getColModel(moduleInfo);
    doTableDisplay(colModel, newItems);
}

function doTableDisplay(colModel, items) {
    app.table1Data = {
        boxClass: 'table-container-bordered',
        colModel: colModel,
        dataItems: items,
        //paging: { size: 10, page: 1 }
    };
    app.table1 = React.render(
        React.createElement(Table, { data:app.table1Data }),
        document.getElementById('table1')
    );
    app.table1.on('table-row-click', function(event) {
        var id = event.id;
        app.activeRowId = app.table1.state.activeItemId;
    });
}

function viewItem(itemId) {
    if (!itemId) {
        return;
    }
    var itemViewUrl = '/module/' + app.moduleName + '/' + itemId + '/view';
    console.log('view item:', itemId, itemViewUrl);
}
*/

function testForm1() {
    console.log('in testForm1');
    app.component1Data = {
        label:'Item Price'
    };
    app.component1 = React.render(
        React.createElement('HtmlInput', { data:app.component1Data }),
        document.getElementById('form1')
    );
}

function testForm2() {
    console.log('in testForm2');

    var testFormFields = [
        {
            type: "HtmlInput",
            data: {
                label: "Student",
                "placeholder": "Student Name"
            }
        },
        {
            type: "HtmlSelect",
            data: {
                label: "Grade",
                value: "grade1",
                options: [
                    { id:"blank", display:"" },
                    { id:"grade1", display:"grade 1" },
                    { id:"grade2", display:"grade 2" },
                    { id:"grade3", display:"grade 3" }
                ]
            }
        }
    ];

    var component2Data = { fields:testFormFields };
    var component2 = React.render(
        <HtmlForm data={ component2Data } />,
        document.getElementById('form2')
    );
}<commit_msg>reactlet table test added in edit page<commit_after>/** @jsx React.DOM */

var React = require('react');
var Table = require('reactlet-table');

var HtmlInput = require('reactlet-html-input');
var HtmlSelect = require('reactlet-html-select');
var HtmlForm = require('reactlet-html-form');

var app = app ||  window.app || {};

$().ready(function() {
    setup();
    testForm3();
});

function setup() {
    console.log('in common view page - module:', app.moduleName, ' id:', app.itemId);
    /*
    getModuleInfo(app.moduleName, function(moduleInfo) {
        getModuleItemData(app.moduleName, app.itemId, function(moduleItems) {
            //updateTableDisplay(moduleInfo, moduleItems);
        });
    });
    */
}

function getModuleInfo(moduleName, callback) {
    var moduleInfoUrl = '/data/modules/' + moduleName + '/info';
    $.get(moduleInfoUrl, function(data) {
        callback && callback( data.info);
    });
}

function getModuleItemData(moduleName, itemId, callback) {
    var moduleItemDataUrl = '/data/modules/' + moduleName + '/' + itemId;
    $.get(moduleItemDataUrl, function(data) {
        callback && callback(data.docs);
    });
}

function getColModel(moduleInfo) {
    var colModel = {
        name: { name:'name', text:'Name', width:'40%' },
        value: { name:'value', text:'Value', width:'60%' }
    };
    return colModel;
}

/*
function updateTableDisplay(moduleInfo, moduleItems) {
    var newItems = [];
    for ( var prop in moduleItems[0] ) {
        if ( prop != '_class' &&
             prop != 'create_by'  && prop != 'create_date' &&
             prop != 'edit_by'   && prop != 'edit_date' ) {
            var newObj = {};
            newObj.name = prop;
            newObj.value = moduleItems[0][prop];
            newItems.push(newObj);
        }
    }
    var colModel = getColModel(moduleInfo);
    doTableDisplay(colModel, newItems);
}

function doTableDisplay(colModel, items) {
    app.table1Data = {
        boxClass: 'table-container-bordered',
        colModel: colModel,
        dataItems: items,
        //paging: { size: 10, page: 1 }
    };
    app.table1 = React.render(
        React.createElement(Table, { data:app.table1Data }),
        document.getElementById('table1')
    );
    app.table1.on('table-row-click', function(event) {
        var id = event.id;
        app.activeRowId = app.table1.state.activeItemId;
    });
}

function viewItem(itemId) {
    if (!itemId) {
        return;
    }
    var itemViewUrl = '/module/' + app.moduleName + '/' + itemId + '/view';
    console.log('view item:', itemId, itemViewUrl);
}
*/

function testForm1() {
    console.log('in testForm1');
    app.component1Data = {
        label:'Item Price'
    };
    app.component1 = React.render(
        React.createElement('HtmlInput', { data:app.component1Data }),
        document.getElementById('form1')
    );

    /*
    app.table1 = React.render(
        React.createElement(Table, { data:app.table1Data }),
        document.getElementById('table1')
    );
    */
}

function testForm2() {
    console.log('in testForm2');

    var testFormFields = [
        {
            type: "HtmlInput",
            data: {
                label: "Student",
                "placeholder": "Student Name"
            }
        },
        {
            type: "HtmlSelect",
            data: {
                label: "Grade",
                value: "grade1",
                options: [
                    { id:"blank", display:"" },
                    { id:"grade1", display:"grade 1" },
                    { id:"grade2", display:"grade 2" },
                    { id:"grade3", display:"grade 3" }
                ]
            }
        }
    ];

    var component2Data = { fields:testFormFields };
    var component2 = React.render(
        <HtmlForm data={ component2Data } />,
        document.getElementById('form2')
    );
}

function testForm3() {
    app.table3Data = {
        boxClass: 'table-container-bordered',
        colModel: {
            id: { name:'id', text:'ID', width:'15%', key:true },
            name: { name:'name', text:'Name', width:'20%', sort:'up' },
            price: { name:'price', text:'Price', width:'15%', type:'money' },
            description: { name:'description', text:'Description', width:'30%' },
            extra: { name:'extra', text:'Extra', show:false, width:'10%' }
        },
        dataItems:[
            { id:'P01', name:'egg', price:7, description:'fresh egg', extra:'n/a' },
            { id:'P21', name:'bread', price:2.99, description:'whole grain bread', extra:'n/a' },
            { id:'P23', name:'chip', price:2.1, description:'potato chip', extra:'n/a' },
            { id:'P54', name:'sauce', price:1.89, description:'dipping sauce', extra:'n/a' },
            { id:'P81', name:'corn', price:4.59, description:'fresh corn', extra:'n/a' }
        ]
    };

    app.table3 = React.render(
        React.createElement(Table, { data:app.table3Data }),
        document.getElementById('form3')
    );

}<|endoftext|>


<commit_before>/*
* Copyright (c) 2014 Stefan Marr, mail@stefan-marr.de
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
const isInIntRange = require('../../lib/platform').isInIntRange;

const Primitives = require('./Primitives').Primitives;

const u = require('../vm/Universe');

function IntegerPrimitives() {
    Primitives.call(this);
    var _this = this;

    function _asString(frame, args) {
        return args[0].primAsString();
    }

    function _sqrt(frame, args) {
        var res = Math.sqrt(args[0].getEmbeddedInteger());
        if (res == Math.floor(res)) {
            return u.universe.newInteger(Math.floor(res));
        } else {
            return u.universe.newDouble(res);
        }
    }

    function _atRandom(frame, args) {
        return u.universe.newInteger(Math.floor(args[0].getEmbeddedInteger()
            * Math.random()));
    }

    function _plus(frame, args) {
        return args[0].primAdd(args[1]);
    }

    function _minus(frame, args) {
        return args[0].primSubtract(args[1]);
    }

    function _mult(frame, args) {
        return args[0].primMultiply(args[1]);
    }

    function _doubleDiv(frame, args) {
        return args[0].primDoubleDiv(args[1]);
    }

    function _intDiv(frame, args) {
        return args[0].primIntDiv(args[1]);
    }

    function _mod(frame, args) {
        return args[0].primModulo(args[1]);
    }

    function _and(frame, args) {
        return args[0].primAnd(args[1]);
    }

    function _equals(frame, args) {
        return args[0].primEquals(args[1]);
    }

    function _equalsEquals(frame, args) {
        return args[0].primEquals(args[1]);
    }

    function _lessThan(frame, args) {
        return args[0].primLessThan(args[1]);
    }

    function _fromString(frame, args) {
        var param = args[1];
        if (!(param instanceof u.SString)) {
            return u.nilObject;
        }
        var intVal = parseInt(param.getEmbeddedString());
        return u.universe.newInteger(intVal);
    }

    function _leftShift(frame, args) {
        var rightObj = args[1];
        var left     = args[0];

        var l = left.getEmbeddedInteger();
        var r = rightObj.getEmbeddedInteger();

        var result = l << r;
        if (Math.floor(l) != l || !isInIntRange(result) || !isInIntRange(l * Math.pow(2, r))) {
            var big = BigInt(l);
            big = big * BigInt(Math.pow(2, r));
            return u.universe.newBigInteger(big);
        }
        return u.universe.newInteger(result);
    }

    function _bitXor(frame, args) {
        var right = args[1];
        var left  = args[0];
        return u.universe.newInteger(left.getEmbeddedInteger()
            ^ right.getEmbeddedInteger())
    }

    function _rem(frame, args) {
        var right = args[1];
        var left  = args[0];
        return u.universe.newInteger(left.getEmbeddedInteger()
            % right.getEmbeddedInteger())
    }

    function _as32BitUnsignedValue(frame, args) {
        return args[0].prim32BitUnsignedValue();
    }

    function _as32BitSignedValue(frame, args) {
        return args[0].prim32BitSignedValue();
    }

    function _unsignedRightShift(frame, args) {
        var right = args[1];
        var left  = args[0];
        return u.universe.newInteger(
            left.getEmbeddedInteger() >>> right.getEmbeddedInteger());
    }

    this.installPrimitives = function () {
        _this.installInstancePrimitive("asString", _asString);
        _this.installInstancePrimitive("sqrt",     _sqrt);
        _this.installInstancePrimitive("atRandom", _atRandom);
        _this.installInstancePrimitive("+",        _plus);
        _this.installInstancePrimitive("-",        _minus);
        _this.installInstancePrimitive("*",        _mult);
        _this.installInstancePrimitive("//",       _doubleDiv);
        _this.installInstancePrimitive("/",        _intDiv);
        _this.installInstancePrimitive("%",        _mod);
        _this.installInstancePrimitive("&",        _and);
        _this.installInstancePrimitive("=",        _equals);
        _this.installInstancePrimitive("==",       _equalsEquals, true);
        _this.installInstancePrimitive("<",        _lessThan);
        _this.installInstancePrimitive("<<",       _leftShift);
        _this.installInstancePrimitive("bitXor:",  _bitXor);
        _this.installInstancePrimitive("rem:",     _rem);
        _this.installInstancePrimitive(">>>",      _unsignedRightShift);

        _this.installInstancePrimitive("as32BitUnsignedValue", _as32BitUnsignedValue);
        _this.installInstancePrimitive("as32BitSignedValue",   _as32BitSignedValue);

        _this.installClassPrimitive("fromString:", _fromString);
    }
}
IntegerPrimitives.prototype = Object.create(Primitives.prototype);
exports.prims = IntegerPrimitives;
<commit_msg>Let over var<commit_after>/*
* Copyright (c) 2014 Stefan Marr, mail@stefan-marr.de
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
const isInIntRange = require('../../lib/platform').isInIntRange;

const Primitives = require('./Primitives').Primitives;

const u = require('../vm/Universe');

function IntegerPrimitives() {
    Primitives.call(this);
    var _this = this;

    function _asString(frame, args) {
        return args[0].primAsString();
    }

    function _sqrt(frame, args) {
        var res = Math.sqrt(args[0].getEmbeddedInteger());
        if (res == Math.floor(res)) {
            return u.universe.newInteger(Math.floor(res));
        } else {
            return u.universe.newDouble(res);
        }
    }

    function _atRandom(frame, args) {
        return u.universe.newInteger(Math.floor(args[0].getEmbeddedInteger()
            * Math.random()));
    }

    function _plus(frame, args) {
        return args[0].primAdd(args[1]);
    }

    function _minus(frame, args) {
        return args[0].primSubtract(args[1]);
    }

    function _mult(frame, args) {
        return args[0].primMultiply(args[1]);
    }

    function _doubleDiv(frame, args) {
        return args[0].primDoubleDiv(args[1]);
    }

    function _intDiv(frame, args) {
        return args[0].primIntDiv(args[1]);
    }

    function _mod(frame, args) {
        return args[0].primModulo(args[1]);
    }

    function _and(frame, args) {
        return args[0].primAnd(args[1]);
    }

    function _equals(frame, args) {
        return args[0].primEquals(args[1]);
    }

    function _equalsEquals(frame, args) {
        return args[0].primEquals(args[1]);
    }

    function _lessThan(frame, args) {
        return args[0].primLessThan(args[1]);
    }

    function _fromString(frame, args) {
        var param = args[1];
        if (!(param instanceof u.SString)) {
            return u.nilObject;
        }
        var intVal = parseInt(param.getEmbeddedString());
        return u.universe.newInteger(intVal);
    }

    function _leftShift(frame, args) {
        var rightObj = args[1];
        var left     = args[0];

        var l = left.getEmbeddedInteger();
        var r = rightObj.getEmbeddedInteger();

        var result = l << r;
        if (Math.floor(l) != l || !isInIntRange(result) || !isInIntRange(l * Math.pow(2, r))) {
            var big = BigInt(l);
            big = big * BigInt(Math.pow(2, r));
            return u.universe.newBigInteger(big);
        }
        return u.universe.newInteger(result);
    }

    function _bitXor(frame, args) {
        let right = args[1];
        let left  = args[0];
        return u.universe.newInteger(left.getEmbeddedInteger()
            ^ right.getEmbeddedInteger())
    }

    function _rem(frame, args) {
        var right = args[1];
        var left  = args[0];
        return u.universe.newInteger(left.getEmbeddedInteger()
            % right.getEmbeddedInteger())
    }

    function _as32BitUnsignedValue(frame, args) {
        return args[0].prim32BitUnsignedValue();
    }

    function _as32BitSignedValue(frame, args) {
        return args[0].prim32BitSignedValue();
    }

    function _unsignedRightShift(frame, args) {
        var right = args[1];
        var left  = args[0];
        return u.universe.newInteger(
            left.getEmbeddedInteger() >>> right.getEmbeddedInteger());
    }

    this.installPrimitives = function () {
        _this.installInstancePrimitive("asString", _asString);
        _this.installInstancePrimitive("sqrt",     _sqrt);
        _this.installInstancePrimitive("atRandom", _atRandom);
        _this.installInstancePrimitive("+",        _plus);
        _this.installInstancePrimitive("-",        _minus);
        _this.installInstancePrimitive("*",        _mult);
        _this.installInstancePrimitive("//",       _doubleDiv);
        _this.installInstancePrimitive("/",        _intDiv);
        _this.installInstancePrimitive("%",        _mod);
        _this.installInstancePrimitive("&",        _and);
        _this.installInstancePrimitive("=",        _equals);
        _this.installInstancePrimitive("==",       _equalsEquals, true);
        _this.installInstancePrimitive("<",        _lessThan);
        _this.installInstancePrimitive("<<",       _leftShift);
        _this.installInstancePrimitive("bitXor:",  _bitXor);
        _this.installInstancePrimitive("rem:",     _rem);
        _this.installInstancePrimitive(">>>",      _unsignedRightShift);

        _this.installInstancePrimitive("as32BitUnsignedValue", _as32BitUnsignedValue);
        _this.installInstancePrimitive("as32BitSignedValue",   _as32BitSignedValue);

        _this.installClassPrimitive("fromString:", _fromString);
    }
}
IntegerPrimitives.prototype = Object.create(Primitives.prototype);
exports.prims = IntegerPrimitives;
<|endoftext|>


<commit_before>$("#name-submit").on('click', function() {
    var name = $('#name-box').val();
    console.log("submitting " + name);
    $.get({
      url: 'http://app.server.local/hello/'+name,
      success: function() {
        $('#name-last').text(name);
      },
      error: function() {
        $('#name-last').text("error");
      }
    });
});
<commit_msg>fetch script<commit_after>$("#name-submit").on('click', function() {
    var name = $('#name-box').val();
    console.log("submitting " + name);
    $.get({
      url: 'http://app.server.local/hello/'+name,
      success: function(resp) {
        $('#name-last').text(resp.body);
      },
      error: function() {
        $('#name-last').text("error");
      }
    });
});
<|endoftext|>


<commit_before>/*eslint no-console: 0*/

import _ from 'lodash'
import superAgent from 'superagent'
import config from '../config'
import constants from '../constants'
import querystring from 'qs'

export default function loadArticles(req, params = []) {
  return new Promise((resolve, reject) => {
    const query = req.query
    const { API_PROTOCOL, API_PORT, API_HOST } = config
    let url = `${API_PROTOCOL}://${API_HOST}:${API_PORT}/posts`
    let slug = typeof params[0] === 'string' ? params[0] : null
    url = slug ? `${url}/${slug}` : url
    superAgent['get'](url).timeout(constants.timeout)
    .query(query)
    .end(function (err, res) {
      if (err) {
        reject(err)
      } else {
        const queryObj = JSON.parse(_.get(query, 'embedded'))
        let aricleRes = res.body
        let writers =  []
        const list = [ 'writters', 'photographers', 'designers', 'engineers' ]
        list.forEach((item) => {
          let aArr = _.get(aricleRes, item, [])
          aArr.forEach((author) => {
            if(author.image) {
              writers.push(author.image)
            }
          })
        })

        // combine author images data if the query contains 'authorImages'
        if(_.get(queryObj, 'authorImages')) {
          const imgIds = _.uniq(writers)
          const imgQuery = querystring.stringify({ where: JSON.stringify({ _id: { '$in': imgIds } } ) })
          const imgUrl = `${API_PROTOCOL}://${API_HOST}:${API_PORT}/images?${imgQuery}`

          superAgent['get'](imgUrl).timeout(constants.timeout)
          .end(function (err, res) {
            if (err) {
              console.warning('AUTHOR IMAGE LOADING FAILED:', err)
            } else {
              const imgItems = _.get(res.body, '_items')

              list.forEach((item) => {
                let authors = _.get(aricleRes, item, [])
                addImage(authors, imgItems)
              })
            }
            resolve(aricleRes)
          })
        } else {
          resolve(aricleRes)
        }
      }
    })
  })
}

function addImage(authors, imgItems) {
  authors.forEach((author) => {
    if(author.image) {
      let match = _.filter(imgItems, '_id', author.image)
      const wImg = _.get(match, [ 0, 'image' ])
      author.image = wImg
    }
  })
}
<commit_msg>fix bug. JSON.parse occurs error when query.embedded is undefined<commit_after>/*eslint no-console: 0*/

import _ from 'lodash'
import superAgent from 'superagent'
import config from '../config'
import constants from '../constants'
import querystring from 'qs'

export default function loadArticles(req, params = []) {
  return new Promise((resolve, reject) => {
    const query = req.query
    const { API_PROTOCOL, API_PORT, API_HOST } = config
    let url = `${API_PROTOCOL}://${API_HOST}:${API_PORT}/posts`
    let slug = typeof params[0] === 'string' ? params[0] : null
    url = slug ? `${url}/${slug}` : url
    superAgent['get'](url).timeout(constants.timeout)
    .query(query)
    .end(function (err, res) {
      if (err) {
        reject(err)
      } else {
        let aricleRes = res.body
        let writers =  []
        const list = [ 'writters', 'photographers', 'designers', 'engineers' ]
        list.forEach((item) => {
          let aArr = _.get(aricleRes, item, [])
          aArr.forEach((author) => {
            if(author.image) {
              writers.push(author.image)
            }
          })
        })

        // combine author images data if the query contains 'authorImages'
        if(_.get(query, [ 'embedded', 'authorImages' ])) {
          const imgIds = _.uniq(writers)
          const imgQuery = querystring.stringify({ where: JSON.stringify({ _id: { '$in': imgIds } } ) })
          const imgUrl = `${API_PROTOCOL}://${API_HOST}:${API_PORT}/images?${imgQuery}`

          superAgent['get'](imgUrl).timeout(constants.timeout)
          .end(function (err, res) {
            if (err) {
              console.warning('AUTHOR IMAGE LOADING FAILED:', err)
            } else {
              const imgItems = _.get(res.body, '_items')

              list.forEach((item) => {
                let authors = _.get(aricleRes, item, [])
                addImage(authors, imgItems)
              })
            }
            resolve(aricleRes)
          })
        } else {
          resolve(aricleRes)
        }
      }
    })
  })
}

function addImage(authors, imgItems) {
  authors.forEach((author) => {
    if(author.image) {
      let match = _.filter(imgItems, '_id', author.image)
      const wImg = _.get(match, [ 0, 'image' ])
      author.image = wImg
    }
  })
}
<|endoftext|>


<commit_before>var path = require('path');
var temp = require('temp');
var child = require('child_process');
var which = require('which');
var fs = require('fs');
var mkdirp = require('mkdirp');

function compile(name, args, options) {
  args = args.slice();

  var dirpath = temp.mkdirSync('amok-output');
  var pathname = args[0].replace(/\.[^\.]+$/, '.js');

  var filename = path.join(dirpath, pathname);
  var dirname = path.dirname(filename);
  mkdirp.sync(dirname);

  var scripts = {};
  scripts[filename] = pathname;

  switch (name) {
    case 'browserify':
      command = which.sync('watchify');
      args = [
        '-o',
        filename
      ];
      break;

    case 'webpack':
      command = which.sync('webpack');
      args = [
        '--watch',
        '--output-file',
        filename
      ];
      break;

    case 'typescript':
      command = which.sync('tsc');
      args = [
        '--watch',
        '--out',
        filename
      ];
      break;

    case 'coffeescript':
      command = which.sync('coffee');
      args = [
        '--watch',
        '--compile',
        '--output',
        dirpath
      ];
      break;

    case 'babel':
      command = which.sync('babel');
      args = [
        '--watch',
        '--out-file',
        filename
      ];
      break;
  }

  var compiler = child.spawn(command, args);

  process.nextTick(function tick() {
    fs.exists(filename, function(exists) {
      if (exists) {
        compiler.emit('ready', scripts);
      } else {
        setTimeout(tick, 100);
      }
    });
  });

  return compiler;
}

module.exports = compile;
<commit_msg>Rename tempdir suffix from output to scripts<commit_after>var path = require('path');
var temp = require('temp');
var child = require('child_process');
var which = require('which');
var fs = require('fs');
var mkdirp = require('mkdirp');

function compile(name, args, options) {
  args = args.slice();

  var dirpath = temp.mkdirSync('scripts');
  var pathname = args[0].replace(/\.[^\.]+$/, '.js');

  var filename = path.join(dirpath, pathname);
  var dirname = path.dirname(filename);
  mkdirp.sync(dirname);

  var scripts = {};
  scripts[filename] = pathname;

  switch (name) {
    case 'browserify':
      command = which.sync('watchify');
      args = [
        '-o',
        filename
      ];
      break;

    case 'webpack':
      command = which.sync('webpack');
      args = [
        '--watch',
        '--output-file',
        filename
      ];
      break;

    case 'typescript':
      command = which.sync('tsc');
      args = [
        '--watch',
        '--out',
        filename
      ];
      break;

    case 'coffeescript':
      command = which.sync('coffee');
      args = [
        '--watch',
        '--compile',
        '--output',
        dirpath
      ];
      break;

    case 'babel':
      command = which.sync('babel');
      args = [
        '--watch',
        '--out-file',
        filename
      ];
      break;
  }

  var compiler = child.spawn(command, args);

  process.nextTick(function tick() {
    fs.exists(filename, function(exists) {
      if (exists) {
        compiler.emit('ready', scripts);
      } else {
        setTimeout(tick, 100);
      }
    });
  });

  return compiler;
}

module.exports = compile;
<|endoftext|>


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

var assert = require('assert');
var Decompress = require('../');
var fs = require('fs');
var path = require('path');
var rm = require('rimraf');

describe('decompress()', function () {
    afterEach(function (cb) {
        rm(path.join(__dirname, 'tmp'), cb);
    });

    it('should extract .tar', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.tar'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.tar())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .tar.gz', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.tar.gz'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.targz())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .zip', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.zip'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.zip())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .zip using the strip option', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test-strip.zip'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.zip({ strip: 1 }))
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });
});
<commit_msg>Fix tests<commit_after>/*global afterEach, describe, it */
'use strict';

var assert = require('assert');
var Decompress = require('../');
var fs = require('fs');
var path = require('path');
var rm = require('rimraf');

describe('decompress()', function () {
    afterEach(function (cb) {
        rm(path.join(__dirname, 'tmp'), cb);
    });

    it('should extract .tar', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.tar'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.tar())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .tar.gz', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.tar.gz'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.targz())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .zip', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.zip'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.zip())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .zip using the strip option', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test-strip.zip'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.zip({ strip: 1 }))
            .decompress(function (err) {
                console.log(err);
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test-strip.jpg')));
                cb();
            });
    });
});
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
// Create the chat configuration
module.exports = function(io, socket) {
  socket.on('init', function(req) {
    console.log('Has user join system');
  });

  // Emit the status event when a socket client is disconnected
  socket.on('disconnect', function() {
    console.log('Has user out system');
  });
};
<commit_msg>Commited from lenh at Fri, Jun 23, 2017  2:58:00 PM<commit_after>'use strict';

const _ = require('lodash');
// Create the chat configuration
module.exports = function (io, socket) {
  socket.on('init', function (req) {
    console.log('Has user join system');
    if (!_.constant(global.socketUsers, { socket: socket.id })) {
      global.socketUsers.push({ socket: socket.id, user: req.user });
    }
    console.log('Online users: ', global.socketUsers.length);
  });

  // Emit the status event when a socket client is disconnected
  socket.on('disconnect', function () {
    global.socketUsers = _.without(global.socketUsers, { socket: socket.id });
    console.log('Has user out system');
    console.log('Online users: ', global.socketUsers.length);
  });
};
<|endoftext|>


<commit_before>/* eslint-disable global-require */

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import Appbase from 'appbase-js';
import 'url-search-params-polyfill';
import { ThemeProvider } from 'emotion-theming';

import configureStore from '@appbaseio/reactivecore';
import { checkSomePropChange } from '@appbaseio/reactivecore/lib/utils/helper';
import { updateAnalyticsConfig } from '@appbaseio/reactivecore/lib/actions/analytics';
import types from '@appbaseio/reactivecore/lib/utils/types';
import URLParamsProvider from './URLParamsProvider';

import getTheme from '../../styles/theme';
import { composeThemeObject, ReactReduxContext } from '../../utils';

class ReactiveBase extends Component {
	constructor(props) {
		super(props);

		this.state = {
			key: '__REACTIVE_BASE__',
		};

		this.setStore(props);
	}

	componentDidMount() {
		const { searchStateHeader, analyticsConfig, analytics } = this.props;
		// TODO: Remove in 4.0
		if (searchStateHeader !== undefined) {
			console.warn(
				'Warning(ReactiveSearch): The `searchStateHeader` prop has been marked as deprecated, please use the `appbaseConfig` prop instead.',
			);
		}
		// TODO: Remove in 4.0
		if (analyticsConfig !== undefined) {
			console.warn(
				'Warning(ReactiveSearch): The `analyticsConfig` prop has been marked as deprecated, please use the `appbaseConfig` prop instead.',
			);
		}
		// TODO: Remove in 4.0
		if (analytics !== undefined) {
			console.warn(
				'Warning(ReactiveSearch): The `analytics` prop has been marked as deprecated, please set the `recordAnalytics` property as `true` in `appbaseConfig` prop instead.',
			);
		}
	}

	componentDidUpdate(prevProps) {
		checkSomePropChange(
			this.props,
			prevProps,
			['app', 'url', 'type', 'credentials', 'mapKey', 'headers', 'graphQLUrl'],
			() => {
				this.setStore(this.props);
				this.setState(state => ({
					key: `${state.key}-0`,
				}));
			},
		);
		checkSomePropChange(this.props, prevProps, ['analyticsConfig'], () => {
			if (this.store) {
				this.store.dispatch(updateAnalyticsConfig(this.props.analyticsConfig));
			}
		});
		checkSomePropChange(this.props, prevProps, ['appbaseConfig'], () => {
			if (this.store) {
				this.store.dispatch(updateAnalyticsConfig(this.props.appbaseConfig));
			}
		});
	}

	componentDidCatch(error, errorInfo) {
		console.error(
			"An error has occured. You're using Reactivesearch Version:",
			`${process.env.VERSION || require('../../../package.json').version}.`,
			'If you think this is a problem with Reactivesearch, please try updating',
			"to the latest version. If you're already at the latest version, please open",
			'an issue at https://github.com/appbaseio/reactivesearch/issues',
			error,
			errorInfo,
		);
	}

	setStore = (props) => {
		this.type = props.type ? props.type : '*';

		const credentials
			= props.url && props.url.trim() !== '' && !props.credentials ? null : props.credentials;

		const appbaseConfig = {
			searchStateHeader: props.searchStateHeader, // for backward compatibility
			...props.analyticsConfig, // TODO: remove in 4.0
			...props.appbaseConfig,
		};
		const config = {
			url: props.url && props.url.trim() !== '' ? props.url : 'https://scalr.api.appbase.io',
			app: props.app,
			credentials,
			type: this.type,
			transformRequest: props.transformRequest,
			analytics: props.appbaseConfig
				? props.appbaseConfig.recordAnalytics
				: !!props.analytics,
			enableAppbase: props.enableAppbase,
			analyticsConfig: appbaseConfig,
			graphQLUrl: props.graphQLUrl,
			transformResponse: props.transformResponse,
		};

		let queryParams = '';
		if (typeof window !== 'undefined') {
			queryParams = props.getSearchParams ? props.getSearchParams() : window.location.search;
		} else {
			queryParams = props.queryParams || '';
		}

		const params = new URLSearchParams(queryParams);
		let selectedValues = {};

		Array.from(params.keys()).forEach((key) => {
			try {
				const parsedParams = JSON.parse(params.get(key));
				const selectedValue = {};
				if (parsedParams.value) {
					selectedValue.value = parsedParams.value;
				} else {
					selectedValue.value = parsedParams;
				}
				if (parsedParams.category) selectedValue.category = parsedParams.category;
				selectedValues = {
					...selectedValues,
					[key]: selectedValue,
				};
			} catch (e) {
				// Do not add to selectedValues if JSON parsing fails.
			}
		});

		const { headers = {}, themePreset } = props;

		const headersObject = { 'X-Search-Client': 'ReactiveSearch React', ...headers };

		const appbaseRef = Appbase(config);
		if (this.props.transformRequest) {
			appbaseRef.transformRequest = this.props.transformRequest;
		}

		const initialState = {
			config: { ...config, mapKey: props.mapKey, themePreset },
			appbaseRef,
			selectedValues,
			headers: headersObject,
			...this.props.initialState,
		};
		this.store = configureStore(initialState);
	};

	render() {
		const theme = composeThemeObject(getTheme(this.props.themePreset), this.props.theme);

		const headersObject = { 'X-Search-Client': 'ReactiveSearch React', ...this.props.headers };
		return (
			<ThemeProvider theme={theme} key={this.state.key}>
				<Provider context={ReactReduxContext} store={this.store}>
					<URLParamsProvider
						headers={headersObject}
						style={this.props.style}
						as={this.props.as}
						className={this.props.className}
						getSearchParams={this.props.getSearchParams}
						setSearchParams={this.props.setSearchParams}
					>
						{this.props.children}
					</URLParamsProvider>
				</Provider>
			</ThemeProvider>
		);
	}
}

ReactiveBase.defaultProps = {
	theme: {},
	themePreset: 'light',
	initialState: {},
	graphQLUrl: '',
	as: 'div',
	enableAppbase: false,
};

ReactiveBase.propTypes = {
	app: types.stringRequired,
	searchStateHeader: types.bool,
	as: types.string,
	children: types.children,
	credentials: types.string,
	headers: types.headers,
	queryParams: types.string,
	theme: types.style,
	themePreset: types.themePreset,
	type: types.string,
	url: types.string,
	transformRequest: types.func,
	mapKey: types.string,
	style: types.style,
	className: types.string,
	initialState: types.children,
	analytics: types.bool,
	enableAppbase: types.bool,
	analyticsConfig: types.analyticsConfig,
	appbaseConfig: types.appbaseConfig,
	graphQLUrl: types.string,
	transformResponse: types.func,
	getSearchParams: types.func,
	setSearchParams: types.func,
};

export default ReactiveBase;
<commit_msg>feat: added x-search-client: _reactive_search-react headerin  rs-react<commit_after>/* eslint-disable global-require */

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import Appbase from 'appbase-js';
import 'url-search-params-polyfill';
import { ThemeProvider } from 'emotion-theming';

import configureStore from '@appbaseio/reactivecore';
import { checkSomePropChange } from '@appbaseio/reactivecore/lib/utils/helper';
import { updateAnalyticsConfig } from '@appbaseio/reactivecore/lib/actions/analytics';
import types from '@appbaseio/reactivecore/lib/utils/types';
import URLParamsProvider from './URLParamsProvider';

import getTheme from '../../styles/theme';
import { composeThemeObject, ReactReduxContext } from '../../utils';

class ReactiveBase extends Component {
	constructor(props) {
		super(props);

		this.state = {
			key: '__REACTIVE_BASE__',
		};

		this.setStore(props);
	}

	componentDidMount() {
		const { searchStateHeader, analyticsConfig, analytics } = this.props;
		// TODO: Remove in 4.0
		if (searchStateHeader !== undefined) {
			console.warn(
				'Warning(ReactiveSearch): The `searchStateHeader` prop has been marked as deprecated, please use the `appbaseConfig` prop instead.',
			);
		}
		// TODO: Remove in 4.0
		if (analyticsConfig !== undefined) {
			console.warn(
				'Warning(ReactiveSearch): The `analyticsConfig` prop has been marked as deprecated, please use the `appbaseConfig` prop instead.',
			);
		}
		// TODO: Remove in 4.0
		if (analytics !== undefined) {
			console.warn(
				'Warning(ReactiveSearch): The `analytics` prop has been marked as deprecated, please set the `recordAnalytics` property as `true` in `appbaseConfig` prop instead.',
			);
		}
	}

	componentDidUpdate(prevProps) {
		checkSomePropChange(
			this.props,
			prevProps,
			['app', 'url', 'type', 'credentials', 'mapKey', 'headers', 'graphQLUrl'],
			() => {
				this.setStore(this.props);
				this.setState((state) => ({
					key: `${state.key}-0`,
				}));
			},
		);
		checkSomePropChange(this.props, prevProps, ['analyticsConfig'], () => {
			if (this.store) {
				this.store.dispatch(updateAnalyticsConfig(this.props.analyticsConfig));
			}
		});
		checkSomePropChange(this.props, prevProps, ['appbaseConfig'], () => {
			if (this.store) {
				this.store.dispatch(updateAnalyticsConfig(this.props.appbaseConfig));
			}
		});
	}

	componentDidCatch(error, errorInfo) {
		console.error(
			"An error has occured. You're using Reactivesearch Version:",
			`${process.env.VERSION || require('../../../package.json').version}.`,
			'If you think this is a problem with Reactivesearch, please try updating',
			"to the latest version. If you're already at the latest version, please open",
			'an issue at https://github.com/appbaseio/reactivesearch/issues',
			error,
			errorInfo,
		);
	}

	setStore = (props) => {
		this.type = props.type ? props.type : '*';

		const credentials =
			props.url && props.url.trim() !== '' && !props.credentials ? null : props.credentials;

		const appbaseConfig = {
			searchStateHeader: props.searchStateHeader, // for backward compatibility
			...props.analyticsConfig, // TODO: remove in 4.0
			...props.appbaseConfig,
		};
		const config = {
			url: props.url && props.url.trim() !== '' ? props.url : 'https://scalr.api.appbase.io',
			app: props.app,
			credentials,
			type: this.type,
			transformRequest: props.transformRequest,
			analytics: props.appbaseConfig
				? props.appbaseConfig.recordAnalytics
				: !!props.analytics,
			enableAppbase: props.enableAppbase,
			analyticsConfig: appbaseConfig,
			graphQLUrl: props.graphQLUrl,
			transformResponse: props.transformResponse,
		};

		let queryParams = '';
		if (typeof window !== 'undefined') {
			queryParams = props.getSearchParams ? props.getSearchParams() : window.location.search;
		} else {
			queryParams = props.queryParams || '';
		}

		const params = new URLSearchParams(queryParams);
		let selectedValues = {};

		Array.from(params.keys()).forEach((key) => {
			try {
				const parsedParams = JSON.parse(params.get(key));
				const selectedValue = {};
				if (parsedParams.value) {
					selectedValue.value = parsedParams.value;
				} else {
					selectedValue.value = parsedParams;
				}
				if (parsedParams.category) selectedValue.category = parsedParams.category;
				selectedValues = {
					...selectedValues,
					[key]: selectedValue,
				};
			} catch (e) {
				// Do not add to selectedValues if JSON parsing fails.
			}
		});

		const { themePreset } = props;

		const headers = { 'X-Search-Client': 'ReactiveSearch React', ...this.props.headers };

		const appbaseRef = Appbase(config);
		if (this.props.transformRequest) {
			appbaseRef.transformRequest = this.props.transformRequest;
		}

		const initialState = {
			config: { ...config, mapKey: props.mapKey, themePreset },
			appbaseRef,
			selectedValues,
			headers,
			...this.props.initialState,
		};
		this.store = configureStore(initialState);
	};

	render() {
		const theme = composeThemeObject(getTheme(this.props.themePreset), this.props.theme);

		const headers = { 'X-Search-Client': 'ReactiveSearch React', ...this.props.headers };
		return (
			<ThemeProvider theme={theme} key={this.state.key}>
				<Provider context={ReactReduxContext} store={this.store}>
					<URLParamsProvider
						headers={headers}
						style={this.props.style}
						as={this.props.as}
						className={this.props.className}
						getSearchParams={this.props.getSearchParams}
						setSearchParams={this.props.setSearchParams}
					>
						{this.props.children}
					</URLParamsProvider>
				</Provider>
			</ThemeProvider>
		);
	}
}

ReactiveBase.defaultProps = {
	theme: {},
	themePreset: 'light',
	initialState: {},
	graphQLUrl: '',
	as: 'div',
	enableAppbase: false,
};

ReactiveBase.propTypes = {
	app: types.stringRequired,
	searchStateHeader: types.bool,
	as: types.string,
	children: types.children,
	credentials: types.string,
	headers: types.headers,
	queryParams: types.string,
	theme: types.style,
	themePreset: types.themePreset,
	type: types.string,
	url: types.string,
	transformRequest: types.func,
	mapKey: types.string,
	style: types.style,
	className: types.string,
	initialState: types.children,
	analytics: types.bool,
	enableAppbase: types.bool,
	analyticsConfig: types.analyticsConfig,
	appbaseConfig: types.appbaseConfig,
	graphQLUrl: types.string,
	transformResponse: types.func,
	getSearchParams: types.func,
	setSearchParams: types.func,
};

export default ReactiveBase;
<|endoftext|>