<commit_before>'use strict';

var expect = require('chai').expect;
var path = require('path');
var bunyan = require('bunyan');
var Api = require('../').Api;
var Request = require('../lib/request');

var log = bunyan.createLogger({name: 'null', streams: []});
var resourcesPath = path.join(__dirname, 'fixtures', 'extensions', 'resources');

var testDataSource = function testDataSource() {
    return {
        process: function (request, callback) {
            callback(null, {
                data: [{
                    id: 1,
                    foo: 'bar'
                }, {
                    id: 2,
                    foo: 'baz'
                }],
                totalCount: null
            });
        },
        prepare: function () {}
    };
};

var testConfig = {
    log: log,
    resourcesPath: resourcesPath,
    dataSources: {
        empty: {
            constructor: testDataSource
        }
    }
};

describe('extensions', function () {
    describe('Api', function () {
        describe('init', function() {
            it('is emitted when the instance is initialized', function (done) {
                var api = new Api();

                api.on('init', function () {
                    api.close(done);
                });

                api.init({log: log});
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();

                var initEmitted = false;
                api.on('init', function (ev, next) {
                    expect(next).to.be.a('function');
                    initEmitted = true;
                    next();
                });

                api.init({log: log}, function () {
                    expect(initEmitted).to.eql(true);
                    api.close(done);
                });
            });
        });

        describe('request', function () {
            it('is emitted when a request is made', function (done) {
                var api = new Api();

                api.init({log: log}, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function () {
                        api.close(done);
                    });
                });

                api.on('request', function (ev) {
                    expect(ev).to.be.an('object');
                    expect(ev.request).to.be.an('object');
                    expect(ev.request.resource).to.eql('test');
                });
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();

                api.init({log: log}, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function () {
                        api.close(done);
                    });
                });

                api.on('request', function (ev, next) {
                    expect(ev).to.be.an('object');
                    expect(ev.request).to.be.an('object');
                    expect(ev.request.resource).to.eql('test');
                    expect(next).to.be.a('function');
                    next();
                });
            });
        });

        describe('response', function () {
            it('is emitted before a response is sent', function (done) {
                var api = new Api();

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        api.close(done);
                    });

                });

                api.on('response', function (ev) {
                    expect(ev).to.be.an('object');
                    expect(ev.response).to.be.an('object');
                    expect(ev.response.data).to.be.an('array');
                });
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();
                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err, response) {
                        if (err) return done(err);
                        expect(responseEmitted).to.eql(true);
                        api.close(done);
                    });
                });

                var responseEmitted = false;

                api.on('response', function (ev, next) {
                    responseEmitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.response).to.be.an('object');
                    expect(ev.response.data).to.be.an('array');
                    expect(next).to.be.a('function');
                    next();
                });
            });
        });

        describe('close', function () {
            it('is emitted when the instance is closed', function (done) {
                var api = new Api();
                api.on('init', function () {
                    api.close();
                });

                api.on('close', done);

                api.init({log: log});
            });

            it('can be called asynchronously', function (done) {
                var closeCalled = false;

                var api = new Api();
                api.on('init', function () {
                    api.close(function () {
                        expect(closeCalled).to.eql(true);
                        done();
                    });
                });

                api.on('close', function (ev, next) {
                    expect(next).to.be.a('function');
                    closeCalled = true;
                    next();
                });

                api.init({log: log});
            });
        });
    });

    describe('resource-processor', function () {
        describe('preExecute', function() {
            it('is emitted with a dataSourceTree', function (done) {
                var api = new Api();
                var emitted = false;

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        expect(emitted).to.eql(true);
                        api.close(done);
                    });

                });

                api.on('preExecute', function (ev) {
                    emitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.dataSourceTree).to.be.an('object');
                });
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();
                var emitted = false;

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        expect(emitted).to.eql(true);
                        api.close(done);
                    });
                });

                var responseEmitted = false;

                api.on('preExecute', function (ev, next) {
                    emitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.dataSourceTree).to.be.an('object');
                    expect(next).to.be.a('function');
                    next();
                });
            });
        });

        describe('postExecute', function() {
            it('is emitted with rawResults', function (done) {
                var api = new Api();
                var emitted = false;

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        expect(emitted).to.eql(true);
                        api.close(done);
                    });

                });

                api.on('postExecute', function (ev) {
                    emitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.rawResults).to.be.an('array');
                });
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();
                var emitted = false;

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        expect(emitted).to.eql(true);
                        api.close(done);
                    });
                });

                var responseEmitted = false;

                api.on('postExecute', function (ev, next) {
                    emitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.rawResults).to.be.an('array');
                    expect(next).to.be.a('function');
                    next();
                });
            });
        });
    });

    describe('resource', function () {
        describe('item', function () {
            it('is emitted when an item is handled', function (done) {
                var api = new Api();

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        api.close(done);
                    });

                });

                api.on('response', function (ev) {
                    expect(ev).to.be.an('object');
                    expect(ev.response).to.be.an('object');
                    expect(ev.response.data).to.be.an('array');
                    expect(ev.response.data.length).to.greaterThan(0);
                    expect(ev.response.data[0]).to.eql({
                        id: 1,
                        bar: 'baz' // this is set by "item" callback, see fixtures/excensions/test/index.js
                    });
                });
            });
        });
    });
});
<commit_msg>tests: typo in comment<commit_after>'use strict';

var expect = require('chai').expect;
var path = require('path');
var bunyan = require('bunyan');
var Api = require('../').Api;
var Request = require('../lib/request');

var log = bunyan.createLogger({name: 'null', streams: []});
var resourcesPath = path.join(__dirname, 'fixtures', 'extensions', 'resources');

var testDataSource = function testDataSource() {
    return {
        process: function (request, callback) {
            callback(null, {
                data: [{
                    id: 1,
                    foo: 'bar'
                }, {
                    id: 2,
                    foo: 'baz'
                }],
                totalCount: null
            });
        },
        prepare: function () {}
    };
};

var testConfig = {
    log: log,
    resourcesPath: resourcesPath,
    dataSources: {
        empty: {
            constructor: testDataSource
        }
    }
};

describe('extensions', function () {
    describe('Api', function () {
        describe('init', function() {
            it('is emitted when the instance is initialized', function (done) {
                var api = new Api();

                api.on('init', function () {
                    api.close(done);
                });

                api.init({log: log});
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();

                var initEmitted = false;
                api.on('init', function (ev, next) {
                    expect(next).to.be.a('function');
                    initEmitted = true;
                    next();
                });

                api.init({log: log}, function () {
                    expect(initEmitted).to.eql(true);
                    api.close(done);
                });
            });
        });

        describe('request', function () {
            it('is emitted when a request is made', function (done) {
                var api = new Api();

                api.init({log: log}, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function () {
                        api.close(done);
                    });
                });

                api.on('request', function (ev) {
                    expect(ev).to.be.an('object');
                    expect(ev.request).to.be.an('object');
                    expect(ev.request.resource).to.eql('test');
                });
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();

                api.init({log: log}, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function () {
                        api.close(done);
                    });
                });

                api.on('request', function (ev, next) {
                    expect(ev).to.be.an('object');
                    expect(ev.request).to.be.an('object');
                    expect(ev.request.resource).to.eql('test');
                    expect(next).to.be.a('function');
                    next();
                });
            });
        });

        describe('response', function () {
            it('is emitted before a response is sent', function (done) {
                var api = new Api();

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        api.close(done);
                    });

                });

                api.on('response', function (ev) {
                    expect(ev).to.be.an('object');
                    expect(ev.response).to.be.an('object');
                    expect(ev.response.data).to.be.an('array');
                });
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();
                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err, response) {
                        if (err) return done(err);
                        expect(responseEmitted).to.eql(true);
                        api.close(done);
                    });
                });

                var responseEmitted = false;

                api.on('response', function (ev, next) {
                    responseEmitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.response).to.be.an('object');
                    expect(ev.response.data).to.be.an('array');
                    expect(next).to.be.a('function');
                    next();
                });
            });
        });

        describe('close', function () {
            it('is emitted when the instance is closed', function (done) {
                var api = new Api();
                api.on('init', function () {
                    api.close();
                });

                api.on('close', done);

                api.init({log: log});
            });

            it('can be called asynchronously', function (done) {
                var closeCalled = false;

                var api = new Api();
                api.on('init', function () {
                    api.close(function () {
                        expect(closeCalled).to.eql(true);
                        done();
                    });
                });

                api.on('close', function (ev, next) {
                    expect(next).to.be.a('function');
                    closeCalled = true;
                    next();
                });

                api.init({log: log});
            });
        });
    });

    describe('resource-processor', function () {
        describe('preExecute', function() {
            it('is emitted with a dataSourceTree', function (done) {
                var api = new Api();
                var emitted = false;

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        expect(emitted).to.eql(true);
                        api.close(done);
                    });

                });

                api.on('preExecute', function (ev) {
                    emitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.dataSourceTree).to.be.an('object');
                });
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();
                var emitted = false;

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        expect(emitted).to.eql(true);
                        api.close(done);
                    });
                });

                var responseEmitted = false;

                api.on('preExecute', function (ev, next) {
                    emitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.dataSourceTree).to.be.an('object');
                    expect(next).to.be.a('function');
                    next();
                });
            });
        });

        describe('postExecute', function() {
            it('is emitted with rawResults', function (done) {
                var api = new Api();
                var emitted = false;

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        expect(emitted).to.eql(true);
                        api.close(done);
                    });

                });

                api.on('postExecute', function (ev) {
                    emitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.rawResults).to.be.an('array');
                });
            });

            it('can be called asynchronously', function (done) {
                var api = new Api();
                var emitted = false;

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        expect(emitted).to.eql(true);
                        api.close(done);
                    });
                });

                var responseEmitted = false;

                api.on('postExecute', function (ev, next) {
                    emitted = true;
                    expect(ev).to.be.an('object');
                    expect(ev.rawResults).to.be.an('array');
                    expect(next).to.be.a('function');
                    next();
                });
            });
        });
    });

    describe('resource', function () {
        describe('item', function () {
            it('is emitted when an item is handled', function (done) {
                var api = new Api();

                api.init(testConfig, function (err) {
                    if (err) return done(err);

                    var request = new Request({resource: 'test'});
                    api.execute(request, function (err) {
                        if (err) return done(err);
                        api.close(done);
                    });

                });

                api.on('response', function (ev) {
                    expect(ev).to.be.an('object');
                    expect(ev.response).to.be.an('object');
                    expect(ev.response.data).to.be.an('array');
                    expect(ev.response.data.length).to.greaterThan(0);
                    expect(ev.response.data[0]).to.eql({
                        id: 1,
                        bar: 'baz' // this is set by "item" callback, see fixtures/extensions/test/index.js
                    });
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>/*
 * This function process the active symbols to get markets
 * and underlying list
 */
function processActiveSymbols(data) {
    'use strict';

    // populate the Symbols object
    Symbols.details(data);

    var market = getDefaultMarket();

    // store the market
    sessionStorage.setItem('market', market);

    displayMarkets('contract_markets', Symbols.markets(), market);
    processMarket();
    // setTimeout(function(){
    // if(document.getElementById('underlying')){
    //     Symbols.getSymbols(0);
    // }
    // }, 60*1000);
}

/*
 * Function to call when market has changed
 */
function processMarket(flag) {
    'use strict';

    // we can get market from sessionStorage as allowed market
    // is already set when this function is called
    var market = sessionStorage.getItem('market');
    var symbol = sessionStorage.getItem('underlying');
    var update_page = Symbols.need_page_update() || flag;

    if (update_page && (!symbol || !Symbols.underlyings()[market][symbol] || !Symbols.underlyings()[market][symbol].is_active)) {
        symbol = undefined;
    }
    displayUnderlyings('underlying', Symbols.underlyings()[market], symbol);

    if (update_page) {
        processMarketUnderlying();
    }
}

/*
 * Function to call when underlying has changed
 */
function processMarketUnderlying() {
    'use strict';

    var underlyingElement = document.getElementById('underlying');
    if (!underlyingElement) {
        return;
    }

    if(underlyingElement.selectedIndex < 0) {
        underlyingElement.selectedIndex = 0;
    }
    var underlying = underlyingElement.value;
    sessionStorage.setItem('underlying', underlying);

    showFormOverlay();

    // forget the old tick id i.e. close the old tick stream
    processForgetTicks();
    // get ticks for current underlying
    Tick.request(underlying);

    Tick.clean();

    updateWarmChart();

    BinarySocket.clearTimeouts();

    Contract.getContracts(underlying);

    displayTooltip(sessionStorage.getItem('market'), underlying);
}

/*
 * Function to display contract form for current underlying
 */
function processContract(contracts) {
    'use strict';
    if(contracts.hasOwnProperty('error') && contracts.error.code === 'InvalidSymbol') {
        var container = document.getElementById('contract_confirmation_container'),
            message_container = document.getElementById('confirmation_message'),
            confirmation_error = document.getElementById('confirmation_error'),
            contracts_list = document.getElementById('contracts_list');
        container.style.display = 'block';
        contracts_list.style.display = 'none';
        message_container.hide();
        confirmation_error.show();
        confirmation_error.innerHTML = contracts.error.message + ' ' + text.localize('Please reload the page') + '';
        return;
    }

    window.chartAllowed = true;
    if (contracts.contracts_for && contracts.contracts_for.feed_license && contracts.contracts_for.feed_license === 'chartonly') {
      window.chartAllowed = false;
    }

    document.getElementById('trading_socket_container').classList.add('show');
    document.getElementById('trading_init_progress').style.display = 'none';

    Contract.setContracts(contracts);

    var contract_categories = Contract.contractForms();
    var formname;
    if (sessionStorage.getItem('formname') && contract_categories[sessionStorage.getItem('formname')]) {
        formname = sessionStorage.getItem('formname');
    } else {
        var tree = getContractCategoryTree(contract_categories);
        if (tree[0]) {
            if (typeof tree[0] === 'object') {
                formname = tree[0][1][0];
            } else {
                formname = tree[0];
            }
        }
    }

    // set form to session storage
    sessionStorage.setItem('formname', formname);

    // change the form placeholder content as per current form (used for mobile menu)
    setFormPlaceholderContent(formname);

    displayContractForms('contract_form_name_nav', contract_categories, formname);

    processContractForm();

    TradingAnalysis.request();

    hideFormOverlay();
}

function processContractForm() {

    Contract.details(sessionStorage.getItem('formname'));

    StartDates.display();

    displayPrediction();

    displaySpreads();

    var r1;
    if (StartDates.displayed() && sessionStorage.getItem('date_start')) {
        r1 = TradingEvents.onStartDateChange(sessionStorage.getItem('date_start'));
        if (!r1) Durations.display();
    } else {
        Durations.display();
    }

    var expiry_type = sessionStorage.getItem('expiry_type') ? sessionStorage.getItem('expiry_type') : 'duration';
    var make_price_request = TradingEvents.onExpiryTypeChange(expiry_type);

    if (sessionStorage.getItem('amount')) $('#amount').val(sessionStorage.getItem('amount'));
    if (sessionStorage.getItem('amount_type')) selectOption(sessionStorage.getItem('amount_type'), document.getElementById('amount_type'));
    if (sessionStorage.getItem('currency')) selectOption(sessionStorage.getItem('currency'), document.getElementById('currency'));

    if (make_price_request >= 0) {
        processPriceRequest();
    }
}

function displayPrediction() {
    var predictionElement = document.getElementById('prediction_row');
    if (Contract.form() === 'digits' && sessionStorage.getItem('formname') !== 'evenodd') {
        predictionElement.show();
        if (sessionStorage.getItem('prediction')) {
            selectOption(sessionStorage.getItem('prediction'), document.getElementById('prediction'));
        }
    } else {
        predictionElement.hide();
    }
}

function displaySpreads() {
    var amountType = document.getElementById('amount_type'),
        amountPerPointLabel = document.getElementById('amount_per_point_label'),
        amount = document.getElementById('amount'),
        amountPerPoint = document.getElementById('amount_per_point'),
        spreadContainer = document.getElementById('spread_element_container'),
        stopTypeDollarLabel = document.getElementById('stop_type_dollar_label'),
        expiryTypeRow = document.getElementById('expiry_row');

    if (sessionStorage.getItem('formname') === 'spreads') {
        amountType.hide();
        amount.hide();
        expiryTypeRow.hide();
        amountPerPointLabel.show();
        amountPerPoint.show();
        spreadContainer.show();
        stopTypeDollarLabel.textContent = document.getElementById('currency').value;
    } else {
        amountPerPointLabel.hide();
        amountPerPoint.hide();
        spreadContainer.hide();
        expiryTypeRow.show();
        amountType.show();
        amount.show();
    }
    if (sessionStorage.getItem('stop_type')) {
        var el = document.querySelectorAll('input[name="stop_type"][value="' + sessionStorage.getItem('stop_type') + '"]');
        if (el) {
            console.log(el);
            el[0].setAttribute('checked', 'checked');
        }
    }
    if (sessionStorage.getItem('amount_per_point')) {
        document.getElementById('amount_per_point').value = sessionStorage.getItem('amount_per_point');
    }
    if (sessionStorage.getItem('stop_loss')) {
        document.getElementById('stop_loss').value = sessionStorage.getItem('stop_loss');
    }
    if (sessionStorage.getItem('stop_profit')) {
        document.getElementById('stop_profit').value = sessionStorage.getItem('stop_profit');
    }
}

function forgetTradingStreams() {
    processForgetProposals();
    processForgetTicks();
}
/*
 * Function to request for cancelling the current price proposal
 */
function processForgetProposals() {
    'use strict';
    showPriceOverlay();
    BinarySocket.send({
        forget_all: "proposal"
    });
    Price.clearMapping();
}

/*
 * Function to process and calculate price based on current form
 * parameters or change in form parameters
 */
function processPriceRequest() {
    'use strict';

    Price.incrFormId();
    processForgetProposals();
    showPriceOverlay();
    var types = Contract.contractType()[Contract.form()];
    if (Contract.form() === 'digits') {
        switch (sessionStorage.getItem('formname')) {
            case 'matchdiff':
                types = {
                    'DIGITMATCH': 1,
                    'DIGITDIFF': 1
                };
                break;
            case 'evenodd':
                types = {
                    'DIGITEVEN': 1,
                    'DIGITODD': 1
                };
                break;
            case 'overunder':
                types = {
                    'DIGITOVER': 1,
                    'DIGITUNDER': 1
                };
        }
    }
    for (var typeOfContract in types) {
        if (types.hasOwnProperty(typeOfContract)) {
            BinarySocket.send(Price.proposal(typeOfContract));
        }
    }
}

/*
 * Function to cancel the current tick stream
 * this need to be invoked before makin
 */
function processForgetTicks() {
    'use strict';
    BinarySocket.send({
        forget_all: 'ticks'
    });
}

/*
 * Function to process ticks stream
 */
function processTick(tick) {
    'use strict';
    var symbol = sessionStorage.getItem('underlying');
    var digit_info = TradingAnalysis.digit_info();
    if(tick.echo_req.ticks === symbol || (tick.tick && tick.tick.symbol === symbol)){
        Tick.details(tick);
        Tick.display();
        if (digit_info && tick.tick) {
            digit_info.update_chart(tick);
        }
        WSTickDisplay.updateChart(tick);
        Purchase.update_spot_list(tick);
        if (!Barriers.isBarrierUpdated()) {
            Barriers.display();
            Barriers.setBarrierUpdate(true);
        }
        updateWarmChart();
    } else {
        if(digit_info)
            digit_info.update_chart(tick);
    }
}

function processProposal(response) {
    'use strict';
    var form_id = Price.getFormId();
    if(response.echo_req.passthrough.form_id===form_id){
        hideOverlayContainer();
        Price.display(response, Contract.contractType()[Contract.form()]);
        hidePriceOverlay();
    }
}

function processTradingTimesRequest(date) {
    var trading_times = Durations.trading_times();
    if (trading_times.hasOwnProperty(date)) {
        processPriceRequest();
    } else {
        showPriceOverlay();
        BinarySocket.send({
            trading_times: date
        });
    }
}

function processTradingTimes(response) {
    Durations.processTradingTimesAnswer(response);

    processPriceRequest();
}
<commit_msg>Fix auto hiding the overlay error message<commit_after>/*
 * This function process the active symbols to get markets
 * and underlying list
 */
function processActiveSymbols(data) {
    'use strict';

    // populate the Symbols object
    Symbols.details(data);

    var market = getDefaultMarket();

    // store the market
    sessionStorage.setItem('market', market);

    displayMarkets('contract_markets', Symbols.markets(), market);
    processMarket();
    // setTimeout(function(){
    // if(document.getElementById('underlying')){
    //     Symbols.getSymbols(0);
    // }
    // }, 60*1000);
}

/*
 * Function to call when market has changed
 */
function processMarket(flag) {
    'use strict';

    // we can get market from sessionStorage as allowed market
    // is already set when this function is called
    var market = sessionStorage.getItem('market');
    var symbol = sessionStorage.getItem('underlying');
    var update_page = Symbols.need_page_update() || flag;

    if (update_page && (!symbol || !Symbols.underlyings()[market][symbol] || !Symbols.underlyings()[market][symbol].is_active)) {
        symbol = undefined;
    }
    displayUnderlyings('underlying', Symbols.underlyings()[market], symbol);

    if (update_page) {
        processMarketUnderlying();
    }
}

/*
 * Function to call when underlying has changed
 */
function processMarketUnderlying() {
    'use strict';

    var underlyingElement = document.getElementById('underlying');
    if (!underlyingElement) {
        return;
    }

    if(underlyingElement.selectedIndex < 0) {
        underlyingElement.selectedIndex = 0;
    }
    var underlying = underlyingElement.value;
    sessionStorage.setItem('underlying', underlying);

    showFormOverlay();

    // forget the old tick id i.e. close the old tick stream
    processForgetTicks();
    // get ticks for current underlying
    Tick.request(underlying);

    Tick.clean();

    updateWarmChart();

    BinarySocket.clearTimeouts();

    Contract.getContracts(underlying);

    displayTooltip(sessionStorage.getItem('market'), underlying);
}

/*
 * Function to display contract form for current underlying
 */
function processContract(contracts) {
    'use strict';
    if(contracts.hasOwnProperty('error') && contracts.error.code === 'InvalidSymbol') {
        processForgetProposals();
        var container = document.getElementById('contract_confirmation_container'),
            message_container = document.getElementById('confirmation_message'),
            confirmation_error = document.getElementById('confirmation_error'),
            contracts_list = document.getElementById('contracts_list');
        container.style.display = 'block';
        contracts_list.style.display = 'none';
        message_container.hide();
        confirmation_error.show();
        confirmation_error.innerHTML = contracts.error.message + ' ' + text.localize('Please reload the page') + '';
        return;
    }

    window.chartAllowed = true;
    if (contracts.contracts_for && contracts.contracts_for.feed_license && contracts.contracts_for.feed_license === 'chartonly') {
      window.chartAllowed = false;
    }

    document.getElementById('trading_socket_container').classList.add('show');
    document.getElementById('trading_init_progress').style.display = 'none';

    Contract.setContracts(contracts);

    var contract_categories = Contract.contractForms();
    var formname;
    if (sessionStorage.getItem('formname') && contract_categories[sessionStorage.getItem('formname')]) {
        formname = sessionStorage.getItem('formname');
    } else {
        var tree = getContractCategoryTree(contract_categories);
        if (tree[0]) {
            if (typeof tree[0] === 'object') {
                formname = tree[0][1][0];
            } else {
                formname = tree[0];
            }
        }
    }

    // set form to session storage
    sessionStorage.setItem('formname', formname);

    // change the form placeholder content as per current form (used for mobile menu)
    setFormPlaceholderContent(formname);

    displayContractForms('contract_form_name_nav', contract_categories, formname);

    processContractForm();

    TradingAnalysis.request();

    hideFormOverlay();
}

function processContractForm() {

    Contract.details(sessionStorage.getItem('formname'));

    StartDates.display();

    displayPrediction();

    displaySpreads();

    var r1;
    if (StartDates.displayed() && sessionStorage.getItem('date_start')) {
        r1 = TradingEvents.onStartDateChange(sessionStorage.getItem('date_start'));
        if (!r1) Durations.display();
    } else {
        Durations.display();
    }

    var expiry_type = sessionStorage.getItem('expiry_type') ? sessionStorage.getItem('expiry_type') : 'duration';
    var make_price_request = TradingEvents.onExpiryTypeChange(expiry_type);

    if (sessionStorage.getItem('amount')) $('#amount').val(sessionStorage.getItem('amount'));
    if (sessionStorage.getItem('amount_type')) selectOption(sessionStorage.getItem('amount_type'), document.getElementById('amount_type'));
    if (sessionStorage.getItem('currency')) selectOption(sessionStorage.getItem('currency'), document.getElementById('currency'));

    if (make_price_request >= 0) {
        processPriceRequest();
    }
}

function displayPrediction() {
    var predictionElement = document.getElementById('prediction_row');
    if (Contract.form() === 'digits' && sessionStorage.getItem('formname') !== 'evenodd') {
        predictionElement.show();
        if (sessionStorage.getItem('prediction')) {
            selectOption(sessionStorage.getItem('prediction'), document.getElementById('prediction'));
        }
    } else {
        predictionElement.hide();
    }
}

function displaySpreads() {
    var amountType = document.getElementById('amount_type'),
        amountPerPointLabel = document.getElementById('amount_per_point_label'),
        amount = document.getElementById('amount'),
        amountPerPoint = document.getElementById('amount_per_point'),
        spreadContainer = document.getElementById('spread_element_container'),
        stopTypeDollarLabel = document.getElementById('stop_type_dollar_label'),
        expiryTypeRow = document.getElementById('expiry_row');

    if (sessionStorage.getItem('formname') === 'spreads') {
        amountType.hide();
        amount.hide();
        expiryTypeRow.hide();
        amountPerPointLabel.show();
        amountPerPoint.show();
        spreadContainer.show();
        stopTypeDollarLabel.textContent = document.getElementById('currency').value;
    } else {
        amountPerPointLabel.hide();
        amountPerPoint.hide();
        spreadContainer.hide();
        expiryTypeRow.show();
        amountType.show();
        amount.show();
    }
    if (sessionStorage.getItem('stop_type')) {
        var el = document.querySelectorAll('input[name="stop_type"][value="' + sessionStorage.getItem('stop_type') + '"]');
        if (el) {
            console.log(el);
            el[0].setAttribute('checked', 'checked');
        }
    }
    if (sessionStorage.getItem('amount_per_point')) {
        document.getElementById('amount_per_point').value = sessionStorage.getItem('amount_per_point');
    }
    if (sessionStorage.getItem('stop_loss')) {
        document.getElementById('stop_loss').value = sessionStorage.getItem('stop_loss');
    }
    if (sessionStorage.getItem('stop_profit')) {
        document.getElementById('stop_profit').value = sessionStorage.getItem('stop_profit');
    }
}

function forgetTradingStreams() {
    processForgetProposals();
    processForgetTicks();
}
/*
 * Function to request for cancelling the current price proposal
 */
function processForgetProposals() {
    'use strict';
    showPriceOverlay();
    BinarySocket.send({
        forget_all: "proposal"
    });
    Price.clearMapping();
}

/*
 * Function to process and calculate price based on current form
 * parameters or change in form parameters
 */
function processPriceRequest() {
    'use strict';

    Price.incrFormId();
    processForgetProposals();
    showPriceOverlay();
    var types = Contract.contractType()[Contract.form()];
    if (Contract.form() === 'digits') {
        switch (sessionStorage.getItem('formname')) {
            case 'matchdiff':
                types = {
                    'DIGITMATCH': 1,
                    'DIGITDIFF': 1
                };
                break;
            case 'evenodd':
                types = {
                    'DIGITEVEN': 1,
                    'DIGITODD': 1
                };
                break;
            case 'overunder':
                types = {
                    'DIGITOVER': 1,
                    'DIGITUNDER': 1
                };
        }
    }
    for (var typeOfContract in types) {
        if (types.hasOwnProperty(typeOfContract)) {
            BinarySocket.send(Price.proposal(typeOfContract));
        }
    }
}

/*
 * Function to cancel the current tick stream
 * this need to be invoked before makin
 */
function processForgetTicks() {
    'use strict';
    BinarySocket.send({
        forget_all: 'ticks'
    });
}

/*
 * Function to process ticks stream
 */
function processTick(tick) {
    'use strict';
    var symbol = sessionStorage.getItem('underlying');
    var digit_info = TradingAnalysis.digit_info();
    if(tick.echo_req.ticks === symbol || (tick.tick && tick.tick.symbol === symbol)){
        Tick.details(tick);
        Tick.display();
        if (digit_info && tick.tick) {
            digit_info.update_chart(tick);
        }
        WSTickDisplay.updateChart(tick);
        Purchase.update_spot_list(tick);
        if (!Barriers.isBarrierUpdated()) {
            Barriers.display();
            Barriers.setBarrierUpdate(true);
        }
        updateWarmChart();
    } else {
        if(digit_info)
            digit_info.update_chart(tick);
    }
}

function processProposal(response) {
    'use strict';
    var form_id = Price.getFormId();
    if(response.echo_req.passthrough.form_id===form_id){
        hideOverlayContainer();
        Price.display(response, Contract.contractType()[Contract.form()]);
        hidePriceOverlay();
    }
}

function processTradingTimesRequest(date) {
    var trading_times = Durations.trading_times();
    if (trading_times.hasOwnProperty(date)) {
        processPriceRequest();
    } else {
        showPriceOverlay();
        BinarySocket.send({
            trading_times: date
        });
    }
}

function processTradingTimes(response) {
    Durations.processTradingTimesAnswer(response);

    processPriceRequest();
}
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs');
var crypto = require('crypto');

module.exports = {
  separateFilesBySize: separateFilesBySize,
  separateFilesByHeadMD5: separateFilesByHeadMD5,
  separateFilesByMD5: separateFilesByMD5
};

function separateFilesBySize(sets) {
  return separateFilesByKeyFunction(sets, keyFunctions.fileSize);
}

function separateFilesByHeadMD5(sets) {
  return separateFilesByKeyFunction(sets, keyFunctions.fileHeadMD5);
}

function separateFilesByMD5(sets) {
  return separateFilesByKeyFunction(sets, keyFunctions.fileMD5);
}

////////////////////////////////////////////////////////////////////////////////

var keyFunctions = {
  fileSize: function(file) {
    return file.size;
  },
  fileHeadMD5: function(file) {
    return crypto.createHash('md5').update(getFileHead(file)).digest('hex');
  },
  fileMD5: function(file) {
    return crypto.createHash('md5').update(fs.readFileSync(file.path)).digest('hex');
  }
}

////////////////////////////////////////////////////////////////////////////////

function getFileHead(file) {
  var headSize = Math.min(1024, file.size);
  var fd = fs.openSync(file.path, 'r');
  var buffer = new Buffer(headSize);
  fs.readSync(fd, buffer, 0, headSize, 0);
  fs.close(fd);
  return buffer.toString('base64');
}

function separateFilesByKeyFunction(sets, keyFunction) {
  var result = [];

  sets.forEach(function(set) {
    var tempObj = {};
    set.forEach(function(file) {
      var key = keyFunction(file);
      if (!(key in tempObj)) tempObj[key] = [];
      tempObj[key].push(file);
    });
    var tempArr = Object.keys(tempObj).map(function(key) { return tempObj[key]; });
    result = result.concat(tempArr);
  });

  return result;
}

<commit_msg>set head md5 to run only on big files<commit_after>"use strict";

var fs = require('fs');
var crypto = require('crypto');

module.exports = {
  separateFilesBySize: separateFilesBySize,
  separateFilesByHeadMD5: separateFilesByHeadMD5,
  separateFilesByMD5: separateFilesByMD5
};

function separateFilesBySize(sets) {
  return separateFilesByKeyFunction(sets, keyFunctions.fileSize);
}

function separateFilesByHeadMD5(sets) {
  // This step is used only on sets of big files. Currently 1M. Should be optimized.
  return separateFilesByKeyFunction(sets, keyFunctions.fileHeadMD5, function(set) { return set[0].size > 1024*1024; });
}

function separateFilesByMD5(sets) {
  return separateFilesByKeyFunction(sets, keyFunctions.fileMD5);
}

////////////////////////////////////////////////////////////////////////////////

var keyFunctions = {
  fileSize: function(file) {
    return file.size;
  },
  fileHeadMD5: function(file) {
    return crypto.createHash('md5').update(getFileHead(file)).digest('hex');
  },
  fileMD5: function(file) {
    return crypto.createHash('md5').update(fs.readFileSync(file.path)).digest('hex');
  }
}

////////////////////////////////////////////////////////////////////////////////

function getFileHead(file) {
  var headSize = Math.min(1024, file.size);
  var fd = fs.openSync(file.path, 'r');
  var buffer = new Buffer(headSize);
  fs.readSync(fd, buffer, 0, headSize, 0);
  fs.close(fd);
  return buffer.toString('base64');
}

function separateFilesByKeyFunction(sets, keyFunction, condition) {
  var result = [];

  sets.forEach(function(set) {
    if (!condition || condition(set)) {
      var tempObj = {};
      set.forEach(function(file) {
        var key = keyFunction(file);
        if (!(key in tempObj)) tempObj[key] = [];
        tempObj[key].push(file);
      });
      var tempArr = Object.keys(tempObj).map(function(key) { return tempObj[key]; });
      result = result.concat(tempArr);
    } else {
      result.push(set);
    }
  });

  return result;
}

<|endoftext|>


<commit_before>var assert = require('assert');
    proxyquire = require('proxyquire'),
    utilStub = {
        initializeModulesWithin: function() {
            return 'validators to be used';
        },
        lastStatusWasExternal: function(repoClient, sha, cb) {
            cb(true);
        }
    };

describe('github hook handler', function() {
    var validationPerformed = false,
        validatedSHA, validatedUser, validatorsUsed, validationPosted,
        githubHook = proxyquire('./../githubHook', {
            './utils/general': utilStub,
            './utils/shaValidator': {
                performCompleteValidation: function(sha, githubUser, _, validators, postStatus, cb) {
                    console.log(arguments);
                    validationPerformed = true;
                    validatedSHA = sha;
                    validatedUser = githubUser;
                    validatorsUsed = validators;
                    validationPosted = postStatus;
                    cb();
                }
            }
        }),
        mockClients = {'foo': true},
        handler = githubHook.initializer(mockClients, 'mockConfig');

    it('calls pr handler when sent a pull_request event', function() {
        var mockPayload = {
                name: 'foo',
                pull_request: {
                    action: 'closed',
                    user: {login: 'login'},
                    head: {sha: 'sha'},
                    base: {label: 'label', ref: 'master'},
                    merged: false,
                    mergeable: true,
                    mergeable_state: "clean"
                }
            },
            mockRequest = {
                body: {
                    payload: JSON.stringify(mockPayload)
                }
            },
            endCalled = false,
            mockResponse = {
                end: function() {
                    endCalled = true;
                }
            };

        validationPerformed = false;

        handler(mockRequest, mockResponse);

        assert(validationPerformed, 'validation against PR was not performed');
        assert.equal(validatedSHA, 'sha', 'validated wrong SHA');
        assert.equal(validatedUser, 'login', 'validated wrong user');
        assert.equal(validatorsUsed, 'validators to be used', 'used wrong validators');
        assert(validationPosted, 'validation status was not posted');
        assert(endCalled, 'request was not closed');

        // Reset just in case further tests use them.
        validationPerformed = undefined;
        validatedSHA = undefined;
        validatedUser = undefined;
        validatorsUsed = undefined;
        validationPosted = undefined;
    });

    // it('calls push handler when sent a push event', function() {});

    // it('calls status handler when sent a status event', function() {});
});<commit_msg>Add a test for non-mergeable PR<commit_after>var assert = require('assert');
    proxyquire = require('proxyquire'),
    utilStub = {
        initializeModulesWithin: function() {
            return 'validators to be used';
        },
        lastStatusWasExternal: function(repoClient, sha, cb) {
            cb(true);
        }
    };

describe('github hook handler', function() {
    var validationPerformed = false,
        validatedSHA, validatedUser, validatorsUsed, validationPosted,
        githubHook = proxyquire('./../githubHook', {
            './utils/general': utilStub,
            './utils/shaValidator': {
                performCompleteValidation: function(sha, githubUser, _, validators, postStatus, cb) {
                    console.log(arguments);
                    validationPerformed = true;
                    validatedSHA = sha;
                    validatedUser = githubUser;
                    validatorsUsed = validators;
                    validationPosted = postStatus;
                    cb();
                }
            }
        }),
        mockClients = {'foo': true},
        handler = githubHook.initializer(mockClients, 'mockConfig');

    it('calls pr handler when sent a mergeable pull_request event', function() {
        var mockPayload = {
                name: 'foo',
                pull_request: {
                    action: 'closed',
                    user: {login: 'login'},
                    head: {sha: 'sha'},
                    base: {label: 'label', ref: 'master'},
                    // a travis passing and mergeable PR:
                    merged: false,
                    mergeable: true,
                    mergeable_state: "clean"
                }
            },
            mockRequest = {
                body: {
                    payload: JSON.stringify(mockPayload)
                }
            },
            endCalled = false,
            mockResponse = {
                end: function() {
                    endCalled = true;
                }
            };

        validationPerformed = false;

        handler(mockRequest, mockResponse);

        assert(validationPerformed, 'validation against PR was not performed');
        assert.equal(validatedSHA, 'sha', 'validated wrong SHA');
        assert.equal(validatedUser, 'login', 'validated wrong user');
        assert.equal(validatorsUsed, 'validators to be used', 'used wrong validators');
        assert(validationPosted, 'validation status was not posted');
        assert(endCalled, 'request was not closed');

        // Reset just in case further tests use them.
        validationPerformed = undefined;
        validatedSHA = undefined;
        validatedUser = undefined;
        validatorsUsed = undefined;
        validationPosted = undefined;
    });

    it('do not calls pr handler when sent a non-mergeable pull_request event', function() {
        var mockPayload = {
                name: 'foo',
                pull_request: {
                    action: 'closed',
                    user: {login: 'login'},
                    head: {sha: 'sha'},
                    base: {label: 'label', ref: 'master'},
                    // a non-mergeable PR
                    merged: false,
                    mergeable: false,
                    mergeable_state: "dirty"
                }
            },
            mockRequest = {
                body: {
                    payload: JSON.stringify(mockPayload)
                }
            },
            endCalled = false,
            mockResponse = {
                end: function() {
                    endCalled = true;
                }
            };

        validationPerformed = false;

        handler(mockRequest, mockResponse);

        assert(!validationPerformed, 'validation against PR should not be performed');
        // TODO post a status instead of not posting
        assert(!validationPosted, 'validation status should not be posted');
        assert(endCalled, 'request was not closed');

        // Reset just in case further tests use them.
        validationPerformed = undefined;
        validatedSHA = undefined;
        validatedUser = undefined;
        validatorsUsed = undefined;
        validationPosted = undefined;
    });

    // it('calls push handler when sent a push event', function() {});

    // it('calls status handler when sent a status event', function() {});
});<|endoftext|>


<commit_before>/*
 * NATSboard
 * Copyright (c) 2015 Fatih Cetinkaya (http://github.com/cmfatih/natsboard)
 * For the full copyright and license information, please view the LICENSE.txt file.
 */

/* jslint node: true */
'use strict';

var util    = require('util'),
    express = require('express'),
    Client  = require('./client');

module.exports = function(app) {

  if(!app || typeof app.get !== 'function') {
    throw new Error('invalid app instance');
  }

  var NATS_URL      = app.get('NATS_URL'),
      router        = express.Router(),
      client        = new Client(),
      serverMetrics = {
        varz: {
          connections:    [],
          mem:            [],
          cpu:            [],
          in_msgs:        [],
          out_msgs:       [],
          in_bytes:       [],
          out_bytes:      [],
          slow_consumers: []
        }
      },
      metricRates = {
        varz: {
          in_msgs:   [],
          out_msgs:  [],
          in_bytes:  [],
          out_bytes: []
        }
      };

  // Disable client caching
  client.caching(false);

  // Gets metrics
  var getMetrics = function getMetrics() {
    return serverMetrics;
  };

  // Gets rates
  var getRates = function getRates() {
    return metricRates;
  };

  // Processes data
  var processData = function processData(url, cb) {

    if(typeof cb !== 'function') {
      throw new Error('invalid callback function');
    }
    else if(typeof url !== 'string') {
      return cb(new Error('invalid url'));
    }

    // Fetch all data
    client.fetchDataAll(url, function(err, result) {
      if(err) {
        return cb(err);
      }

      // Iterate metrics
      Object.keys(serverMetrics).forEach(function(type) {
        if(result[type]) {
          Object.keys(serverMetrics[type]).forEach(function(metric) {
            if(typeof result[type][metric] !== 'undefined') {

              // Calculate rate
              if(metricRates[type] && typeof metricRates[type][metric] !== 'undefined') {
                var metricLen = serverMetrics[type][metric].length;
                if(metricLen) {
                  var metricLast = serverMetrics[type][metric][serverMetrics[type][metric].length-1] || 0,
                      metricCur  = result[type][metric] || 0;

                  // TODO: There is no guarantee that metrics will be per second with this code
                  //       so add timestamp to metrics and calculate base on it.
                  var metricRate = metricCur-metricLast;

                  // Add rate
                  metricRates[type][metric].push(metricRate);
                  // If length is greater then limit
                  if(metricRates[type][metric].length > 5) {
                    metricRates[type][metric].shift(); // remove first element
                  }
                }
              }

              // Add metric
              serverMetrics[type][metric].push(result[type][metric]);
              // If length is greater then limit
              if(serverMetrics[type][metric].length > 5) {
                serverMetrics[type][metric].shift(); // remove first element
              }
            }
          });
        }
      });

      return cb();
    });
  };

  // Fetches data periodically
  var fetcher = function fetcher(url) {
    var running = false;
    setInterval(function() {
      if(!running) {
        running = true;
        processData(url, function(err) {
          if(err) {
            console.error(err);
          }
          running = false;
        });
      }
    }, 1000);
  };

  // Start fetcher
  fetcher(NATS_URL);
  console.log(util.format('Fetching data from %s', NATS_URL));

  // Handles metrics route
  router.get('/metrics/metrics', function(req, res) {
    return res.json(getMetrics());
  });

  // Handles metrics route
  router.get('/metrics/rates', function(req, res) {
    return res.json(getRates());
  });

  // Return
  return {
    fetcher:    fetcher,
    getMetrics: getMetrics,
    getRates:   getRates,
    router:     router
  };
};<commit_msg>Add pusher<commit_after>/*
 * NATSboard
 * Copyright (c) 2015 Fatih Cetinkaya (http://github.com/cmfatih/natsboard)
 * For the full copyright and license information, please view the LICENSE.txt file.
 */

/* jslint node: true */
'use strict';

var util    = require('util'),
    express = require('express'),
    Client  = require('./client');

module.exports = function(app) {

  if(!app || typeof app.get !== 'function') {
    throw new Error('invalid app instance');
  }

  var NATS_URL      = app.get('NATS_URL'),
      WS            = app.get('WS'),
      router        = express.Router(),
      client        = new Client(),
      serverMetrics = {
        varz: {
          connections:    [],
          mem:            [],
          cpu:            [],
          slow_consumers: [],
          in_msgs:        [],
          out_msgs:       [],
          in_bytes:       [],
          out_bytes:      []
        }
      },
      metricRates = {
        varz: {
          connections:    [],
          mem:            [],
          cpu:            [],
          slow_consumers: [],
          in_msgs:        [],
          out_msgs:       [],
          in_bytes:       [],
          out_bytes:      []
        }
      };

  // Disable client caching
  client.caching(false);

  // Gets metrics
  var getMetrics = function getMetrics() {
    return serverMetrics;
  };

  // Gets rates
  var getRates = function getRates() {
    return metricRates;
  };

  // Processes data
  var processData = function processData(url, cb) {

    if(typeof cb !== 'function') {
      throw new Error('invalid callback function');
    }
    else if(typeof url !== 'string') {
      return cb(new Error('invalid url'));
    }

    // Fetch all data
    client.fetchDataAll(url, function(err, result) {
      if(err) {
        return cb(err);
      }

      // Iterate metrics
      Object.keys(serverMetrics).forEach(function(type) {
        if(result[type]) {
          Object.keys(serverMetrics[type]).forEach(function(metric) {
            if(typeof result[type][metric] !== 'undefined') {

              // Calculate rate
              if(metricRates[type] && typeof metricRates[type][metric] !== 'undefined') {
                var metricRate = result[type][metric] || 0,
                    metricLen  = serverMetrics[type][metric].length;

                // If there is a metric then
                if(metricLen) {
                  if(['in_msgs', 'out_msgs', 'in_bytes', 'out_bytes'].indexOf(metric) !== -1) {
                    // TODO: There is no guarantee that metrics will be per second with this code
                    //       so add timestamp to metrics and calculate base on it.
                    var metricLast = serverMetrics[type][metric][serverMetrics[type][metric].length-1] || 0;
                    metricRate = metricRate-metricLast;
                  }
                }

                // Add rate
                metricRates[type][metric].push(metricRate);
                // If length is greater then limit
                if(metricRates[type][metric].length > 5) {
                  metricRates[type][metric].shift(); // remove first element
                }
              }

              // Add metric
              serverMetrics[type][metric].push(result[type][metric]);
              // If length is greater then limit
              if(serverMetrics[type][metric].length > 5) {
                serverMetrics[type][metric].shift(); // remove first element
              }
            }
          });
        }
      });

      return cb();
    });
  };

  // Fetches data periodically
  var fetcher = function fetcher(url) {
    var running = false;
    setInterval(function() {
      if(!running) {
        running = true;
        processData(url, function(err) {
          if(err) {
            console.error(err);
          }
          running = false;
        });
      }
    }, 1000);
  };

  // Pushes data periodically
  var pusher = function pusher() {
    var running = false;
    setInterval(function() {
      if(!running) {
        running = true;
        // Send data
        WS.connections.forEach(function(client) {
          client.sendText(JSON.stringify({
            timestamp: new Date().getTime(),
            rates:     getRates()
          }));
        });
        running = false;
      }
    }, 1000);
  };

  // Start fetcher
  fetcher(NATS_URL);
  console.log(util.format('Fetching data from %s', NATS_URL));

  // Start pusher
  pusher();
  console.log('Pushing data to websocket connections...');

  // Handles metrics route
  router.get('/metrics/metrics', function(req, res) {
    return res.json(getMetrics());
  });

  // Handles metrics route
  router.get('/metrics/rates', function(req, res) {
    return res.json(getRates());
  });

  // Return
  return {
    fetcher:    fetcher,
    getMetrics: getMetrics,
    getRates:   getRates,
    router:     router
  };
};<|endoftext|>


<commit_before>function sendUndoEvent(action_id) {
	socket.emit('undo',
		{
			'data': {
				'action_id': action_id,
				'board_id': whiteboard_id
			}
		}
	);
	paint_blobs_undone[action_id] = action_id;
}

function sendPaintEvent(tool_name, action_data) {
	// console.log('sendPaintEvent', tool_name, the_points);
	var action_id = Math.random();
	socket.emit('paint',
		{
			'data': {
				'action_id': action_id,
				'tool': tool_name,
				'data': action_data,
				'board_id': whiteboard_id
			}
		}
	);
	paint_blobs_mine.push(action_id);
	drawCommand(tool_name, action_data);
}

function modalClose(extra_thing) {
	toolbarActivate('#toolbar_normal');
	$('#modal_pane').hide();
	$(extra_thing).hide();
}

function modalOpen(extra_thing) {
	toolbarActivate('#toolbar_confirmcancel');
	$('#modal_pane').show();
	$(extra_thing).show();
}

// Perform events

function eventToolDown(n, p) {
	tool_heads[n] = active_tool.makeToolHead();
	if (tool_heads[n]) {
		tool_heads[n].onMove(p);
	}
}

function eventToolMove(n, p) {
	if (tool_heads[n]) {
		tool_heads[n].onMove(p);
	}
}

function eventToolUp(n) {
	if (tool_heads[n]) {
		tool_heads[n].onRelease();
		tool_heads[n] = null;
	}
}

// Interperet events

function mouseDown(e) {
	eventToolDown(0, new Point(e.pageX, e.pageY));
	e.preventDefault();
}

function mouseMove(e) {
	eventToolMove(0, new Point(e.pageX, e.pageY));
	// e.preventDefault();
}

function mouseUp(e) {
	eventToolUp(0);
	// e.preventDefault();
}

function touchDown(e) {
	mouseDown(e.touches[0]);
	e.preventDefault();
}

function touchMove(e) {
	mouseMove(e.touches[0]);
	e.preventDefault();
}

function drawCommand(the_tool, the_data) {
	if (the_tool in tools) {
		tools[the_tool].drawFull(the_data);
	}
}

function modalInputConfirm() {
	for (i in tool_heads) {
		if (tool_heads[i] != null) {
			tool_heads[i].onModalConfirm();
		}
	}
}

function modalInputCancel() {
	for (i in tool_heads) {
		if (tool_heads[i] != null) {
			tool_heads[i].onModalCancel();
		}
	}
}

function modalKeyHandle(event) {
	if (event.keyCode == 13 && !event.shiftKey) modalInputConfirm();
	if (event.keyCode == 27) modalInputCancel();
}

$('#modal_pane').mousedown(mouseMove);
$('#button_cancel').mousedown(modalInputCancel);
$('#button_confirm').mousedown(modalInputConfirm);
$('#modal_pane').keydown(modalKeyHandle);
// $('#modal_pane').mousemove(mouseMove);
$('#canvas2').mousedown(mouseDown);
$('#canvas2').mousemove(mouseMove);
$('#canvas2').mouseup(mouseUp);
// document.addEventListener('touchstart', touchDown, false);
// document.addEventListener('touchmove', touchMove, false);
// document.addEventListener('touchend', mouseUp, false);
// document.addEventListener('touchcancel', mouseUp, false);
document.getElementById('canvas2').addEventListener('touchstart', touchDown, false);
document.getElementById('canvas2').addEventListener('touchmove', touchMove, false);
document.getElementById('canvas2').addEventListener('touchend', mouseUp, false);
document.getElementById('canvas2').addEventListener('touchcancel', mouseUp, false);

// Tool buttons

function triggerToolButton(t, dbl) {
	console.log('Tool:', t);
	// Tigger the click event
	var click_result = false;
	if (dbl) {
		click_result = tools[t].onDoubleClick();
	} else {
		click_result = tools[t].onButtonClick();
	}
	var p = tools[t].buttonImageSelected;
	if (click_result === true) {
		// Button was selected. This is good.
		active_tool = tools[t];
		// Change button images
		for (i in tools) {
			var n2 = tools[i].name;
			var p2 = tools[i].buttonImage;
			document.getElementById('button_' + n2).src = '/static/images/' + p2;
		}
		document.getElementById('button_' + t).src = '/static/images/' + p;
	} else if (click_result === false) {
		// The button did an action, we don't need to do anything.
	} else {
		// The button produced a toolhead.
		// Probably means the modal pane was opened, for clear confirmation or something.
		tool_heads[0] = click_result;
	}
}

$(document).ready( function() {
	for (i in tools) {
		// Clojures because javascript is strange...
		// console.log(i, 'is a tool');
		function clojure() {
			var name = tools[i].name;
			var desktop_only = tools[i]['desktopOnly'];
			if (desktop_only === true && /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
				// disable the stuff
				console.log('Disabling tool', i);
				$('#button_' + name).hide();
				$('#button_' + name).next().hide();
			} else {
				$('#button_' + name).click(function(e) {triggerToolButton(name, false);});
				$('#button_' + name).dblclick(function(e) {triggerToolButton(name, true);})
			}
		}
		clojure();
	}
});

// Colours

var colours = {
	black: '#444444',
	blue: '#484fc0',
	red: '#df4b26'
};

global_colour = colours['black'];

function triggerColourButton(col) {
	console.log('Colour: ', col, colours[col]);
	global_colour = colours[col];
	for (i in colours) {
		$("#colour_" + i).attr('src', '/static/images/col_' + i + '.png');
	}
	$('#colour_' + col).attr('src', '/static/images/col_s_' + col + '.png');
	if (active_tool.name == 'eraser') {
		triggerToolButton('pencil');
	}
}

$(document).ready( function() {
	for (i in colours) {
		// console.log(i, 'is a colour');
		function clojure() {
			var x = i;
			$('#colour_' + x).click(function(e) {triggerColourButton(x);});
		}
		clojure();
	}
});

// Toolbars

function toolbarActivate(to_activate) {
	var toolbars = ['#toolbar_normal', '#toolbar_confirmcancel'];
	for (i in toolbars) {
		$(toolbars[i]).css('display', 'none');
	}
	$(to_activate).css('display', 'block');
}

toolbarActivate('#toolbar_normal');

function drawEverything() {
	console.log('Drawing everything!');
	drawClear(context_picture);
	for (i in paint_blobs_all) {
		if (! (paint_blobs_all[i]['action_id'] in paint_blobs_undone)) {
			drawCommand(paint_blobs_all[i].tool, paint_blobs_all[i].data);
		}
	}
}

// Data transfer

$(document).ready(function() {

	triggerToolButton('pencil');
	triggerColourButton('blue');

	console.log('Board ID:', whiteboard_id);

	socket = io.connect('http://' + document.domain + ':' + location.port + '/');

	socket.on('paint', function(msg) {
		// console.log('paint', msg);
		if (msg.data.board_id == whiteboard_id) {
			actions = msg.data.actions;
			for (i in actions) {
				// console.log(actions[i].tool, actions[i].points);
				drawCommand(actions[i].tool, actions[i].data);
				paint_blobs_all.push(actions[i]);
			}
		}
	});

	socket.on('undo', function(msg) {
		if (msg.data.board_id == whiteboard_id) {
			aid = msg.data.action_id;
			console.log('Received Undo', aid);
			paint_blobs_undone[aid] = aid;
			drawEverything();
		}
	});

	socket.emit('full image', {data:{'board_id': whiteboard_id}})

	// window.setTimeout(
	// 	function() {socket.emit('full image', {data:{'board_id': whiteboard_id}});},
	// 	10
	// );

});

$(window).on('beforeunload', function(){
	socket.close();
});<commit_msg>Confirm and cancel buttons trigger on release<commit_after>function sendUndoEvent(action_id) {
	socket.emit('undo',
		{
			'data': {
				'action_id': action_id,
				'board_id': whiteboard_id
			}
		}
	);
	paint_blobs_undone[action_id] = action_id;
}

function sendPaintEvent(tool_name, action_data) {
	// console.log('sendPaintEvent', tool_name, the_points);
	var action_id = Math.random();
	socket.emit('paint',
		{
			'data': {
				'action_id': action_id,
				'tool': tool_name,
				'data': action_data,
				'board_id': whiteboard_id
			}
		}
	);
	paint_blobs_mine.push(action_id);
	drawCommand(tool_name, action_data);
}

function modalClose(extra_thing) {
	toolbarActivate('#toolbar_normal');
	$('#modal_pane').hide();
	$(extra_thing).hide();
}

function modalOpen(extra_thing) {
	toolbarActivate('#toolbar_confirmcancel');
	$('#modal_pane').show();
	$(extra_thing).show();
}

// Perform events

function eventToolDown(n, p) {
	tool_heads[n] = active_tool.makeToolHead();
	if (tool_heads[n]) {
		tool_heads[n].onMove(p);
	}
}

function eventToolMove(n, p) {
	if (tool_heads[n]) {
		tool_heads[n].onMove(p);
	}
}

function eventToolUp(n) {
	if (tool_heads[n]) {
		tool_heads[n].onRelease();
		tool_heads[n] = null;
	}
}

// Interperet events

function mouseDown(e) {
	eventToolDown(0, new Point(e.pageX, e.pageY));
	e.preventDefault();
}

function mouseMove(e) {
	eventToolMove(0, new Point(e.pageX, e.pageY));
	// e.preventDefault();
}

function mouseUp(e) {
	eventToolUp(0);
	// e.preventDefault();
}

function touchDown(e) {
	mouseDown(e.touches[0]);
	e.preventDefault();
}

function touchMove(e) {
	mouseMove(e.touches[0]);
	e.preventDefault();
}

function drawCommand(the_tool, the_data) {
	if (the_tool in tools) {
		tools[the_tool].drawFull(the_data);
	}
}

function modalInputConfirm() {
	for (i in tool_heads) {
		if (tool_heads[i] != null) {
			tool_heads[i].onModalConfirm();
		}
	}
}

function modalInputCancel() {
	for (i in tool_heads) {
		if (tool_heads[i] != null) {
			tool_heads[i].onModalCancel();
		}
	}
}

function modalKeyHandle(event) {
	if (event.keyCode == 13 && !event.shiftKey) modalInputConfirm();
	if (event.keyCode == 27) modalInputCancel();
}

$('#modal_pane').mousedown(mouseMove);
$('#button_cancel').click(modalInputCancel);
$('#button_confirm').click(modalInputConfirm);
$('#modal_pane').keydown(modalKeyHandle);
// $('#modal_pane').mousemove(mouseMove);
$('#canvas2').mousedown(mouseDown);
$('#canvas2').mousemove(mouseMove);
$('#canvas2').mouseup(mouseUp);
// document.addEventListener('touchstart', touchDown, false);
// document.addEventListener('touchmove', touchMove, false);
// document.addEventListener('touchend', mouseUp, false);
// document.addEventListener('touchcancel', mouseUp, false);
document.getElementById('canvas2').addEventListener('touchstart', touchDown, false);
document.getElementById('canvas2').addEventListener('touchmove', touchMove, false);
document.getElementById('canvas2').addEventListener('touchend', mouseUp, false);
document.getElementById('canvas2').addEventListener('touchcancel', mouseUp, false);

// Tool buttons

function triggerToolButton(t, dbl) {
	console.log('Tool:', t);
	// Tigger the click event
	var click_result = false;
	if (dbl) {
		click_result = tools[t].onDoubleClick();
	} else {
		click_result = tools[t].onButtonClick();
	}
	var p = tools[t].buttonImageSelected;
	if (click_result === true) {
		// Button was selected. This is good.
		active_tool = tools[t];
		// Change button images
		for (i in tools) {
			var n2 = tools[i].name;
			var p2 = tools[i].buttonImage;
			document.getElementById('button_' + n2).src = '/static/images/' + p2;
		}
		document.getElementById('button_' + t).src = '/static/images/' + p;
	} else if (click_result === false) {
		// The button did an action, we don't need to do anything.
	} else {
		// The button produced a toolhead.
		// Probably means the modal pane was opened, for clear confirmation or something.
		tool_heads[0] = click_result;
	}
}

$(document).ready( function() {
	for (i in tools) {
		// Clojures because javascript is strange...
		// console.log(i, 'is a tool');
		function clojure() {
			var name = tools[i].name;
			var desktop_only = tools[i]['desktopOnly'];
			if (desktop_only === true && /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
				// disable the stuff
				console.log('Disabling tool', i);
				$('#button_' + name).hide();
				$('#button_' + name).next().hide();
			} else {
				$('#button_' + name).click(function(e) {triggerToolButton(name, false);});
				$('#button_' + name).dblclick(function(e) {triggerToolButton(name, true);})
			}
		}
		clojure();
	}
});

// Colours

var colours = {
	black: '#444444',
	blue: '#484fc0',
	red: '#df4b26'
};

global_colour = colours['black'];

function triggerColourButton(col) {
	console.log('Colour: ', col, colours[col]);
	global_colour = colours[col];
	for (i in colours) {
		$("#colour_" + i).attr('src', '/static/images/col_' + i + '.png');
	}
	$('#colour_' + col).attr('src', '/static/images/col_s_' + col + '.png');
	if (active_tool.name == 'eraser') {
		triggerToolButton('pencil');
	}
}

$(document).ready( function() {
	for (i in colours) {
		// console.log(i, 'is a colour');
		function clojure() {
			var x = i;
			$('#colour_' + x).click(function(e) {triggerColourButton(x);});
		}
		clojure();
	}
});

// Toolbars

function toolbarActivate(to_activate) {
	var toolbars = ['#toolbar_normal', '#toolbar_confirmcancel'];
	for (i in toolbars) {
		$(toolbars[i]).css('display', 'none');
	}
	$(to_activate).css('display', 'block');
}

toolbarActivate('#toolbar_normal');

function drawEverything() {
	console.log('Drawing everything!');
	drawClear(context_picture);
	for (i in paint_blobs_all) {
		if (! (paint_blobs_all[i]['action_id'] in paint_blobs_undone)) {
			drawCommand(paint_blobs_all[i].tool, paint_blobs_all[i].data);
		}
	}
}

// Data transfer

$(document).ready(function() {

	triggerToolButton('pencil');
	triggerColourButton('blue');

	console.log('Board ID:', whiteboard_id);

	socket = io.connect('http://' + document.domain + ':' + location.port + '/');

	socket.on('paint', function(msg) {
		// console.log('paint', msg);
		if (msg.data.board_id == whiteboard_id) {
			actions = msg.data.actions;
			for (i in actions) {
				// console.log(actions[i].tool, actions[i].points);
				drawCommand(actions[i].tool, actions[i].data);
				paint_blobs_all.push(actions[i]);
			}
		}
	});

	socket.on('undo', function(msg) {
		if (msg.data.board_id == whiteboard_id) {
			aid = msg.data.action_id;
			console.log('Received Undo', aid);
			paint_blobs_undone[aid] = aid;
			drawEverything();
		}
	});

	socket.emit('full image', {data:{'board_id': whiteboard_id}})

	// window.setTimeout(
	// 	function() {socket.emit('full image', {data:{'board_id': whiteboard_id}});},
	// 	10
	// );

});

$(window).on('beforeunload', function(){
	socket.close();
});<|endoftext|>


<commit_before>'use strict';

/**
 * Test content
 * @type {{file: string, sha1: string}}
 */
module.exports = {
  file: __dirname + '/../assets/test.txt',
  filename: 'test.txt',
  data: 'The fox is brown',
  type: 'text/plain',
  ext: 'txt',
  sha1: 'a03f181dc7dedcfb577511149b8844711efdb04f',
  sha1Bogus: 'a03f181dc7dedcfb577511149b8844711efdb04e',
  relativePath:
    '/a0/3f/18/1d/c7/de/dc/fb/57/75/11/14/9b/88/44/71/1e/fd/b0/4f.txt'
}
<commit_msg>Add sha256 for testing<commit_after>'use strict';

/**
 * Test content
 * @type {{file: string, sha1: string}}
 */
module.exports = {
  file: __dirname + '/../assets/test.txt',
  filename: 'test.txt',
  data: 'The fox is brown',
  type: 'text/plain',
  ext: 'txt',
  sha1: 'a03f181dc7dedcfb577511149b8844711efdb04f',
  sha256: 'c11e154a748960b1777bdf3932cca9b0c8611f077ac3298c51696325c6b649ee',
  sha1Bogus: 'a03f181dc7dedcfb577511149b8844711efdb04e',
  sha256Bogus: 'c11e154a748960b1777bdf3932cca9b0c8611f077ac3298c51696325c6b649ef',
  relativePath:
    '/a0/3f/18/1d/c7/de/dc/fb/57/75/11/14/9b/88/44/71/1e/fd/b0/4f.txt'
}
<|endoftext|>