<commit_before>/// <reference path="../chance.js" />
/// <reference path="../node_modules/underscore/underscore-min.js" />

var expect = chai.expect;

describe("Person", function () {
    var name, first, last, prefix, suffix, ssn, chance = new Chance();

    describe("age()", function () {
        it("returns a random age within expected bounds", function () {
            _(1000).times(function () {
                expect(chance.age()).to.be.a('number');
                expect(chance.age()).to.be.within(1, 100);
            });
        });

        describe("ranges", function() {
            var age;

            it("child", function () {
                _(1000).times(function () {
                    age = chance.age({ type: 'child' });
                    expect(age).to.be.a('number');
                    expect(age).to.be.within(1, 12);
                });
            });

            it("teen", function () {
                _(1000).times(function () {
                    age = chance.age({ type: 'teen' });
                    expect(age).to.be.a('number');
                    expect(age).to.be.within(13, 19);
                });
            });

            it("adult", function () {
                _(1000).times(function () {
                    age = chance.age({ type: 'adult' });
                    expect(age).to.be.a('number');
                    expect(age).to.be.within(18, 65);
                });
            });

            it("senior", function () {
                _(1000).times(function () {
                    age = chance.age({ type: 'senior' });
                    expect(age).to.be.a('number');
                    expect(age).to.be.within(65, 100);
                });
            });
        });

        it("can have the type specified", function () {
            _(1000).times(function () {
                expect(chance.age({type: 'child'})).to.be.within(1, 13);
                expect(chance.age({type: 'senior'})).to.be.within(65, 120);
            });
        });
    });

    describe("birthday()", function () {
        it("returns a random birthday", function () {
            _(1000).times(function () {
                expect(chance.birthday()).to.be.a('Date');
                expect(chance.birthday().getFullYear()).to.be.within((new Date().getFullYear() - 120), (new Date().getFullYear()));
            });
        });

        it("can have a string returned", function () {
            _(1000).times(function () {
                expect(chance.birthday({string: true})).to.be.a('string');
                expect(chance.birthday({string: true})).to.match(/^[0-9][0-9]?\/[0-9][0-9]?\/[0-9]{4}/m);
            });
        });

        it("can have a year specified", function () {
            _(1000).times(function () {
                expect(chance.birthday({year: 1983}).getFullYear()).to.equal(1983);
            });
        });

        it("can have an age range specified", function () {
            _(1000).times(function () {
                expect(chance.birthday({type: 'child'}).getFullYear()).to.be.within((new Date().getFullYear() - 13), (new Date().getFullYear()));
            });
        });
    });

    describe("gender()", function () {
        it("returns a random gender", function () {
            _(1000).times(function () {
                expect(chance.gender()).to.be.match(/(Male|Female)/);
            });
        });
    });

    describe("name()", function () {
        it("returns a random name", function () {
            _(1000).times(function () {
                name = chance.name();
                expect(name).to.be.a('string');
                expect(name).to.have.length.within(2, 30);
                expect(name.split(' ')).to.have.length(2);
            });
        });

        it("can have the middle name specified", function () {
            _(1000).times(function () {
                name = chance.name({middle: true});
                expect(name).to.be.a('string');
                expect(name.split(' ')).to.have.length(3);
            });
        });

        it("can have the middle initial specified", function () {
            _(1000).times(function () {
                name = chance.name({middle_initial: true});
                expect(name).to.be.a('string');
                expect(name.split(' ')).to.have.length(3);
                expect(name.split(' ')[1]).to.match(/[A-Z]\./);
                expect(name.indexOf('.')).to.be.ok;
            });
        });

        it("can have the prefix specified", function () {
            _(1000).times(function () {
                name = chance.name({prefix: true});
                expect(name).to.be.a('string');
                expect(name.split(' ')).to.have.length(3);
            });
        });

        it("can have the suffix specified", function () {
            _(1000).times(function () {
                name = chance.name({suffix: true});
                expect(name).to.be.a('string');
                expect(name.split(' ')).to.have.length(3);
            });
        });
    });

    describe("first()", function () {
        it("returns a random first name", function () {
            _(1000).times(function () {
                first = chance.first();
                expect(first).to.be.a('string');
                expect(first).to.have.length.within(2, 20);
                expect(first.split(' ')).to.have.length(1);
            });
        });
    });

    describe("last()", function () {
        it("returns a random last name", function () {
            _(1000).times(function () {
                last = chance.last();
                expect(last).to.be.a('string');
                expect(last).to.have.length.within(2, 20);
                expect(last.split(' ')).to.have.length(1);
            });
        });

    });

    describe("name_prefix()", function () {
        it("returns a random prefix", function () {
            _(1000).times(function () {
                prefix = chance.name_prefix();
                expect(prefix).to.be.a('string');
                expect(prefix).to.have.length.below(5);
            });
        });

        it("returns a correctly gendered prefix", function () {
            _(1000).times(function () {
                prefix = chance.name_prefix({ gender: "female" });
                expect(prefix).to.not.equal("Mr.");
                prefix = chance.name_prefix({ gender: "male" });
                expect(prefix).to.not.equal("Mrs.");
                expect(prefix).to.not.equal("Miss");
            });
        });

        it("can get full prefix", function () {
            _(1000).times(function () {
                prefix = chance.name_prefix({full: true});
                expect(prefix).to.be.a('string');
                expect(prefix).to.have.length.above(3);
            });
        });
    });

    describe("name_suffix()", function () {
        it("returns a random suffix", function () {
            _(1000).times(function () {
                suffix = chance.name_suffix();
                expect(suffix).to.be.a('string');
                expect(suffix).to.have.length.below(7);
            });
        });

        it("can get full suffix", function () {
            _(1000).times(function () {
                suffix = chance.name_suffix({full: true});
                expect(suffix).to.be.a('string');
                expect(suffix).to.have.length.above(5);
            });
        });
    });

    describe("suffix()", function () {
        it("returns a random suffix", function () {
            _(1000).times(function () {
                suffix = chance.suffix();
                expect(suffix).to.be.a('string');
                expect(suffix).to.have.length.below(7);
            });
        });

        it("can get full suffix", function () {
            _(1000).times(function () {
                suffix = chance.suffix({full: true});
                expect(suffix).to.be.a('string');
                expect(suffix).to.have.length.above(5);
            });
        });
    });

    describe("ssn()", function () {
        it("returns a random socal security number", function () {
            _(1000).times(function () {
                ssn = chance.ssn();
                expect(ssn).to.be.a('string');
                expect(ssn).to.match(/^\d{3}-\d{2}-\d{4}$/m);
                expect(ssn).to.have.length(11);
            });
        });

        it("can get just last 4", function () {
            _(1000).times(function () {
                ssn = chance.ssn({ ssnFour: true });
                expect(ssn).to.be.a('string');
                expect(ssn).to.match(/^\d{4}$/m);
                expect(ssn).to.have.length(4);
            });
        });
    });

    describe("cpf()", function () {
        var cpf;
        it("returns a random valid taxpayer number for Brazil citizens (CPF)", function () {
            _(1000).times(function () {
                cpf = chance.cpf();
                expect(cpf).to.be.a('string');
                expect(cpf).to.match(/^\d{3}.\d{3}.\d{3}-\d{2}$/m);
                expect(cpf).to.have.length(14);
            });
        });
    });

    describe("israelId()",function(){
        it("Should return a valid israel ID",function(){
            var x=chance.israelId();
            expect(x).to.have.length(9);
            var y=0;
            for (var i=0;i<8;i++){
                    var thisDigit=  x[i] *  (i/2===parseInt(i/2) ? 1 : 2);
                    thisDigit=chance.pad(thisDigit,2).toString();
                    thisDigit=parseInt(thisDigit[0]) + parseInt(thisDigit[1]);
                    y=y+thisDigit;
                    }
            var lastDigit=10-parseInt(y.toString().slice(-1)).toString().slice(-1);
            expect(x[8]).to.equal(lastDigit.toString());
        });
    });

    describe('mrz()', function() {
        it('should return a valid passport number when given valid inputs', function() {
            var sample = "P<GBRFOLKS<<JOANNE<<<<<<<<<<<<<<<<<<<<<<<<<<2321126135GBR6902069F1601013<<<<<<<<<<<<<<02",
                actual = chance.mrz({
                    first: 'Joanne',
                    last: 'Folks',
                    gender: 'F',
                    dob: '690206',
                    expiry: '160101',
                    passportNumber: '232112613',
                });

            expect(actual).to.equal(sample);

            sample = "P<GBRKELLY<<LIDA<<<<<<<<<<<<<<<<<<<<<<<<<<<<3071365913GBR6606068F2003131<<<<<<<<<<<<<<04";
            actual = chance.mrz({
                first: 'Lida',
                last: 'Kelly',
                gender: 'F',
                dob: '660606',
                expiry: '200313',
                passportNumber: '307136591',
            });

            expect(actual).to.equal(sample);
        });
        it('should return a valid random passport number when not given any inputs', function() {
            var actual = chance.mrz();
            expect(actual).to.be.a.string;
            expect(actual.substr(0, 5)).to.equal('P<GBR');
            expect(actual).to.have.length(88);
            expect(actual.substr(44)).to.match(/^[A-Z0-9<]{9}[0-9]{1}[A-Z]{3}[0-9]{7}[A-Z]{1}[0-9]{7}[A-Z0-9<]{14}[0-9]{2}$/);
        });
    });
});
<commit_msg>Update test.person.js<commit_after>/// <reference path="../chance.js" />
/// <reference path="../node_modules/underscore/underscore-min.js" />

var expect = chai.expect;

describe("Person", function () {
    var name, first, last, prefix, suffix, ssn, chance = new Chance();

    describe("age()", function () {
        it("returns a random age within expected bounds", function () {
            _(1000).times(function () {
                expect(chance.age()).to.be.a('number');
                expect(chance.age()).to.be.within(1, 100);
            });
        });

        describe("ranges", function() {
            var age;

            it("child", function () {
                _(1000).times(function () {
                    age = chance.age({ type: 'child' });
                    expect(age).to.be.a('number');
                    expect(age).to.be.within(1, 12);
                });
            });

            it("teen", function () {
                _(1000).times(function () {
                    age = chance.age({ type: 'teen' });
                    expect(age).to.be.a('number');
                    expect(age).to.be.within(13, 19);
                });
            });

            it("adult", function () {
                _(1000).times(function () {
                    age = chance.age({ type: 'adult' });
                    expect(age).to.be.a('number');
                    expect(age).to.be.within(18, 65);
                });
            });

            it("senior", function () {
                _(1000).times(function () {
                    age = chance.age({ type: 'senior' });
                    expect(age).to.be.a('number');
                    expect(age).to.be.within(65, 100);
                });
            });
        });

        it("can have the type specified", function () {
            _(1000).times(function () {
                expect(chance.age({type: 'child'})).to.be.within(1, 13);
                expect(chance.age({type: 'senior'})).to.be.within(65, 120);
            });
        });
    });

    describe("birthday()", function () {
        it("returns a random birthday", function () {
            _(1000).times(function () {
                expect(chance.birthday()).to.be.a('Date');
                expect(chance.birthday().getFullYear()).to.be.within((new Date().getFullYear() - 120), (new Date().getFullYear()));
            });
        });

        it("can have a string returned", function () {
            _(1000).times(function () {
                expect(chance.birthday({string: true})).to.be.a('string');
                expect(chance.birthday({string: true})).to.match(/^[0-9][0-9]?\/[0-9][0-9]?\/[0-9]{4}/m);
            });
        });

        it("can have a year specified", function () {
            _(1000).times(function () {
                expect(chance.birthday({year: 1983}).getFullYear()).to.equal(1983);
            });
        });

        it("can have an age range specified", function () {
            _(1000).times(function () {
                expect(chance.birthday({type: 'child'}).getFullYear()).to.be.within((new Date().getFullYear() - 13), (new Date().getFullYear()));
            });
        });
    });

    describe("gender()", function () {
        it("returns a random gender", function () {
            _(1000).times(function () {
                expect(chance.gender()).to.be.match(/(Male|Female)/);
            });
        });
    });

    describe("name()", function () {
        it("returns a random name", function () {
            _(1000).times(function () {
                name = chance.name();
                expect(name).to.be.a('string');
                expect(name).to.have.length.within(2, 30);
                expect(name.split(' ')).to.have.length(2);
            });
        });

        it("can have the middle name specified", function () {
            _(1000).times(function () {
                name = chance.name({middle: true});
                expect(name).to.be.a('string');
                expect(name.split(' ')).to.have.length(3);
            });
        });

        it("can have the middle initial specified", function () {
            _(1000).times(function () {
                name = chance.name({middle_initial: true});
                expect(name).to.be.a('string');
                expect(name.split(' ')).to.have.length(3);
                expect(name.split(' ')[1]).to.match(/[A-Z]\./);
                expect(name.indexOf('.')).to.be.ok;
            });
        });

        it("can have the prefix specified", function () {
            _(1000).times(function () {
                name = chance.name({prefix: true});
                expect(name).to.be.a('string');
                expect(name.split(' ')).to.have.length(3);
            });
        });

        it("can have the suffix specified", function () {
            _(1000).times(function () {
                name = chance.name({suffix: true});
                expect(name).to.be.a('string');
                expect(name.split(' ')).to.have.length(3);
            });
        });
    });

    describe("first()", function () {
        it("returns a random first name", function () {
            _(1000).times(function () {
                first = chance.first();
                expect(first).to.be.a('string');
                expect(first).to.have.length.within(2, 20);
                expect(first.split(' ')).to.have.length(1);
            });
        });
    });

    describe("last()", function () {
        it("returns a random last name", function () {
            _(1000).times(function () {
                last = chance.last();
                expect(last).to.be.a('string');
                expect(last).to.have.length.within(2, 20);
                expect(last.split(' ')).to.have.length(1);
            });
        });

    });

    describe("name_prefix()", function () {
        it("returns a random prefix", function () {
            _(1000).times(function () {
                prefix = chance.name_prefix();
                expect(prefix).to.be.a('string');
                expect(prefix).to.have.length.below(5);
            });
        });

        it("returns a correctly gendered prefix", function () {
            _(1000).times(function () {
                prefix = chance.name_prefix({ gender: "female" });
                expect(prefix).to.not.equal("Mr.");
                prefix = chance.name_prefix({ gender: "male" });
                expect(prefix).to.not.equal("Mrs.");
                expect(prefix).to.not.equal("Miss");
            });
        });

        it("can get full prefix", function () {
            _(1000).times(function () {
                prefix = chance.name_prefix({full: true});
                expect(prefix).to.be.a('string');
                expect(prefix).to.have.length.above(3);
            });
        });
    });

    describe("name_suffix()", function () {
        it("returns a random suffix", function () {
            _(1000).times(function () {
                suffix = chance.name_suffix();
                expect(suffix).to.be.a('string');
                expect(suffix).to.have.length.below(7);
            });
        });

        it("can get full suffix", function () {
            _(1000).times(function () {
                suffix = chance.name_suffix({full: true});
                expect(suffix).to.be.a('string');
                expect(suffix).to.have.length.above(5);
            });
        });
    });

    describe("suffix()", function () {
        it("returns a random suffix", function () {
            _(1000).times(function () {
                suffix = chance.suffix();
                expect(suffix).to.be.a('string');
                expect(suffix).to.have.length.below(7);
            });
        });

        it("can get full suffix", function () {
            _(1000).times(function () {
                suffix = chance.suffix({full: true});
                expect(suffix).to.be.a('string');
                expect(suffix).to.have.length.above(5);
            });
        });
    });

    describe("ssn()", function () {
        it("returns a random socal security number", function () {
            _(1000).times(function () {
                ssn = chance.ssn();
                expect(ssn).to.be.a('string');
                expect(ssn).to.match(/^\d{3}-\d{2}-\d{4}$/m);
                expect(ssn).to.have.length(11);
            });
        });

        it("can get just last 4", function () {
            _(1000).times(function () {
                ssn = chance.ssn({ ssnFour: true });
                expect(ssn).to.be.a('string');
                expect(ssn).to.match(/^\d{4}$/m);
                expect(ssn).to.have.length(4);
            });
        });
    });

    describe("cpf()", function () {
        var cpf;
        it("returns a random valid taxpayer number for Brazil citizens (CPF)", function () {
            _(1000).times(function () {
                cpf = chance.cpf();
                expect(cpf).to.be.a('string');
                expect(cpf).to.match(/^\d{3}.\d{3}.\d{3}-\d{2}$/m);
                expect(cpf).to.have.length(14);
            });
        });
    });

    describe("israelId()",function(){
        it("Should return a valid israel ID",function(){
            _(1000).times(function () {
                var x=chance.israelId();
                expect(x).to.have.length(9);
                var y=0;
                for (var i=0;i<8;i++){
                        var thisDigit=  x[i] *  (i/2===parseInt(i/2) ? 1 : 2);
                        thisDigit=chance.pad(thisDigit,2).toString();
                        thisDigit=parseInt(thisDigit[0]) + parseInt(thisDigit[1]);
                        y=y+thisDigit;
                        }
                var lastDigit=(10-parseInt(y.toString().slice(-1)).toString().slice(-1)).toString().slice(-1);
                expect(x[8]).to.equal(lastDigit);
            })
        });
    });

    describe('mrz()', function() {
        it('should return a valid passport number when given valid inputs', function() {
            var sample = "P<GBRFOLKS<<JOANNE<<<<<<<<<<<<<<<<<<<<<<<<<<2321126135GBR6902069F1601013<<<<<<<<<<<<<<02",
                actual = chance.mrz({
                    first: 'Joanne',
                    last: 'Folks',
                    gender: 'F',
                    dob: '690206',
                    expiry: '160101',
                    passportNumber: '232112613',
                });

            expect(actual).to.equal(sample);

            sample = "P<GBRKELLY<<LIDA<<<<<<<<<<<<<<<<<<<<<<<<<<<<3071365913GBR6606068F2003131<<<<<<<<<<<<<<04";
            actual = chance.mrz({
                first: 'Lida',
                last: 'Kelly',
                gender: 'F',
                dob: '660606',
                expiry: '200313',
                passportNumber: '307136591',
            });

            expect(actual).to.equal(sample);
        });
        it('should return a valid random passport number when not given any inputs', function() {
            var actual = chance.mrz();
            expect(actual).to.be.a.string;
            expect(actual.substr(0, 5)).to.equal('P<GBR');
            expect(actual).to.have.length(88);
            expect(actual.substr(44)).to.match(/^[A-Z0-9<]{9}[0-9]{1}[A-Z]{3}[0-9]{7}[A-Z]{1}[0-9]{7}[A-Z0-9<]{14}[0-9]{2}$/);
        });
    });
});
<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

var now;

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    console.log('Checking alive key for key : ' + adapterShortName);
    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    sendTo('history.0', 'enableHistory', {
                        id: 'system.adapter.history.0.memRss',
                        options: {
                            changesOnly:  true,
                            debounce:     0,
                            retention:    31536000,
                            maxLength:    3,
                            changesMinDelta: 0.5
                        }
                    }, function (result) {
                        expect(result.error).to.be.undefined;
                        expect(result.success).to.be.true;
                        // wait till adapter receives the new settings
                        setTimeout(function () {
                            done();
                        }, 2000);
                    });
                    /*objects.getObject('system.adapter.history.0.memRss', function (err, obj) {
                        obj.common.custom = {
                            'history.0': {
                                enabled:      true,
                                changesOnly:  false,
                                debounce:     0,
                                retention:    31536000,
                                maxLength:    3
                            }
                        };
                        objects.setObject('system.adapter.history.0.memRss', obj, function (err) {
                            // wait till adapter receives the new settings
                            setTimeout(function () {
                                done();
                            }, 2000);
                        });
                    });*/

                });
        });
    });
    it('Test ' + adapterShortName + ': Write values into DB', function (done) {
        this.timeout(25000);
        now = new Date().getTime();

        states.setState('system.adapter.history.0.memRss', {val: 1, ts: now - 20000}, function (err) {
            if (err) {
                console.log(err);
            }
            setTimeout(function () {
                states.setState('system.adapter.history.0.memRss', {val: 2, ts: now - 10000}, function (err) {
                    if (err) {
                        console.log(err);
                    }
                    setTimeout(function () {
                        states.setState('system.adapter.history.0.memRss', {val: 2, ts: now - 5000}, function (err) {
                            if (err) {
                                console.log(err);
                            }
                            setTimeout(function () {
                                states.setState('system.adapter.history.0.memRss', {val: 2.2, ts: now - 4000}, function (err) {
                                    if (err) {
                                        console.log(err);
                                    }
                                    setTimeout(function () {
                                        states.setState('system.adapter.history.0.memRss', {val: 2.5, ts: now - 3000}, function (err) {
                                            if (err) {
                                                console.log(err);
                                            }
                                            setTimeout(function () {
                                                states.setState('system.adapter.history.0.memRss', {val: 3, ts: now - 1000}, function (err) {
                                                    if (err) {
                                                        console.log(err);
                                                    }
                                                    done();
                                                });
                                            }, 100);
                                        });
                                    }, 100);
                                });
                            }, 100);
                        });
                    }, 100);
                });
            }, 100);
        });
    });
    it('Test ' + adapterShortName + ': Read values from DB using GetHistory', function (done) {
        this.timeout(25000);

        sendTo('history.0', 'getHistory', {
            id: 'system.adapter.history.0.memRss',
            options: {
                start:     now-30000,
                count:     50,
                aggregate: 'none'
            }
        }, function (result) {
            console.log(JSON.stringify(result.result, null, 2));
            expect(result.result.length).to.be.at.least(4);
            var found = 0;
            for (var i = 0; i < result.result.length; i++) {
                if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++;
            }
            expect(found).to.be.equal(4);

            sendTo('history.0', 'getHistory', {
                id: 'system.adapter.history.0.memRss',
                options: {
                    start:     now-15000,
                    count:     2,
                    aggregate: 'none'
                }
            }, function (result) {
                console.log(JSON.stringify(result.result, null, 2));
                expect(result.result.length).to.be.equal(2);
                var found = 0;
                for (var i = 0; i < result.result.length; i++) {
                    if (result.result[i].val >= 2 && result.result[i].val < 3) found ++;
                }
                expect(found).to.be.equal(2);
                done();
            });
        });
    });
    it('Test ' + adapterShortName + ': Read average from DB using GetHistory', function (done) {
        this.timeout(25000);

        sendTo('history.0', 'getHistory', {
            id: 'system.adapter.history.0.memRss',
            options: {
                start:     now-30000,
                end:       now+1,
                count:     1,
                aggregate: 'average',
                ignoreNull: true
            }
        }, function (result) {
            console.log(JSON.stringify(result.result, null, 2));
            expect(result.result.length).to.be.equal(3);
            expect(result.result[0].val).to.be.equal(2.13);
            expect(result.result[1].val).to.be.equal(2.13);
            expect(result.result[2].val).to.be.equal(2.13);
        });
    });
    it('Test ' + adapterShortName + ': Disable Datapoint again', function (done) {
        this.timeout(5000);

        sendTo('history.0', 'disableHistory', {
            id: 'system.adapter.history.0.memRss',
        }, function (result) {
            expect(result.error).to.be.undefined;
            expect(result.success).to.be.true;
            // wait till adapter receives the new settings
            done();
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<commit_msg>final fix of test<commit_after>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

var now;

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    console.log('Checking alive key for key : ' + adapterShortName);
    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    sendTo('history.0', 'enableHistory', {
                        id: 'system.adapter.history.0.memRss',
                        options: {
                            changesOnly:  true,
                            debounce:     0,
                            retention:    31536000,
                            maxLength:    3,
                            changesMinDelta: 0.5
                        }
                    }, function (result) {
                        expect(result.error).to.be.undefined;
                        expect(result.success).to.be.true;
                        // wait till adapter receives the new settings
                        setTimeout(function () {
                            done();
                        }, 2000);
                    });
                    /*objects.getObject('system.adapter.history.0.memRss', function (err, obj) {
                        obj.common.custom = {
                            'history.0': {
                                enabled:      true,
                                changesOnly:  false,
                                debounce:     0,
                                retention:    31536000,
                                maxLength:    3
                            }
                        };
                        objects.setObject('system.adapter.history.0.memRss', obj, function (err) {
                            // wait till adapter receives the new settings
                            setTimeout(function () {
                                done();
                            }, 2000);
                        });
                    });*/

                });
        });
    });
    it('Test ' + adapterShortName + ': Write values into DB', function (done) {
        this.timeout(25000);
        now = new Date().getTime();

        states.setState('system.adapter.history.0.memRss', {val: 1, ts: now - 20000}, function (err) {
            if (err) {
                console.log(err);
            }
            setTimeout(function () {
                states.setState('system.adapter.history.0.memRss', {val: 2, ts: now - 10000}, function (err) {
                    if (err) {
                        console.log(err);
                    }
                    setTimeout(function () {
                        states.setState('system.adapter.history.0.memRss', {val: 2, ts: now - 5000}, function (err) {
                            if (err) {
                                console.log(err);
                            }
                            setTimeout(function () {
                                states.setState('system.adapter.history.0.memRss', {val: 2.2, ts: now - 4000}, function (err) {
                                    if (err) {
                                        console.log(err);
                                    }
                                    setTimeout(function () {
                                        states.setState('system.adapter.history.0.memRss', {val: 2.5, ts: now - 3000}, function (err) {
                                            if (err) {
                                                console.log(err);
                                            }
                                            setTimeout(function () {
                                                states.setState('system.adapter.history.0.memRss', {val: 3, ts: now - 1000}, function (err) {
                                                    if (err) {
                                                        console.log(err);
                                                    }
                                                    done();
                                                });
                                            }, 100);
                                        });
                                    }, 100);
                                });
                            }, 100);
                        });
                    }, 100);
                });
            }, 100);
        });
    });
    it('Test ' + adapterShortName + ': Read values from DB using GetHistory', function (done) {
        this.timeout(25000);

        sendTo('history.0', 'getHistory', {
            id: 'system.adapter.history.0.memRss',
            options: {
                start:     now-30000,
                count:     50,
                aggregate: 'none'
            }
        }, function (result) {
            console.log(JSON.stringify(result.result, null, 2));
            expect(result.result.length).to.be.at.least(4);
            var found = 0;
            for (var i = 0; i < result.result.length; i++) {
                if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++;
            }
            expect(found).to.be.equal(4);

            sendTo('history.0', 'getHistory', {
                id: 'system.adapter.history.0.memRss',
                options: {
                    start:     now-15000,
                    count:     2,
                    aggregate: 'none'
                }
            }, function (result) {
                console.log(JSON.stringify(result.result, null, 2));
                expect(result.result.length).to.be.equal(2);
                var found = 0;
                for (var i = 0; i < result.result.length; i++) {
                    if (result.result[i].val >= 2 && result.result[i].val < 3) found ++;
                }
                expect(found).to.be.equal(2);
                done();
            });
        });
    });
    it('Test ' + adapterShortName + ': Read average from DB using GetHistory', function (done) {
        this.timeout(25000);

        sendTo('history.0', 'getHistory', {
            id: 'system.adapter.history.0.memRss',
            options: {
                start:     now-30000,
                end:       now+1,
                count:     1,
                aggregate: 'average',
                ignoreNull: true
            }
        }, function (result) {
            console.log(JSON.stringify(result.result, null, 2));
            expect(result.result.length).to.be.equal(3);
            expect(result.result[0].val).to.be.equal(2.13);
            expect(result.result[1].val).to.be.equal(2.13);
            expect(result.result[2].val).to.be.equal(2.13);
            done();
        });
    });
    it('Test ' + adapterShortName + ': Disable Datapoint again', function (done) {
        this.timeout(5000);

        sendTo('history.0', 'disableHistory', {
            id: 'system.adapter.history.0.memRss',
        }, function (result) {
            expect(result.error).to.be.undefined;
            expect(result.success).to.be.true;
            // wait till adapter receives the new settings
            done();
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<|endoftext|>


<commit_before>/**
* MediaKeys namespace.
*/
if (typeof MediaKeys == "undefined") var MediaKeys = {};

MediaKeys.basePlayer = "//iframe[@id='app-player']";
MediaKeys.playButton = "//button[@id='play-pause' and not(contains(@class,'playing'))]";
MediaKeys.pauseButton = "//button[@id='play-pause' and contains(@class,'playing')]";
MediaKeys.skipButton = "//button[@id='next']";
MediaKeys.previousButton = "//button[@id='previous']";
<commit_msg>Update play.spotify.com-view.js<commit_after>/**
 * MediaKeys namespace.
 */
if (typeof MediaKeys == "undefined") var MediaKeys = {};

MediaKeys.basePlayer = "//iframe[@id='app-player']";
MediaKeys.playButton = "//button[@id='play-pause' and not(contains(@class,'playing'))]";
MediaKeys.pauseButton = "//button[@id='play-pause' and contains(@class,'playing')]";
MediaKeys.skipButton = "//button[@id='next']";
MediaKeys.previousButton = "//button[@id='previous']";
<|endoftext|>


<commit_before>// Testing libraries
const chai = require('chai');
chai.use(require('chai-as-promised'));
global.cheerio = require('cheerio');
global.expect = chai.expect;
global.fs = require('fs');
global.request = require('supertest');
global.url = require('url');

// Rose modules
global.app = require('../app');
global.Feature = require('../lib/feature');
global.scraper = require('../lib/scraper');
global.seedData = require('./seedData');
global.seeds = require('../lib/seeds');

// Mocks
global.mockedSeeds = function () {
	seeds(seedData);
};
<commit_msg>Add missing return for test helper<commit_after>// Testing libraries
const chai = require('chai');
chai.use(require('chai-as-promised'));
global.cheerio = require('cheerio');
global.expect = chai.expect;
global.fs = require('fs');
global.request = require('supertest');
global.url = require('url');

// Rose modules
global.app = require('../app');
global.Feature = require('../lib/feature');
global.scraper = require('../lib/scraper');
global.seedData = require('./seedData');
global.seeds = require('../lib/seeds');

// Mocks
global.mockedSeeds = function () {
  return seeds(seedData);
};
<|endoftext|>


<commit_before>/* globals _, ko, casexml, $ */
hqDefine("data_interfaces/js/case_management", function() {
    var CaseManagement = function (o) {
        'use strict';
        var self = {};

        self.receiverUrl = o.receiverUrl;
        self.updatedCase = null;
        self.webUserID = o.webUserID;
        self.webUserName = o.webUserName;
        self.form_name = o.form_name;

        // What's checked in the table below
        self.selected_cases = ko.observableArray();
        self.selected_owners = ko.observableArray();
        self.selected_owner_types = ko.observableArray();

        // What we're assigning to
        self.new_owner = ko.observable();

        self.is_submit_enabled = ko.computed(function () {
            return !!self.new_owner();
        }, self);

        self.should_show_owners = ko.observable(true);

        var enddate = new Date(o.enddate),
            now = new Date();
        self.on_today = (enddate.toDateString() === now.toDateString());

        var getOwnerType = function (ownerId) {
            if (ownerId.startsWith('u')) {
                return 'user';
            } else if (ownerId.startsWith('sg')) {
                return 'group';
            }
        };

        var updateCaseRow = function (caseId, ownerId, ownerType) {
            return function() {
                var $checkbox = $('#data-interfaces-reassign-cases input[data-caseid="' + caseId + '"].selected-commcare-case'),
                    username = $('#reassign_owner_select').data().select2.data().text,
                    dateMessage = (self.on_today) ? '' :
                        'Out of range of filter. Will ' +
                                        'not appear on page refresh.';
                $checkbox.data('owner', ownerId);
                $checkbox.data('ownertype', ownerType);

                var $row = $checkbox.closest("tr"),
                    groupLabel = '';

                if (ownerType === 'group') {
                    groupLabel = ' group';
                }

                $row.find('td:nth-child(4)').html(username + groupLabel +' updated');
                $row.find('td:nth-child(5)').html('Today ' + dateMessage);
                $checkbox.prop("checked", false).change();
            };
        };

        self.changeNewOwner = function () {
            self.new_owner($('#reassign_owner_select').val());
        };

        self.updateCaseSelection = function (data, event) {
            var $checkbox = $(event.currentTarget),
                caseID = $checkbox.data('caseid'),
                ownerID = $checkbox.data('owner'),
                ownerType = $checkbox.data('ownertype');

            var ind = self.selected_cases().indexOf(caseID),
                $selectedRow = $checkbox.closest('tr');

            if ($checkbox.is(':checked')) {
                $selectedRow.addClass('active');
                if (ind < 0) {
                    self.selected_cases.push(caseID);
                }
                self.selected_owner_types.push(ownerType);
                self.selected_owners.push(ownerID);
            } else {
                $selectedRow.removeClass('active');
                if (ind >= 0) {
                    self.selected_cases.splice(ind, 1);
                }
                self.selected_owner_types.splice(self.selected_owner_types().indexOf(ownerType), 1);
                self.selected_owners.splice(self.selected_owners().indexOf(ownerID), 1);
            }
        };

        self.clearCaseSelection = function () {
            self.selected_cases.removeAll();
        };

        self.updateCaseOwners = function (form) {
            var newOwner = $(form).find('#reassign_owner_select').val(),
                $modal = $('#caseManagementStatusModal'),
                ownerType = getOwnerType(newOwner);

            if (newOwner.includes('__')) {
                // groups and users have different number of characters before the id
                // users are u__id and groups are sg__id
                newOwner = newOwner.slice(newOwner.indexOf('__') + 2);
            }

            if (_.isEmpty(newOwner)) {
                $modal.find('.modal-body').text("Please select an owner");
                $modal.modal('show');
            } else {
                $(form).find("[type='submit']").disableButton();
                for (var i = 0; i < self.selected_cases().length; i++) {
                    var caseId = self.selected_cases()[i],
                        xform;
                    xform = casexml.CaseDelta.wrap({
                        case_id: caseId,
                        properties: {owner_id: newOwner},
                    }).asXFormInstance({
                        user_id: self.webUserID,
                        username: self.webUserName,
                        form_name: self.form_name,
                    }).serialize();

                    $.ajax({
                        url: self.receiverUrl,
                        type: 'post',
                        data: xform,
                        success: updateCaseRow(caseId, newOwner, ownerType),
                    });

                }
            }
        };

        return self;
    };

    ko.bindingHandlers.caseReassignmentForm = {
        update: function(element, valueAccessor) {
            var value = valueAccessor()();
            var $element = $(element);
            if (value.length > 0) {
                $element.slideDown();
            } else {
                $element.find("[type='submit']").enableButton();
                $element.slideUp();
            }
        },
    };

    $(function() {
        var initialPageData = hqImport("hqwebapp/js/initial_page_data"),
            interfaceSelector = '#data-interfaces-reassign-cases',
            caseManagementModel = CaseManagement({
                receiverUrl: initialPageData.reverse("receiver_secure_post"),
                enddate: initialPageData.get("reassign_cases_enddate"),
                webUserID: initialPageData.get("web_user_id"),
                webUserName: initialPageData.get("web_username"),
                form_name: gettext("Case Reassignment (via HQ)"),
            });

        // Apply bindings whenever report content is refreshed
        $(document).on('ajaxSuccess', function(e, xhr, ajaxOptions) {
            if (ajaxOptions.url.indexOf(initialPageData.get("js_options").asyncUrl) === -1) {
                return;
            }

            // Apply bindings to reassignment interface and select2
            $(interfaceSelector).koApplyBindings(caseManagementModel);

            $('#reassign_owner_select').select2({
                placeholder: gettext("Search for users or groups"),
                ajax: {
                    url: initialPageData.reverse("reassign_case_options"),
                    data: function (term) {
                        return {
                            q: term,
                        };
                    },
                    dataType: 'json',
                    quietMillis: 250,
                    results: function (data) {
                        return {
                            total: data.total,
                            results: data.results,
                        };
                    },
                    cache: true,
                },
            });
        });

        // Event handlers for selecting & de-selecting cases
        // Similar to archive_forms.js, would be good to combine the two
        $(document).on("click", interfaceSelector + " a.select-all", function () {
            $(interfaceSelector).find('input.selected-commcare-case').prop('checked', true).change();
            return false;
        });

        function selectNone() {
            $(interfaceSelector).find('input.selected-commcare-case:checked').prop('checked', false).change();
        }

        $(document).on("click", interfaceSelector + " a.select-none", function() {
            selectNone();
            return false;
        });

        $(document).on("mouseup", interfaceSelector + " .dataTables_paginate a", selectNone);
        $(document).on("change", interfaceSelector + " .dataTables_length select", selectNone);

        $(document).on("change", interfaceSelector + " input.selected-commcare-case", function(e) {
            caseManagementModel.updateCaseSelection({}, e);
        });
    });
});
<commit_msg>Fix race condition and also fix for other reporting pages<commit_after>/* globals _, ko, casexml, $ */
hqDefine("data_interfaces/js/case_management", function() {
    var CaseManagement = function (o) {
        'use strict';
        var self = {};

        self.receiverUrl = o.receiverUrl;
        self.updatedCase = null;
        self.webUserID = o.webUserID;
        self.webUserName = o.webUserName;
        self.form_name = o.form_name;

        // What's checked in the table below
        self.selected_cases = ko.observableArray();
        self.selected_owners = ko.observableArray();
        self.selected_owner_types = ko.observableArray();

        // What we're assigning to
        self.new_owner = ko.observable();

        self.is_submit_enabled = ko.computed(function () {
            return !!self.new_owner();
        }, self);

        self.should_show_owners = ko.observable(true);

        var enddate = new Date(o.enddate),
            now = new Date();
        self.on_today = (enddate.toDateString() === now.toDateString());

        var getOwnerType = function (ownerId) {
            if (ownerId.startsWith('u')) {
                return 'user';
            } else if (ownerId.startsWith('sg')) {
                return 'group';
            }
        };

        var updateCaseRow = function (caseId, ownerId, ownerType) {
            return function() {
                var $checkbox = $('#data-interfaces-reassign-cases input[data-caseid="' + caseId + '"].selected-commcare-case'),
                    username = $('#reassign_owner_select').data().select2.data().text,
                    dateMessage = (self.on_today) ? '' :
                        'Out of range of filter. Will ' +
                                        'not appear on page refresh.';
                $checkbox.data('owner', ownerId);
                $checkbox.data('ownertype', ownerType);

                var $row = $checkbox.closest("tr"),
                    groupLabel = '';

                if (ownerType === 'group') {
                    groupLabel = ' group';
                }

                $row.find('td:nth-child(4)').html(username + groupLabel +' updated');
                $row.find('td:nth-child(5)').html('Today ' + dateMessage);
                $checkbox.prop("checked", false).change();
            };
        };

        self.changeNewOwner = function () {
            self.new_owner($('#reassign_owner_select').val());
        };

        self.updateCaseSelection = function (data, event) {
            var $checkbox = $(event.currentTarget),
                caseID = $checkbox.data('caseid'),
                ownerID = $checkbox.data('owner'),
                ownerType = $checkbox.data('ownertype');

            var ind = self.selected_cases().indexOf(caseID),
                $selectedRow = $checkbox.closest('tr');

            if ($checkbox.is(':checked')) {
                $selectedRow.addClass('active');
                if (ind < 0) {
                    self.selected_cases.push(caseID);
                }
                self.selected_owner_types.push(ownerType);
                self.selected_owners.push(ownerID);
            } else {
                $selectedRow.removeClass('active');
                if (ind >= 0) {
                    self.selected_cases.splice(ind, 1);
                }
                self.selected_owner_types.splice(self.selected_owner_types().indexOf(ownerType), 1);
                self.selected_owners.splice(self.selected_owners().indexOf(ownerID), 1);
            }
        };

        self.clearCaseSelection = function () {
            self.selected_cases.removeAll();
        };

        self.updateCaseOwners = function (form) {
            var newOwner = $(form).find('#reassign_owner_select').val(),
                $modal = $('#caseManagementStatusModal'),
                ownerType = getOwnerType(newOwner);

            if (newOwner.includes('__')) {
                // groups and users have different number of characters before the id
                // users are u__id and groups are sg__id
                newOwner = newOwner.slice(newOwner.indexOf('__') + 2);
            }

            if (_.isEmpty(newOwner)) {
                $modal.find('.modal-body').text("Please select an owner");
                $modal.modal('show');
            } else {
                $(form).find("[type='submit']").disableButton();
                for (var i = 0; i < self.selected_cases().length; i++) {
                    var caseId = self.selected_cases()[i],
                        xform;
                    xform = casexml.CaseDelta.wrap({
                        case_id: caseId,
                        properties: {owner_id: newOwner},
                    }).asXFormInstance({
                        user_id: self.webUserID,
                        username: self.webUserName,
                        form_name: self.form_name,
                    }).serialize();

                    $.ajax({
                        url: self.receiverUrl,
                        type: 'post',
                        data: xform,
                        success: updateCaseRow(caseId, newOwner, ownerType),
                    });

                }
            }
        };

        return self;
    };

    ko.bindingHandlers.caseReassignmentForm = {
        update: function(element, valueAccessor) {
            var value = valueAccessor()();
            var $element = $(element);
            if (value.length > 0) {
                $element.slideDown();
            } else {
                $element.find("[type='submit']").enableButton();
                $element.slideUp();
            }
        },
    };

    $(function() {
        var initialPageData = hqImport("hqwebapp/js/initial_page_data"),
            interfaceSelector = '#data-interfaces-reassign-cases',
            caseManagementModel;

        var applyBindings = function() {
            if ($(interfaceSelector).length) {
                caseManagementModel = CaseManagement({
                    receiverUrl: initialPageData.reverse("receiver_secure_post"),
                    enddate: initialPageData.get("reassign_cases_enddate"),
                    webUserID: initialPageData.get("web_user_id"),
                    webUserName: initialPageData.get("web_username"),
                    form_name: gettext("Case Reassignment (via HQ)"),
                });
                $(interfaceSelector).koApplyBindings(caseManagementModel);
            }

            var $select = $('#reassign_owner_select');
            if ($select.length) {
                $select.select2({
                    placeholder: gettext("Search for users or groups"),
                    ajax: {
                        url: initialPageData.reverse("reassign_case_options"),
                        data: function (term) {
                            return {
                                q: term,
                            };
                        },
                        dataType: 'json',
                        quietMillis: 250,
                        results: function (data) {
                            return {
                                total: data.total,
                                results: data.results,
                            };
                        },
                        cache: true,
                    },
                });
            }
        }

        // Apply bindings whenever report content is refreshed
        applyBindings();
        $(document).on('ajaxSuccess', function(e, xhr, ajaxOptions) {
            var jsOptions = initialPageData.get("js_options");
            if (jsOptions && ajaxOptions.url.indexOf(jsOptions.asyncUrl) === -1) {
                return;
            }
            applyBindings();
        });

        // Event handlers for selecting & de-selecting cases
        // Similar to archive_forms.js, would be good to combine the two
        $(document).on("click", interfaceSelector + " a.select-all", function () {
            $(interfaceSelector).find('input.selected-commcare-case').prop('checked', true).change();
            return false;
        });

        function selectNone() {
            $(interfaceSelector).find('input.selected-commcare-case:checked').prop('checked', false).change();
        }

        $(document).on("click", interfaceSelector + " a.select-none", function() {
            selectNone();
            return false;
        });

        $(document).on("mouseup", interfaceSelector + " .dataTables_paginate a", selectNone);
        $(document).on("change", interfaceSelector + " .dataTables_length select", selectNone);

        $(document).on("change", interfaceSelector + " input.selected-commcare-case", function(e) {
            caseManagementModel.updateCaseSelection({}, e);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

// Import required libraroes
var pg = require('pg');
var _ = require('lodash');
var async = require('async');
var elasticsearch = require('elasticsearch');

var conString = 'postgres://'+process.env.POSTGRES_USER+':'+process.env.POSTGRES_PASSWORD+'@'+process.env.POSTGRES_SERVER+'/dataportal';

var clientElastic = new elasticsearch.Client({
  host: process.env.ESDBHOST+':9200'
});

var client = new pg.Client(conString);

function fixDate(date) {
  var day = new Date(date).getDate();
  var month = new Date(date).getMonth();
  var year = new Date(date).getFullYear();

  if(day < 1) {
    day = 1;
  }
  if(month < 1) {
    month = 1;
  } else if(month > 12) {
    month = 12;
  }

  if (day > 28 && month == 2) {
    day = 28;
  }
  if (day > 31 && (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)) {
    day = 31;
  }
  if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11)) {
    day = 30;
  }
  return year+'-'+month+'-'+day;
}

client.connect(function(err) {
  if(err) {
    return console.error('could not connect to postgres', err);
  }
  client.query('SELECT \
    "public"."dwca_resource"."id" AS id, \
    "public"."dwca_resource"."name" AS name, \
    "public"."resource_metadata"."gbif_package_id" AS gbif_package_id, \
    "public"."resource_metadata"."alternate_identifier" AS alternate_identifier, \
    "public"."resource_metadata"."title" AS title, \
    "public"."resource_metadata"."publication_date" AS publication_date, \
    "public"."resource_metadata"."language" AS language, \
    "public"."resource_metadata"."_abstract" AS resource_description, \
    "public"."resource_metadata"."keyword" AS keyword, \
    "public"."resource_metadata"."keyword_thesaurus" AS keyword_thesaurus, \
    "public"."resource_metadata"."intellectual_rights" AS intellectual_rights, \
    "public"."resource_metadata"."citation" AS citation, \
    "public"."resource_metadata"."hierarchy_level" AS hierarchy_level, \
    "public"."resource_metadata"."resource_logo_url" AS logo_url, \
    "public"."resource_metadata"."parent_collection_identifier", \
    "public"."resource_metadata"."collection_identifier" AS collection_identifier, \
    "public"."resource_metadata"."collection_name" \
    FROM "public"."dwca_resource" \
    JOIN "public"."resource_metadata" ON "public"."dwca_resource"."id" = "public"."resource_metadata"."dwca_resource_id"', function(err, result) {
    if(err) {
      return console.error('error running query', err);
    }
    var resource = {};
    async.eachSeries(result.rows, function(n,callback) {
      async.series({
        fillInitialData: function(callback) {
          var parsedAndFixedDate = fixDate(n.publication_date);
          resource = {
            id: n.id,
            name: n.name,
            title: n.title,
            description: n.resource_description,
            intellectual_rights: n.jerarquianombrescomunes,
            citation: n.citation,
            logo_url: n.logo_url,
            publication_date: parsedAndFixedDate,
            gbif_package_id: n.gbif_package_id,
            alternate_identifier: n.alternate_identifier,
            language: n.language,
            keyword: n.keyword,
            keyword_thesaurus: n.keyword_thesaurus,
            hierarchy_level: n.hierarchy_level,
            collection_identifier: n.collection_identifier,
            collection_name: n.collection_name
          };
          callback();
        },
        getContactData: function(callback) {
          client.query('SELECT \
            "public"."contact"."auto_id" AS id_contact, \
            "public"."contact"."name" AS name, \
            "public"."contact"."position_name" AS position_name, \
            "public"."contact"."organization_name" AS organization_name, \
            "public"."contact"."address" AS address, \
            "public"."contact"."city" AS city, \
            "public"."contact"."administrative_area" AS administrative_area, \
            "public"."contact"."country" AS country, \
            "public"."contact"."postal_code" AS postal_code, \
            "public"."contact"."phone" AS phone, \
            "public"."contact"."email" AS email, \
            "public"."contact"."role" AS role, \
            "public"."contact"."publisher_fkey", \
            "public"."contact"."resource_metadata_fkey" \
            FROM \
            "public"."contact" \
            WHERE \
            "public"."contact"."resource_metadata_fkey" = '+n.id, function(err, result) {
            if((typeof result !== 'undefined')) {
              if(result.rows.length > 0) {
                resource.contact = [];
                _.forEach(result.rows, function(n2,key2) {
                  resource.contact[key2] = {
                    id: n2.id_contact,
                    name: n2.name,
                    position_name: n2.position_name,
                    organization_name: n2.organization_name,
                    address: n2.address,
                    city: n2.city,
                    administrative_area: n2.administrative_area,
                    country: n2.country,
                    postal_code: n2.postal_code,
                    phone: n2.phone,
                    email: n2.email,
                    role: n2.role
                  };
                });
              }
            }
            callback();
          });
        },
        saveToElasticSearch: function(callback) {
          if((typeof resource !== 'undefined')) {
            clientElastic.create({
              index: 'sibdataportal',
              type: 'resource',
              body: resource
            }, function (error, response) {
              if(error) {
                console.log(error);
              }
              callback();
            });
          } else {
            callback();
          }
        }
      }, function(err) {
        if(err) {
          console.log("Error saving data");
        } else {
          // Continue data processing
          //console.log(ficha);
          callback();
        }
      })
    }, function(err) {
      if(err) {
        console.log("Error saving data");
      } else {
        console.log("Catalog info saved successfully");
        client.end();
      }
    });
  });
});
<commit_msg>Fix an error related with the correct date using universal time<commit_after>'use strict';

// Import required libraroes
var pg = require('pg');
var _ = require('lodash');
var async = require('async');
var elasticsearch = require('elasticsearch');

var conString = 'postgres://'+process.env.POSTGRES_USER+':'+process.env.POSTGRES_PASSWORD+'@'+process.env.POSTGRES_SERVER+'/dataportal';

var clientElastic = new elasticsearch.Client({
  host: process.env.ESDBHOST+':9200'
});

var client = new pg.Client(conString);

function fixDate(date) {
  var day = new Date(date).getUTCDate();
  var month = new Date(date).getUTCMonth()+1;
  var year = new Date(date).getUTCFullYear();

  if(day < 1) {
    day = 1;
  }
  if(month < 1) {
    month = 1;
  } else if(month > 12) {
    month = 12;
  }

  if (day > 28 && month == 2) {
    day = 28;
  }
  if (day > 31 && (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)) {
    day = 31;
  }
  if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11)) {
    day = 30;
  }
  return year+'-'+month+'-'+day;
}

client.connect(function(err) {
  if(err) {
    return console.error('could not connect to postgres', err);
  }
  client.query('SELECT \
    "public"."dwca_resource"."id" AS id, \
    "public"."dwca_resource"."name" AS name, \
    "public"."resource_metadata"."gbif_package_id" AS gbif_package_id, \
    "public"."resource_metadata"."alternate_identifier" AS alternate_identifier, \
    "public"."resource_metadata"."title" AS title, \
    "public"."resource_metadata"."publication_date" AS publication_date, \
    "public"."resource_metadata"."language" AS language, \
    "public"."resource_metadata"."_abstract" AS resource_description, \
    "public"."resource_metadata"."keyword" AS keyword, \
    "public"."resource_metadata"."keyword_thesaurus" AS keyword_thesaurus, \
    "public"."resource_metadata"."intellectual_rights" AS intellectual_rights, \
    "public"."resource_metadata"."citation" AS citation, \
    "public"."resource_metadata"."hierarchy_level" AS hierarchy_level, \
    "public"."resource_metadata"."resource_logo_url" AS logo_url, \
    "public"."resource_metadata"."parent_collection_identifier", \
    "public"."resource_metadata"."collection_identifier" AS collection_identifier, \
    "public"."resource_metadata"."collection_name" \
    FROM "public"."dwca_resource" \
    JOIN "public"."resource_metadata" ON "public"."dwca_resource"."id" = "public"."resource_metadata"."dwca_resource_id"', function(err, result) {
    if(err) {
      return console.error('error running query', err);
    }
    var resource = {};
    async.eachSeries(result.rows, function(n,callback) {
      async.series({
        fillInitialData: function(callback) {
          var parsedAndFixedDate = fixDate(n.publication_date);
          resource = {
            id: n.id,
            name: n.name,
            title: n.title,
            description: n.resource_description,
            intellectual_rights: n.jerarquianombrescomunes,
            citation: n.citation,
            logo_url: n.logo_url,
            publication_date: parsedAndFixedDate,
            gbif_package_id: n.gbif_package_id,
            alternate_identifier: n.alternate_identifier,
            language: n.language,
            keyword: n.keyword,
            keyword_thesaurus: n.keyword_thesaurus,
            hierarchy_level: n.hierarchy_level,
            collection_identifier: n.collection_identifier,
            collection_name: n.collection_name
          };
          callback();
        },
        getContactData: function(callback) {
          client.query('SELECT \
            "public"."contact"."auto_id" AS id_contact, \
            "public"."contact"."name" AS name, \
            "public"."contact"."position_name" AS position_name, \
            "public"."contact"."organization_name" AS organization_name, \
            "public"."contact"."address" AS address, \
            "public"."contact"."city" AS city, \
            "public"."contact"."administrative_area" AS administrative_area, \
            "public"."contact"."country" AS country, \
            "public"."contact"."postal_code" AS postal_code, \
            "public"."contact"."phone" AS phone, \
            "public"."contact"."email" AS email, \
            "public"."contact"."role" AS role, \
            "public"."contact"."publisher_fkey", \
            "public"."contact"."resource_metadata_fkey" \
            FROM \
            "public"."contact" \
            WHERE \
            "public"."contact"."resource_metadata_fkey" = '+n.id, function(err, result) {
            if((typeof result !== 'undefined')) {
              if(result.rows.length > 0) {
                resource.contact = [];
                _.forEach(result.rows, function(n2,key2) {
                  resource.contact[key2] = {
                    id: n2.id_contact,
                    name: n2.name,
                    position_name: n2.position_name,
                    organization_name: n2.organization_name,
                    address: n2.address,
                    city: n2.city,
                    administrative_area: n2.administrative_area,
                    country: n2.country,
                    postal_code: n2.postal_code,
                    phone: n2.phone,
                    email: n2.email,
                    role: n2.role
                  };
                });
              }
            }
            callback();
          });
        },
        saveToElasticSearch: function(callback) {
          if((typeof resource !== 'undefined')) {
            clientElastic.create({
              index: 'sibdataportal',
              type: 'resource',
              body: resource
            }, function (error, response) {
              if(error) {
                console.log(error);
              }
              callback();
            });
          } else {
            callback();
          }
        }
      }, function(err) {
        if(err) {
          console.log("Error saving data");
        } else {
          // Continue data processing
          //console.log(ficha);
          callback();
        }
      })
    }, function(err) {
      if(err) {
        console.log("Error saving data");
      } else {
        console.log("Catalog info saved successfully");
        client.end();
      }
    });
  });
});
<|endoftext|>


<commit_before>(function($) { $.fn.exist = function() { return this.length > 0; }; })(jQuery);

var TinyTab = $.klass({
  initialize: function(element, panels) {
    this.container = $(element);
    if(this.container.exist()) {
      var tabs = this.container.find(".tabs:first");
      // tabs.cleanWhitespace(); TODO find a jQuery equivalent method
      this.tabs = tabs.children();

      this.panels = this.container.find(".panel");
      this.showFirstPanel();
      this.selectFirstTab();
      var self = this;
      this.tabs.each(function() {
        $(this).bind("click", {self: self, element: this}, function(eventData) {
          var self = eventData.data.self;
          self.selectTab(eventData.data.element);
          eventData.stopPropagation();
        });
      });
    }
  },
  selectFirstTab: function() {
    tab = $(this.tabs[0]).is(":visible") ? this.tabs[0] : this.tabs[1];
    this.selectTab(tab);
  },
  selectTab: function(element) {
    this.tabs.removeClass("selected");
    $(element).addClass("selected");
    this.showPanel(element);
  },
  selectedTab: function() {
    return $($.grep(this.tabs, function(tab, i) {
      return $(tab).hasClass("selected");
    })[0]);
  },
  showFirstPanel: function() {
    this.showPanel(this.panels[0]);
  },
  showPanel: function(element) {
    this.panels.hide();
    $("#" + (element.id || $(element).attr("id")).replace("tab_", "")).show();
  }
});

var AssetWidget = {
  tinyTab: null,
  authenticityToken: null,
	siteId: function() {
		return location.href.match(/sites\/([0-9]+)\//)[1];
	},
	assetId: function(element) {
		return element.attr('id').match(/_(\d+)$/)[1];
	},
	memberId: function() {
		return location.href.match(/\/([0-9]+)\/(edit)/)[1];
	},
	assetsUrl: function() {
		return '/admin/sites/' + this.siteId() + '/assets';
	},
  isEdit: function() {
    return location.href.match(/\/[0-9]+\/edit#?$/)
  },
	collectionUrl: function(element) {
		return this.assetsUrl() + '/' + this.assetId(element) + '/contents';
	},
	memberUrl: function(element) {
		return this.collectionUrl(element) + '/' + this.memberId();
	},
  attachAsset: function(element, async) {
    if(!this.isAttached(element)) {
      $.ajax({
        url: this.collectionUrl(element),
				data: {
					content_id: this.memberId(),
					authenticity_token: this.authenticityToken
				},
        type: 'post',
        dataType: 'script',
        async: this.async(async)
      });
		}
  },
  detachAsset: function(element, async) {
    if(this.isAttached(element)) {
      $.ajax({
        url: this.memberUrl(element),
        data: {
          _method: 'delete',
          authenticity_token: this.authenticityToken
        },
        type: 'post',
        dataType: 'script',
        async: this.async(async)
      });
		}
  },
  async: function(value) {
    return value === undefined;
  },
	isAttached: function(element) {
	  return $("#attached_asset_" + this.assetId(element)).exist();
	},
	updateSelected: function() {
		if(!$('#assets_widget').exist()) return;
		var selectedIds = this.selectedAssetIds();
		this.updateSelectedTab(selectedIds.length > 0);
		this.updateSelectedAssets(selectedIds);
	},
	updateSelectedTab: function(show) {
		show ? this.showSelectedTab() : this.hideSelectedTab();
		this.tinyTab.selectFirstTab();
	},
	showSelectedTab: function() {
		$('#tab_attached_assets').show();
		$("#attached_assets").addClass("asset_list");
	},
	hideSelectedTab: function() {
		$('#tab_attached_assets').hide();
		if(this.tinyTab.selectedTab() == $('#tab_attached_assets')) {
			this.tinyTab.unselectTab();
		}
		$('#attached_assets').hide().removeClass("asset_list");
	},
	updateSelectedAssets: function(ids) {
	  $.each(['latest', 'bucket'], function() {
	    $("." + this + "_asset").each(function() { $(this).removeClass("selected"); });
	    var prefix = this;
	    $.each(ids, function() {
	      var asset = $("#" + prefix + "_asset_" + this);
	      if (asset.length > 0) { asset.addClass("selected"); }
	    });
	  });
	},
	selectedAssetIds: function() {
	  return $(".attached_asset").map(function(i, asset) {
	    return AssetWidget.assetId($(asset));
	  });
	},
  showAttachTools: function(id) {
		if(this.isEdit()) {
			$('#' + id + ' div').show();
		}
  },
  hideAttachTools: function(id) {
		$('#' + id + ' div').hide();
  },
	search: function(query) {
    if(!query) return;
    $('#search_assets_spinner').show();
    $.get(this.assetsUrl(), { query: escape(query), limit: 6, source: 'widget' });
	},
  upload: function(element) {
    if(!$("#asset_upload_frame").exist())
      $('body').append('');

    var parent = $(element).parent();
		var form = $(document.createElement("form"))
		             .attr("method", "post")
		             .attr("action", this.assetsUrl())
		             .attr("enctype", "multipart/form-data")
		             .attr("target", "asset_upload_frame")
		             .attr("style", "display:none");
		form.append('<input type="hidden" name="authenticity_token" value="'+this.authenticityToken+'"></input>')
		    .append('<input type="hidden" name="respond_to_parent" value="1"></input>')
        .append($(element));
    $('body').append(form);

    form.submit();
    form.remove();
    parent.prepend('<input id="asset-uploaded-data" name="assets[][data]" type="file" />');
  }
};

$(document).ready(function() {
  AssetWidget.tinyTab = new TinyTab("#assets_widget", "#panels");
  AssetWidget.authenticityToken = $("[name=authenticity_token]").val();
  AssetWidget.updateSelected();

  $("#assets_widget .attach_asset").live("click", function(event) { AssetWidget.attachAsset($(this)); });
  $("#assets_widget .detach_asset").live("click", function(event) { AssetWidget.detachAsset($(this)); });
  $("#assets_widget .asset").live("mouseover", function(event) { AssetWidget.showAttachTools($(this).attr("id")); });
  $("#assets_widget .asset").live("mouseout", function(event) { AssetWidget.hideAttachTools($(this).attr("id")); });

  $("#search_assets_button").click(function(event)   { AssetWidget.search($("#search_assets_query").val()); });
  $("#search_assets_query").keypress(function(event) { if(event.keyCode == 13) { AssetWidget.search($("#search_assets_query").val()); event.preventDefault(); } });
  $("#upload-assets-button").click(function(event)   { AssetWidget.upload($('#asset-uploaded-data')); });
});
<commit_msg>Assets widget tiny speed up and refactoring<commit_after>(function($) { $.fn.exist = function() { return this.length > 0; }; })(jQuery);

var TinyTab = $.klass({
  initialize: function(element, panels) {
    this.container = $(element);
    if(this.container.exist()) {
      var tabs = this.container.find(".tabs:first");
      // tabs.cleanWhitespace(); TODO find a jQuery equivalent method
      this.tabs = tabs.children();

      this.panels = this.container.find(".panel");
      this.showFirstPanel();
      this.selectFirstTab();
      var self = this;
      this.tabs.each(function() {
        $(this).bind("click", {self: self, element: this}, function(eventData) {
          var self = eventData.data.self;
          self.selectTab(eventData.data.element);
          eventData.stopPropagation();
        });
      });
    }
  },
  selectFirstTab: function() {
    tab = $(this.tabs[0]).is(":visible") ? this.tabs[0] : this.tabs[1];
    this.selectTab(tab);
  },
  selectTab: function(element) {
    this.tabs.removeClass("selected");
    $(element).addClass("selected");
    this.showPanel(element);
  },
  selectedTab: function() {
    return $($.grep(this.tabs, function(tab, i) {
      return $(tab).hasClass("selected");
    })[0]);
  },
  showFirstPanel: function() {
    this.showPanel(this.panels[0]);
  },
  showPanel: function(element) {
    this.panels.hide();
    $("#" + (element.id || $(element).attr("id")).replace("tab_", "")).show();
  }
});

var AssetWidget = {
  tinyTab: null,
  authenticityToken: null,
	siteId: function() {
		return location.href.match(/sites\/([0-9]+)\//)[1];
	},
	assetId: function(element) {
		return element.attr('id').match(/_(\d+)$/)[1];
	},
	memberId: function() {
		return location.href.match(/\/([0-9]+)\/(edit)/)[1];
	},
	assetsUrl: function() {
		return '/admin/sites/' + this.siteId() + '/assets';
	},
  isEdit: function() {
    return location.href.match(/\/[0-9]+\/edit#?$/)
  },
	collectionUrl: function(element) {
		return this.assetsUrl() + '/' + this.assetId(element) + '/contents';
	},
	memberUrl: function(element) {
		return this.collectionUrl(element) + '/' + this.memberId();
	},
  attachAsset: function(element, async) {
    if(!this.isAttached(element)) {
      $.ajax({
        url: this.collectionUrl(element),
				data: {
					content_id: this.memberId(),
					authenticity_token: this.authenticityToken
				},
        type: 'post',
        dataType: 'script',
        async: this.isAsync(async)
      });
		}
  },
  detachAsset: function(element, async) {
    if(this.isAttached(element)) {
      $.ajax({
        url: this.memberUrl(element),
        data: {
          _method: 'delete',
          authenticity_token: this.authenticityToken
        },
        type: 'post',
        dataType: 'script',
        async: this.isAsync(async)
      });
		}
  },
  isAsync: function(value) {
    return value === undefined;
  },
	isAttached: function(element) {
	  return $("#attached_asset_" + this.assetId(element)).exist();
	},
	updateSelected: function() {
		if(!$('#assets_widget').exist()) return;
		var selectedIds = this.selectedAssetIds();
		this.updateSelectedTab(selectedIds.length > 0);
		this.updateSelectedAssets(selectedIds);
	},
	updateSelectedTab: function(show) {
		show ? this.showSelectedTab() : this.hideSelectedTab();
		this.tinyTab.selectFirstTab();
	},
	showSelectedTab: function() {
		$('#tab_attached_assets').show();
		$("#attached_assets").addClass("asset_list");
	},
	hideSelectedTab: function() {
		$('#tab_attached_assets').hide();
		if(this.tinyTab.selectedTab() == $('#tab_attached_assets')) {
			this.tinyTab.unselectTab();
		}
		$('#attached_assets').hide().removeClass("asset_list");
	},
	updateSelectedAssets: function(ids) {
	  $.each(['latest', 'bucket'], function() {
	    $("." + this + "_asset").removeClass("selected");
	    var prefix = this;
	    $.each(ids, function() {
	      var asset = $("#" + prefix + "_asset_" + this);
	      if (asset.length > 0) { asset.addClass("selected"); }
	    });
	  });
	},
	selectedAssetIds: function() {
	  return $(".attached_asset").map(function(i, asset) {
	    return AssetWidget.assetId($(asset));
	  });
	},
  showAttachTools: function(id) {
		if(this.isEdit()) {
			$('#' + id + ' div').show();
		}
  },
  hideAttachTools: function(id) {
		$('#' + id + ' div').hide();
  },
	search: function(query) {
    if(!query) return;
    $('#search_assets_spinner').show();
    $.get(this.assetsUrl(), { query: escape(query), limit: 6, source: 'widget' });
	},
  upload: function(element) {
    if(!$("#asset_upload_frame").exist())
      $('body').append('');

    var parent = $(element).parent();
		var form = $(document.createElement("form"))
		             .attr("method", "post")
		             .attr("action", this.assetsUrl())
		             .attr("enctype", "multipart/form-data")
		             .attr("target", "asset_upload_frame")
		             .attr("style", "display:none");
		form.append('<input type="hidden" name="authenticity_token" value="'+this.authenticityToken+'"></input>')
		    .append('<input type="hidden" name="respond_to_parent" value="1"></input>')
        .append($(element));
    $('body').append(form);

    form.submit();
    form.remove();
    parent.prepend('<input id="asset-uploaded-data" name="assets[][data]" type="file" />');
  }
};

$(document).ready(function() {
  AssetWidget.tinyTab = new TinyTab("#assets_widget", "#panels");
  AssetWidget.authenticityToken = $("[name=authenticity_token]").val();
  AssetWidget.updateSelected();

  $("#assets_widget .attach_asset").live("click", function(event) { AssetWidget.attachAsset($(this)); });
  $("#assets_widget .detach_asset").live("click", function(event) { AssetWidget.detachAsset($(this)); });
  $("#assets_widget .asset").live("mouseover", function(event) { AssetWidget.showAttachTools($(this).attr("id")); });
  $("#assets_widget .asset").live("mouseout", function(event) { AssetWidget.hideAttachTools($(this).attr("id")); });

  $("#search_assets_button").click(function(event)   { AssetWidget.search($("#search_assets_query").val()); });
  $("#search_assets_query").keypress(function(event) { if(event.keyCode == 13) { AssetWidget.search($("#search_assets_query").val()); event.preventDefault(); } });
  $("#upload-assets-button").click(function(event)   { AssetWidget.upload($('#asset-uploaded-data')); });
});
<|endoftext|>