<commit_before>var countDownDate = addMinutes(new Date(), 2.016);

var x = setInterval(function () {
    var now = new Date().getTime();
    var distance = countDownDate - now;

    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    document.getElementById('timer').innerHTML = minutes + ':' + seconds.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false });

    if (distance < 1000) {
        clearInterval(x);
        saveScore();
        window.location = 'fail.html';
    }
}, 1000);

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes * 60000);
}
window.onload = function () {
    var challengeNumber = localStorage.getItem('challengeNumber');

    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");
    editor.setOptions({
        fontSize: "14pt"
    });

    switch (challengeNumber) {
        case '1':
            challengeOne();
            break;
        case '2':
            challengeTwo();
            break;
        case '3':
            challengeThree();
            break;
        default:
            return;
    }

}
function challengeOne() {
    document.getElementById("testButton").addEventListener("click", function () {
        var code = ace.edit("editor").getValue();

        var array = [2, 3, 7, 1, 5, 6, 0].toString();
        var result = eval(code + '\n challenge([' + array + ']);');
        var correctResult = [0, 1, 2, 3, 5, 6, 7];

        if (!Array.isArray(result)) {
            document.getElementById("warning").innerHTML = "Does not return an array!";
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(2000);
            return;
        }

        if (result.length == correctResult.length
            && result.every(function (element, index) { return element === correctResult[index]; })) {
            saveScore();
            window.location = 'success.html';
        } else {
            document.getElementById("warning").innerHTML = "INCORRECT";
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(2000);
        }
    });
}

function challengeTwo() {
    var editor = ace.edit("editor");
    editor.setOptions({
        readOnly: true,
        highlightActiveLine: false,
        highlightGutterLine: false
    });
    document.getElementById("testButton").addEventListener("click", function () {
        var answer = document.getElementById("answer").value;
        if (answer == "") {
            window.location = 'success.html';
        } else {
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(1800);
        }
    });
}
function challengeThree() {
    document.getElementById("testButton").addEventListener("click", function () {
        var code = ace.edit("editor").getValue();

        var str = "Bacon";
        var result = eval(code + '\n challenge(\"' + str + '\");');

        if (!(typeof (result) === "string")) {
            document.getElementById("warning").innerHTML = "Not of type string!";
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(2000);
            return;
        }

        if (result.length == str.length && result == "nocaB") {

            saveScore();
            window.location = 'success.html';
        } else {
            document.getElementById("warning").innerHTML = "INCORRECT";
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(2000);
        }
    });
}

function saveScore() {
    var name = localStorage.getItem('playerName');
    var time = document.getElementById('timer').innerHTML;
    var challengeNumber = localStorage.getItem('challengeNumber');
    var challenge;
    var scores;

    switch (challengeNumber) {
        case '1':
            scores = localStorage.getItem('challengeOneScores');
            challenge = 'challengeOneScores';
            break;
        case '2':
            scores = localStorage.getItem('challengeTwoScores');
            challenge = 'challengeTwoScores';
            break;
        case '3':
            scores = localStorage.getItem('challengeThreeScores');
            challenge = 'challengeThreeScores';
            break;
        default:
            return;
    }

    addRecords(scores, name, time, challenge);
}

function addRecords(scores, name, time, challenge) {
    if (scores === null || scores === 'null')
        scores = [];

    var scoresObj = Array.isArray(scores) ? scores : JSON.parse(scores);

    scoresObj.push({
        name: name,
        time: time
    });

    localStorage.setItem(challenge, JSON.stringify(scoresObj));
}<commit_msg>fixed scoring for challenge2<commit_after>var countDownDate = addMinutes(new Date(), 2.016);

var x = setInterval(function () {
    var now = new Date().getTime();
    var distance = countDownDate - now;

    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    document.getElementById('timer').innerHTML = minutes + ':' + seconds.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false });

    if (distance < 1000) {
        clearInterval(x);
        saveScore();
        window.location = 'fail.html';
    }
}, 1000);

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes * 60000);
}
window.onload = function () {
    var challengeNumber = localStorage.getItem('challengeNumber');

    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");
    editor.setOptions({
        fontSize: "14pt"
    });

    switch (challengeNumber) {
        case '1':
            challengeOne();
            break;
        case '2':
            challengeTwo();
            break;
        case '3':
            challengeThree();
            break;
        default:
            return;
    }

}
function challengeOne() {
    document.getElementById("testButton").addEventListener("click", function () {
        var code = ace.edit("editor").getValue();

        var array = [2, 3, 7, 1, 5, 6, 0].toString();
        var result = eval(code + '\n challenge([' + array + ']);');
        var correctResult = [0, 1, 2, 3, 5, 6, 7];

        if (!Array.isArray(result)) {
            document.getElementById("warning").innerHTML = "Does not return an array!";
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(2000);
            return;
        }

        if (result.length == correctResult.length
            && result.every(function (element, index) { return element === correctResult[index]; })) {
            saveScore();
            window.location = 'success.html';
        } else {
            document.getElementById("warning").innerHTML = "INCORRECT";
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(2000);
        }
    });
}

function challengeTwo() {
    var editor = ace.edit("editor");
    editor.setOptions({
        readOnly: true,
        highlightActiveLine: false,
        highlightGutterLine: false
    });
    document.getElementById("testButton").addEventListener("click", function () {
        var answer = document.getElementById("answer").value;
        if (answer == "") {
            window.location = 'success.html';
        } else {
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(1800);
            return;
        }
        saveScore();
    });
}
function challengeThree() {
    document.getElementById("testButton").addEventListener("click", function () {
        var code = ace.edit("editor").getValue();

        var str = "Bacon";
        var result = eval(code + '\n challenge(\"' + str + '\");');

        if (!(typeof (result) === "string")) {
            document.getElementById("warning").innerHTML = "Not of type string!";
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(2000);
            return;
        }

        if (result.length == str.length && result == "nocaB") {

            saveScore();
            window.location = 'success.html';
        } else {
            document.getElementById("warning").innerHTML = "INCORRECT";
            document.getElementById("warning").setAttribute("style", "display:visible")
            $("#warning").fadeOut(2000);
        }
    });
}

function saveScore() {
    var name = localStorage.getItem('playerName');
    var time = document.getElementById('timer').innerHTML;
    var challengeNumber = localStorage.getItem('challengeNumber');
    var challenge;
    var scores;

    switch (challengeNumber) {
        case '1':
            scores = localStorage.getItem('challengeOneScores');
            challenge = 'challengeOneScores';
            break;
        case '2':
            scores = localStorage.getItem('challengeTwoScores');
            challenge = 'challengeTwoScores';
            break;
        case '3':
            scores = localStorage.getItem('challengeThreeScores');
            challenge = 'challengeThreeScores';
            break;
        default:
            return;
    }

    addRecords(scores, name, time, challenge);
}

function addRecords(scores, name, time, challenge) {
    if (scores === null || scores === 'null')
        scores = [];

    var scoresObj = Array.isArray(scores) ? scores : JSON.parse(scores);

    scoresObj.push({
        name: name,
        time: time
    });

    localStorage.setItem(challenge, JSON.stringify(scoresObj));
}<|endoftext|>


<commit_before>import Position from '../mixin/position';
import Togglable from '../mixin/togglable';
import {addClass, Animation, attr, css, includes, isTouch, MouseTracker, offset, on, once, pointerEnter, pointerLeave, pointInRect, query, removeClasses, toggleClass, trigger, within} from 'uikit-util';

let active;

export default {

    mixins: [Position, Togglable],

    args: 'pos',

    props: {
        mode: 'list',
        toggle: Boolean,
        boundary: Boolean,
        boundaryAlign: Boolean,
        delayShow: Number,
        delayHide: Number,
        clsDrop: String
    },

    data: {
        mode: ['click', 'hover'],
        toggle: '- *',
        boundary: window,
        boundaryAlign: false,
        delayShow: 0,
        delayHide: 800,
        clsDrop: false,
        hoverIdle: 200,
        animation: ['uk-animation-fade'],
        cls: 'uk-open'
    },

    computed: {

        boundary({boundary}, $el) {
            return query(boundary, $el);
        },

        clsDrop({clsDrop}) {
            return clsDrop || `uk-${this.$options.name}`;
        },

        clsPos() {
            return this.clsDrop;
        }

    },

    created() {
        this.tracker = new MouseTracker();
    },

    connected() {

        addClass(this.$el, this.clsDrop);

        const {toggle} = this.$props;
        this.toggle = toggle && this.$create('toggle', query(toggle, this.$el), {
            target: this.$el,
            mode: this.mode
        });

        !this.toggle && trigger(this.$el, 'updatearia');

    },

    events: [

        {

            name: 'click',

            delegate() {
                return `.${this.clsDrop}-close`;
            },

            handler(e) {
                e.preventDefault();
                this.hide(false);
            }

        },

        {

            name: 'click',

            delegate() {
                return 'a[href^="#"]';
            },

            handler({defaultPrevented, current: {hash}}) {
                if (!defaultPrevented && hash && !within(hash, this.$el)) {
                    this.hide(false);
                }
            }

        },

        {

            name: 'beforescroll',

            handler() {
                this.hide(false);
            }

        },

        {

            name: 'toggle',

            self: true,

            handler(e, toggle) {

                e.preventDefault();

                if (this.isToggled()) {
                    this.hide(false);
                } else {
                    this.show(toggle, false);
                }
            }

        },

        {

            name: pointerEnter,

            filter() {
                return includes(this.mode, 'hover');
            },

            handler(e) {

                if (isTouch(e)) {
                    return;
                }

                if (active
                    && active !== this
                    && active.toggle
                    && includes(active.toggle.mode, 'hover')
                    && !within(e.target, active.toggle.$el)
                    && !pointInRect({x: e.pageX, y: e.pageY}, offset(active.$el))
                ) {
                    active.hide(false);
                }

                e.preventDefault();
                this.show(this.toggle);
            }

        },

        {

            name: 'toggleshow',

            handler(e, toggle) {

                if (toggle && !includes(toggle.target, this.$el)) {
                    return;
                }

                e.preventDefault();
                this.show(toggle || this.toggle);
            }

        },

        {

            name: `togglehide ${pointerLeave}`,

            handler(e, toggle) {

                if (isTouch(e) || toggle && !includes(toggle.target, this.$el)) {
                    return;
                }

                e.preventDefault();

                if (this.toggle && includes(this.toggle.mode, 'hover')) {
                    this.hide();
                }
            }

        },

        {

            name: 'beforeshow',

            self: true,

            handler() {
                this.clearTimers();
                Animation.cancel(this.$el);
                this.position();
            }

        },

        {

            name: 'show',

            self: true,

            handler() {
                this.tracker.init();
                trigger(this.$el, 'updatearia');
                registerEvent();
            }

        },

        {

            name: 'beforehide',

            self: true,

            handler() {
                this.clearTimers();
            }

        },

        {

            name: 'hide',

            handler({target}) {

                if (this.$el !== target) {
                    active = active === null && within(target, this.$el) && this.isToggled() ? this : active;
                    return;
                }

                active = this.isActive() ? null : active;
                trigger(this.$el, 'updatearia');
                this.tracker.cancel();
            }

        },

        {

            name: 'updatearia',

            self: true,

            handler(e, toggle) {

                e.preventDefault();

                this.updateAria(this.$el);

                if (toggle || this.toggle) {
                    attr((toggle || this.toggle).$el, 'aria-expanded', this.isToggled() ? 'true' : 'false');
                    toggleClass(this.toggle.$el, this.cls, this.isToggled());
                }
            }
        }

    ],

    update: {

        write() {

            if (this.isToggled() && !Animation.inProgress(this.$el)) {
                this.position();
            }

        },

        events: ['resize']

    },

    methods: {

        show(toggle, delay = true) {

            const show = () => !this.isToggled() && this.toggleElement(this.$el, true);
            const tryShow = () => {

                this.toggle = toggle || this.toggle;

                this.clearTimers();

                if (this.isActive()) {
                    return;
                } else if (delay && active && active !== this && active.isDelaying) {
                    this.showTimer = setTimeout(this.show, 10);
                    return;
                } else if (this.isParentOf(active)) {

                    if (active.hideTimer) {
                        active.hide(false);
                    } else {
                        return;
                    }

                } else if (active && this.isChildOf(active)) {

                    active.clearTimers();

                } else if (active && !this.isChildOf(active) && !this.isParentOf(active)) {

                    let prev;
                    while (active && active !== prev && !this.isChildOf(active)) {
                        prev = active;
                        active.hide(false);
                    }

                }

                if (delay && this.delayShow) {
                    this.showTimer = setTimeout(show, this.delayShow);
                } else {
                    show();
                }

                active = this;
            };

            if (toggle && this.toggle && toggle.$el !== this.toggle.$el) {

                once(this.$el, 'hide', tryShow);
                this.hide(false);

            } else {
                tryShow();
            }
        },

        hide(delay = true) {

            const hide = () => this.toggleNow(this.$el, false);

            this.clearTimers();

            this.isDelaying = this.tracker.movesTo(this.$el);

            if (delay && this.isDelaying) {
                this.hideTimer = setTimeout(this.hide, this.hoverIdle);
            } else if (delay && this.delayHide) {
                this.hideTimer = setTimeout(hide, this.delayHide);
            } else {
                hide();
            }
        },

        clearTimers() {
            clearTimeout(this.showTimer);
            clearTimeout(this.hideTimer);
            this.showTimer = null;
            this.hideTimer = null;
            this.isDelaying = false;
        },

        isActive() {
            return active === this;
        },

        isChildOf(drop) {
            return drop && drop !== this && within(this.$el, drop.$el);
        },

        isParentOf(drop) {
            return drop && drop !== this && within(drop.$el, this.$el);
        },

        position() {

            removeClasses(this.$el, `${this.clsDrop}-(stack|boundary)`);
            css(this.$el, {top: '', left: '', display: 'block'});
            toggleClass(this.$el, `${this.clsDrop}-boundary`, this.boundaryAlign);

            const boundary = offset(this.boundary);
            const alignTo = this.boundaryAlign ? boundary : offset(this.toggle.$el);

            if (this.align === 'justify') {
                const prop = this.getAxis() === 'y' ? 'width' : 'height';
                css(this.$el, prop, alignTo[prop]);
            } else if (this.$el.offsetWidth > Math.max(boundary.right - alignTo.left, alignTo.right - boundary.left)) {
                addClass(this.$el, `${this.clsDrop}-stack`);
            }

            this.positionAt(this.$el, this.boundaryAlign ? this.boundary : this.toggle.$el, this.boundary);

            css(this.$el, 'display', '');

        }

    }

};

let registered;

function registerEvent() {

    if (registered) {
        return;
    }

    registered = true;
    on(document, 'click', ({defaultPrevented, target}) => {
        let prev;
        while (!defaultPrevented && active && active !== prev && !within(target, active.$el) && !(active.toggle && within(target, active.toggle.$el))) {
            prev = active;
            active.hide(false);
        }
    });
}
<commit_msg>fix: do not close dropdown in the same click event, that triggered the dropdown<commit_after>import Position from '../mixin/position';
import Togglable from '../mixin/togglable';
import {addClass, Animation, attr, css, includes, isTouch, MouseTracker, offset, on, once, pointerEnter, pointerLeave, pointInRect, query, removeClasses, toggleClass, trigger, within} from 'uikit-util';

let active;

export default {

    mixins: [Position, Togglable],

    args: 'pos',

    props: {
        mode: 'list',
        toggle: Boolean,
        boundary: Boolean,
        boundaryAlign: Boolean,
        delayShow: Number,
        delayHide: Number,
        clsDrop: String
    },

    data: {
        mode: ['click', 'hover'],
        toggle: '- *',
        boundary: window,
        boundaryAlign: false,
        delayShow: 0,
        delayHide: 800,
        clsDrop: false,
        hoverIdle: 200,
        animation: ['uk-animation-fade'],
        cls: 'uk-open'
    },

    computed: {

        boundary({boundary}, $el) {
            return query(boundary, $el);
        },

        clsDrop({clsDrop}) {
            return clsDrop || `uk-${this.$options.name}`;
        },

        clsPos() {
            return this.clsDrop;
        }

    },

    created() {
        this.tracker = new MouseTracker();
    },

    connected() {

        addClass(this.$el, this.clsDrop);

        const {toggle} = this.$props;
        this.toggle = toggle && this.$create('toggle', query(toggle, this.$el), {
            target: this.$el,
            mode: this.mode
        });

        !this.toggle && trigger(this.$el, 'updatearia');

    },

    events: [

        {

            name: 'click',

            delegate() {
                return `.${this.clsDrop}-close`;
            },

            handler(e) {
                e.preventDefault();
                this.hide(false);
            }

        },

        {

            name: 'click',

            delegate() {
                return 'a[href^="#"]';
            },

            handler({defaultPrevented, current: {hash}}) {
                if (!defaultPrevented && hash && !within(hash, this.$el)) {
                    this.hide(false);
                }
            }

        },

        {

            name: 'beforescroll',

            handler() {
                this.hide(false);
            }

        },

        {

            name: 'toggle',

            self: true,

            handler(e, toggle) {

                e.preventDefault();

                if (this.isToggled()) {
                    this.hide(false);
                } else {
                    this.show(toggle, false);
                }
            }

        },

        {

            name: pointerEnter,

            filter() {
                return includes(this.mode, 'hover');
            },

            handler(e) {

                if (isTouch(e)) {
                    return;
                }

                if (active
                    && active !== this
                    && active.toggle
                    && includes(active.toggle.mode, 'hover')
                    && !within(e.target, active.toggle.$el)
                    && !pointInRect({x: e.pageX, y: e.pageY}, offset(active.$el))
                ) {
                    active.hide(false);
                }

                e.preventDefault();
                this.show(this.toggle);
            }

        },

        {

            name: 'toggleshow',

            handler(e, toggle) {

                if (toggle && !includes(toggle.target, this.$el)) {
                    return;
                }

                e.preventDefault();
                this.show(toggle || this.toggle);
            }

        },

        {

            name: `togglehide ${pointerLeave}`,

            handler(e, toggle) {

                if (isTouch(e) || toggle && !includes(toggle.target, this.$el)) {
                    return;
                }

                e.preventDefault();

                if (this.toggle && includes(this.toggle.mode, 'hover')) {
                    this.hide();
                }
            }

        },

        {

            name: 'beforeshow',

            self: true,

            handler() {
                this.clearTimers();
                Animation.cancel(this.$el);
                this.position();
            }

        },

        {

            name: 'show',

            self: true,

            handler() {
                this.tracker.init();
                trigger(this.$el, 'updatearia');

                // If triggered from an click event handler, delay adding the click handler
                const off = delayOn(document, 'click', ({defaultPrevented, target}) => {
                    if (!defaultPrevented && !within(target, this.$el) && !(this.toggle && within(target, this.toggle.$el))) {
                        this.hide(false);
                    }
                });

                once(this.$el, 'hide', off, {self: true});
            }

        },

        {

            name: 'beforehide',

            self: true,

            handler() {
                this.clearTimers();
            }

        },

        {

            name: 'hide',

            handler({target}) {

                if (this.$el !== target) {
                    active = active === null && within(target, this.$el) && this.isToggled() ? this : active;
                    return;
                }

                active = this.isActive() ? null : active;
                trigger(this.$el, 'updatearia');
                this.tracker.cancel();
            }

        },

        {

            name: 'updatearia',

            self: true,

            handler(e, toggle) {

                e.preventDefault();

                this.updateAria(this.$el);

                if (toggle || this.toggle) {
                    attr((toggle || this.toggle).$el, 'aria-expanded', this.isToggled());
                    toggleClass(this.toggle.$el, this.cls, this.isToggled());
                }
            }
        }

    ],

    update: {

        write() {

            if (this.isToggled() && !Animation.inProgress(this.$el)) {
                this.position();
            }

        },

        events: ['resize']

    },

    methods: {

        show(toggle, delay = true) {

            const show = () => !this.isToggled() && this.toggleElement(this.$el, true);
            const tryShow = () => {

                this.toggle = toggle || this.toggle;

                this.clearTimers();

                if (this.isActive()) {
                    return;
                } else if (delay && active && active !== this && active.isDelaying) {
                    this.showTimer = setTimeout(this.show, 10);
                    return;
                } else if (this.isParentOf(active)) {

                    if (active.hideTimer) {
                        active.hide(false);
                    } else {
                        return;
                    }

                } else if (this.isChildOf(active)) {

                    active.clearTimers();

                } else if (active && !this.isChildOf(active) && !this.isParentOf(active)) {

                    let prev;
                    while (active && active !== prev && !this.isChildOf(active)) {
                        prev = active;
                        active.hide(false);
                    }

                }

                if (delay && this.delayShow) {
                    this.showTimer = setTimeout(show, this.delayShow);
                } else {
                    show();
                }

                active = this;
            };

            if (toggle && this.toggle && toggle.$el !== this.toggle.$el) {

                once(this.$el, 'hide', tryShow);
                this.hide(false);

            } else {
                tryShow();
            }
        },

        hide(delay = true) {

            const hide = () => this.toggleNow(this.$el, false);

            this.clearTimers();

            this.isDelaying = this.tracker.movesTo(this.$el);

            if (delay && this.isDelaying) {
                this.hideTimer = setTimeout(this.hide, this.hoverIdle);
            } else if (delay && this.delayHide) {
                this.hideTimer = setTimeout(hide, this.delayHide);
            } else {
                hide();
            }
        },

        clearTimers() {
            clearTimeout(this.showTimer);
            clearTimeout(this.hideTimer);
            this.showTimer = null;
            this.hideTimer = null;
            this.isDelaying = false;
        },

        isActive() {
            return active === this;
        },

        isChildOf(drop) {
            return drop && drop !== this && within(this.$el, drop.$el);
        },

        isParentOf(drop) {
            return drop && drop !== this && within(drop.$el, this.$el);
        },

        position() {

            removeClasses(this.$el, `${this.clsDrop}-(stack|boundary)`);
            css(this.$el, {top: '', left: '', display: 'block'});
            toggleClass(this.$el, `${this.clsDrop}-boundary`, this.boundaryAlign);

            const boundary = offset(this.boundary);
            const alignTo = this.boundaryAlign ? boundary : offset(this.toggle.$el);

            if (this.align === 'justify') {
                const prop = this.getAxis() === 'y' ? 'width' : 'height';
                css(this.$el, prop, alignTo[prop]);
            } else if (this.$el.offsetWidth > Math.max(boundary.right - alignTo.left, alignTo.right - boundary.left)) {
                addClass(this.$el, `${this.clsDrop}-stack`);
            }

            this.positionAt(this.$el, this.boundaryAlign ? this.boundary : this.toggle.$el, this.boundary);

            css(this.$el, 'display', '');

        }

    }

};

function delayOn(el, type, fn) {
    let off = once(el, type, () =>
        off = on(el, type, fn)
    , true);
    return () => off();
}
<|endoftext|>


<commit_before>// Global Ajax Setup
var globalAjaxOptions = {};
$.ajaxSetup = function (options) {
    if (options.type) options.method = options.type;
    for (var option in options) {
        globalAjaxOptions[option]  = options[option];
    }
};

// Ajax
var _jsonpRequests = 0;
$.ajax = function (options) {
    var defaults = {
        method: 'GET',
        data: false,
        async: true,
        cache: true,
        user: '',
        password: '',
        headers: {},
        xhrFields: {},
        statusCode: {},
        processData: true,
        dataType: 'text',
        contentType: 'application/x-www-form-urlencoded',
        timeout: 0
    };
    var callbacks = ['beforeSend', 'error', 'complete', 'success', 'statusCode'];

    //For jQuery guys
    if (options.type) options.method = options.type;

    // Merge global and defaults
    for (var globalOption in globalAjaxOptions) {
        if (callbacks.indexOf(globalOption) < 0) defaults[globalOption] = globalAjaxOptions[globalOption];
    }
    // Function to run XHR callbacks and events
    function fireAjaxCallback (eventName, eventData, callbackName) {
        var a = arguments;
        if (eventName) $(document).trigger(eventName, eventData);
        if (callbackName) {
            // Global callback
            if (callbackName in globalAjaxOptions) globalAjaxOptions[callbackName](a[3], a[4], a[5], a[6]);
            // Options callback
            if (options[callbackName]) options[callbackName](a[3], a[4], a[5], a[6]);
        }
    }

    // Merge options and defaults
    for (var prop in defaults) {
        if (!(prop in options)) options[prop] = defaults[prop];
    }

    // Default URL
    if (!options.url) {
        options.url = window.location.toString();
    }
    // UC method
    var _method = options.method.toUpperCase();
    // Data to modify GET URL
    if ((_method === 'GET' || _method === 'HEAD') && options.data) {
        var stringData;
        if (typeof options.data === 'string') {
            // Should be key=value string
            if (options.data.indexOf('?') >= 0) stringData = options.data.split('?')[1];
            else stringData = options.data;
        }
        else {
            // Should be key=value object
            stringData = $.serializeObject(options.data);
        }
        if (options.url.indexOf('?') >= 0) options.url += '&' + stringData;
        else options.url += '?' + stringData;
    }
    // JSONP
    if (options.dataType === 'json' && options.url.indexOf('callback=') >= 0) {

        var callbackName = 'f7jsonp_' + Date.now() + (_jsonpRequests++);
        var requestUrl, abortTimeout;
        var callbackSplit = options.url.split('callback=');
        if (callbackSplit[1].indexOf('&') >= 0) {
            var addVars = callbackSplit[1].split('&').filter(function (el) { return el.indexOf('=') > 0; }).join('&');
            requestUrl = callbackSplit[0] + 'callback=' + callbackName + (addVars.length > 0 ? '&' + addVars : '');
        }
        else {
            requestUrl = callbackSplit[0] + 'callback=' + callbackName;
        }

        // Create script
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.onerror = function() {
            clearTimeout(abortTimeout);
            fireAjaxCallback(undefined, undefined, 'error', null, 'scripterror');
        };
        script.src = requestUrl;

        // Handler
        window[callbackName] = function (data) {
            clearTimeout(abortTimeout);
            fireAjaxCallback(undefined, undefined, 'success', data);
            script.parentNode.removeChild(script);
            script = null;
            delete window[callbackName];
        };
        document.querySelector('head').appendChild(script);

        if (options.timeout > 0) {
            abortTimeout = setTimeout(function () {
                script.parentNode.removeChild(script);
                script = null;
                fireAjaxCallback(undefined, undefined, 'error', null, 'timeout');
            }, options.timeout);
        }

        return;
    }

    // Cache for GET/HEAD requests
    if (_method === 'GET' || _method === 'HEAD') {
        if (options.cache === false) options.url += ('_nocache=' + Date.now());
    }

    // Create XHR
    var xhr = new XMLHttpRequest();

    // Save Request URL
    xhr.requestUrl = options.url;

    // Open XHR
    xhr.open(_method, options.url, options.async, options.user, options.password);

    // Create POST Data
    var postData = null;

    if ((_method === 'POST' || _method === 'PUT') && options.data) {
        if (options.processData) {
            var postDataInstances = [ArrayBuffer, Blob, Document, FormData];
            // Post Data
            if (postDataInstances.indexOf(options.data.constructor) >= 0) {
                postData = options.data;
            }
            else {
                // POST Headers
                var boundary = '---------------------------' + Date.now().toString(16);

                if (options.contentType === 'multipart\/form-data') {
                    xhr.setRequestHeader('Content-Type', 'multipart\/form-data; boundary=' + boundary);
                }
                else {
                    xhr.setRequestHeader('Content-Type', options.contentType);
                }
                postData = '';
                var _data = $.serializeObject(options.data);
                if (options.contentType === 'multipart\/form-data') {
                    boundary = '---------------------------' + Date.now().toString(16);
                    _data = _data.split('&');
                    var _newData = [];
                    for (var i = 0; i < _data.length; i++) {
                        _newData.push('Content-Disposition: form-data; name="' + _data[i].split('=')[0] + '"\r\n\r\n' + _data[i].split('=')[1] + '\r\n');
                    }
                    postData = '--' + boundary + '\r\n' + _newData.join('--' + boundary + '\r\n') + '--' + boundary + '--\r\n';
                }
                else {
                    postData = options.contentType === 'application/x-www-form-urlencoded' ? _data : _data.replace(/&/g, '\r\n');
                }
            }
        }
        else {
            postData = options.data;
        }

    }

    // Additional headers
    if (options.headers) {
        for (var header in options.headers) {
            xhr.setRequestHeader(header, options.headers[header]);
        }
    }

    // Check for crossDomain
    if (typeof options.crossDomain === 'undefined') {
        options.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(options.url) && RegExp.$2 !== window.location.host;
    }

    if (!options.crossDomain) {
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    }

    if (options.xhrFields) {
        for (var field in options.xhrFields) {
            xhr[field] = options.xhrFields[field];
        }
    }

    var xhrTimeout;
    // Handle XHR
    xhr.onload = function (e) {
        if (xhrTimeout) clearTimeout(xhrTimeout);
        if (xhr.status === 200 || xhr.status === 0) {
            var isSuccess, responseData;
            if (options.dataType === 'json') {
                try {
                    responseData = JSON.parse(xhr.responseText);
                    fireAjaxCallback('ajaxSuccess', {xhr: xhr}, 'success', responseData, xhr.status, xhr);
                }
                catch (e) {
                    fireAjaxCallback('ajaxError', {xhr: xhr, parseerror: true}, 'error', xhr, 'parseerror');
                }
            }
            else {
                fireAjaxCallback('ajaxSuccess', {xhr: xhr}, 'success', xhr.responseText, xhr.status, xhr);
            }
        }
        else {
            fireAjaxCallback('ajaxError', {xhr: xhr}, 'error', xhr, xhr.status);
        }
        if (options.statusCode) {
            if (globalAjaxOptions.statusCode && globalAjaxOptions.statusCode[xhr.status]) globalAjaxOptions.statusCode[xhr.status](xhr);
            if (options.statusCode[xhr.status]) options.statusCode[xhr.status](xhr);
        }
        fireAjaxCallback('ajaxComplete', {xhr: xhr}, 'complete', xhr, xhr.status);
    };

    xhr.onerror = function (e) {
        if (xhrTimeout) clearTimeout(xhrTimeout);
        fireAjaxCallback('ajaxError', {xhr: xhr}, 'error', xhr, xhr.status);
    };

    // Ajax start callback
    fireAjaxCallback('ajaxStart', {xhr: xhr}, 'start', xhr);
    fireAjaxCallback(undefined, undefined, 'beforeSend', xhr);

    // Send XHR
    xhr.send(postData);

    // Timeout
    if (options.timeout > 0) {
        xhrTimeout = setTimeout(function () {
            xhr.abort();
            fireAjaxCallback('ajaxError', {xhr: xhr, timeout: true}, 'error', xhr, 'timeout');
            fireAjaxCallback('complete', {xhr: xhr, timeout: true}, 'complete', xhr, 'timeout');
        }, options.timeout);
    }

    // Return XHR object
    return xhr;
};
// Shrotcuts
(function () {
    var methods = ('get post getJSON').split(' ');
    function createMethod(method) {
        $[method] = function (url, data, success) {
            return $.ajax({
                url: url,
                method: method === 'post' ? 'POST' : 'GET',
                data: typeof data === 'function' ? undefined : data,
                success: typeof data === 'function' ? data : success,
                dataType: method === 'getJSON' ? 'json' : undefined
            });
        };
    }
    for (var i = 0; i < methods.length; i++) {
        createMethod(methods[i]);
    }
})();<commit_msg>Fix cache and ajaxComplete callback<commit_after>// Global Ajax Setup
var globalAjaxOptions = {};
$.ajaxSetup = function (options) {
    if (options.type) options.method = options.type;
    for (var option in options) {
        globalAjaxOptions[option]  = options[option];
    }
};

// Ajax
var _jsonpRequests = 0;
$.ajax = function (options) {
    var defaults = {
        method: 'GET',
        data: false,
        async: true,
        cache: true,
        user: '',
        password: '',
        headers: {},
        xhrFields: {},
        statusCode: {},
        processData: true,
        dataType: 'text',
        contentType: 'application/x-www-form-urlencoded',
        timeout: 0
    };
    var callbacks = ['beforeSend', 'error', 'complete', 'success', 'statusCode'];

    //For jQuery guys
    if (options.type) options.method = options.type;

    // Merge global and defaults
    for (var globalOption in globalAjaxOptions) {
        if (callbacks.indexOf(globalOption) < 0) defaults[globalOption] = globalAjaxOptions[globalOption];
    }
    // Function to run XHR callbacks and events
    function fireAjaxCallback (eventName, eventData, callbackName) {
        var a = arguments;
        if (eventName) $(document).trigger(eventName, eventData);
        if (callbackName) {
            // Global callback
            if (callbackName in globalAjaxOptions) globalAjaxOptions[callbackName](a[3], a[4], a[5], a[6]);
            // Options callback
            if (options[callbackName]) options[callbackName](a[3], a[4], a[5], a[6]);
        }
    }

    // Merge options and defaults
    for (var prop in defaults) {
        if (!(prop in options)) options[prop] = defaults[prop];
    }

    // Default URL
    if (!options.url) {
        options.url = window.location.toString();
    }
    // UC method
    var _method = options.method.toUpperCase();
    // Data to modify GET URL
    if ((_method === 'GET' || _method === 'HEAD') && options.data) {
        var stringData;
        if (typeof options.data === 'string') {
            // Should be key=value string
            if (options.data.indexOf('?') >= 0) stringData = options.data.split('?')[1];
            else stringData = options.data;
        }
        else {
            // Should be key=value object
            stringData = $.serializeObject(options.data);
        }
        if (options.url.indexOf('?') >= 0) options.url += '&' + stringData;
        else options.url += '?' + stringData;
    }
    // JSONP
    if (options.dataType === 'json' && options.url.indexOf('callback=') >= 0) {

        var callbackName = 'f7jsonp_' + Date.now() + (_jsonpRequests++);
        var requestUrl, abortTimeout;
        var callbackSplit = options.url.split('callback=');
        if (callbackSplit[1].indexOf('&') >= 0) {
            var addVars = callbackSplit[1].split('&').filter(function (el) { return el.indexOf('=') > 0; }).join('&');
            requestUrl = callbackSplit[0] + 'callback=' + callbackName + (addVars.length > 0 ? '&' + addVars : '');
        }
        else {
            requestUrl = callbackSplit[0] + 'callback=' + callbackName;
        }

        // Create script
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.onerror = function() {
            clearTimeout(abortTimeout);
            fireAjaxCallback(undefined, undefined, 'error', null, 'scripterror');
        };
        script.src = requestUrl;

        // Handler
        window[callbackName] = function (data) {
            clearTimeout(abortTimeout);
            fireAjaxCallback(undefined, undefined, 'success', data);
            script.parentNode.removeChild(script);
            script = null;
            delete window[callbackName];
        };
        document.querySelector('head').appendChild(script);

        if (options.timeout > 0) {
            abortTimeout = setTimeout(function () {
                script.parentNode.removeChild(script);
                script = null;
                fireAjaxCallback(undefined, undefined, 'error', null, 'timeout');
            }, options.timeout);
        }

        return;
    }

    // Cache for GET/HEAD requests
    if (_method === 'GET' || _method === 'HEAD') {
        if (options.cache === false) {
            if (options.url.indexOf('?') >= 0) {
                options.url += ('&_nocache=' + Date.now());
            }
            else {
                options.url += ('?_nocache=' + Date.now());
            }
        }
    }

    // Create XHR
    var xhr = new XMLHttpRequest();

    // Save Request URL
    xhr.requestUrl = options.url;

    // Open XHR
    xhr.open(_method, options.url, options.async, options.user, options.password);

    // Create POST Data
    var postData = null;

    if ((_method === 'POST' || _method === 'PUT') && options.data) {
        if (options.processData) {
            var postDataInstances = [ArrayBuffer, Blob, Document, FormData];
            // Post Data
            if (postDataInstances.indexOf(options.data.constructor) >= 0) {
                postData = options.data;
            }
            else {
                // POST Headers
                var boundary = '---------------------------' + Date.now().toString(16);

                if (options.contentType === 'multipart\/form-data') {
                    xhr.setRequestHeader('Content-Type', 'multipart\/form-data; boundary=' + boundary);
                }
                else {
                    xhr.setRequestHeader('Content-Type', options.contentType);
                }
                postData = '';
                var _data = $.serializeObject(options.data);
                if (options.contentType === 'multipart\/form-data') {
                    boundary = '---------------------------' + Date.now().toString(16);
                    _data = _data.split('&');
                    var _newData = [];
                    for (var i = 0; i < _data.length; i++) {
                        _newData.push('Content-Disposition: form-data; name="' + _data[i].split('=')[0] + '"\r\n\r\n' + _data[i].split('=')[1] + '\r\n');
                    }
                    postData = '--' + boundary + '\r\n' + _newData.join('--' + boundary + '\r\n') + '--' + boundary + '--\r\n';
                }
                else {
                    postData = options.contentType === 'application/x-www-form-urlencoded' ? _data : _data.replace(/&/g, '\r\n');
                }
            }
        }
        else {
            postData = options.data;
        }

    }

    // Additional headers
    if (options.headers) {
        for (var header in options.headers) {
            xhr.setRequestHeader(header, options.headers[header]);
        }
    }

    // Check for crossDomain
    if (typeof options.crossDomain === 'undefined') {
        options.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(options.url) && RegExp.$2 !== window.location.host;
    }

    if (!options.crossDomain) {
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    }

    if (options.xhrFields) {
        for (var field in options.xhrFields) {
            xhr[field] = options.xhrFields[field];
        }
    }

    var xhrTimeout;
    // Handle XHR
    xhr.onload = function (e) {
        if (xhrTimeout) clearTimeout(xhrTimeout);
        if (xhr.status === 200 || xhr.status === 0) {
            var isSuccess, responseData;
            if (options.dataType === 'json') {
                try {
                    responseData = JSON.parse(xhr.responseText);
                    fireAjaxCallback('ajaxSuccess', {xhr: xhr}, 'success', responseData, xhr.status, xhr);
                }
                catch (e) {
                    fireAjaxCallback('ajaxError', {xhr: xhr, parseerror: true}, 'error', xhr, 'parseerror');
                }
            }
            else {
                fireAjaxCallback('ajaxSuccess', {xhr: xhr}, 'success', xhr.responseText, xhr.status, xhr);
            }
        }
        else {
            fireAjaxCallback('ajaxError', {xhr: xhr}, 'error', xhr, xhr.status);
        }
        if (options.statusCode) {
            if (globalAjaxOptions.statusCode && globalAjaxOptions.statusCode[xhr.status]) globalAjaxOptions.statusCode[xhr.status](xhr);
            if (options.statusCode[xhr.status]) options.statusCode[xhr.status](xhr);
        }
        fireAjaxCallback('ajaxComplete', {xhr: xhr}, 'complete', xhr, xhr.status);
    };

    xhr.onerror = function (e) {
        if (xhrTimeout) clearTimeout(xhrTimeout);
        fireAjaxCallback('ajaxError', {xhr: xhr}, 'error', xhr, xhr.status);
    };

    // Ajax start callback
    fireAjaxCallback('ajaxStart', {xhr: xhr}, 'start', xhr);
    fireAjaxCallback(undefined, undefined, 'beforeSend', xhr);

    // Send XHR
    xhr.send(postData);

    // Timeout
    if (options.timeout > 0) {
        xhrTimeout = setTimeout(function () {
            xhr.abort();
            fireAjaxCallback('ajaxError', {xhr: xhr, timeout: true}, 'error', xhr, 'timeout');
            fireAjaxCallback('ajaxComplete', {xhr: xhr, timeout: true}, 'complete', xhr, 'timeout');
        }, options.timeout);
    }

    // Return XHR object
    return xhr;
};
// Shrotcuts
(function () {
    var methods = ('get post getJSON').split(' ');
    function createMethod(method) {
        $[method] = function (url, data, success) {
            return $.ajax({
                url: url,
                method: method === 'post' ? 'POST' : 'GET',
                data: typeof data === 'function' ? undefined : data,
                success: typeof data === 'function' ? data : success,
                dataType: method === 'getJSON' ? 'json' : undefined
            });
        };
    }
    for (var i = 0; i < methods.length; i++) {
        createMethod(methods[i]);
    }
})();<|endoftext|>


<commit_before>import { $ } from './libs/helpers';

document.addEventListener('DOMContentLoaded', () => {
  window.stellar = {};
  window.stellar.boot = new Promise(resolve => {
    chrome.storage.local.get(
      [
        'nextImage',
        'pausedImage',
        'cloudService',
        'dropbox',
        'onedrive',
        'forecast',
      ],
      d => {
        const data = { ...d };

        window.stellar.nextImage = data.nextImage;

        chrome.storage.sync.get(res => {
          const { photoFrequency } = res;
          const { pausedImage } = data;

          if (photoFrequency === 'paused') {
            data.nextImage = pausedImage;
          }

          const { nextImage } = data;

          if (nextImage) {
            const body = $('body');
            body.style.backgroundImage = `url(${nextImage.base64})`;
          }

          const result = Object.assign(res, data);
          resolve(result);
        });
      }
    );
  });

  chrome.runtime.sendMessage({ command: 'load-data' });

  const loadCss = url =>
    new Promise((resolve, reject) => {
      const link = document.createElement('link');
      link.type = 'text/css';
      link.rel = 'stylesheet';
      link.href = url;
      link.onload = resolve;
      link.onerror = reject;
      document.getElementsByTagName('head')[0].appendChild(link);
    });

  const loadJs = url =>
    new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url;
      script.onload = resolve;
      script.onerror = reject;
      document.getElementsByTagName('head')[0].appendChild(script);
    });

  const loadControls = () => {
    document.removeEventListener('mousemove', loadControls);
    document.removeEventListener('focus', loadControls);

    // CSS first to avoid flash of unstyled content
    loadCss('css/main.css')
      .then(() => loadJs('js/index.bundle.js'))
      .catch(console.error);
  };

  document.addEventListener('mousemove', loadControls);
  document.addEventListener('focus', loadControls);

  chrome.storage.local.get('forecast', r => {
    const { forecast } = r;
    window.forecast = forecast;
  });

  chrome.storage.local.get('cloudService', r => {
    window.cloudService = r.cloudService;
  });
});
<commit_msg>Reduce size of data object before resolving<commit_after>import { $ } from './libs/helpers';

document.addEventListener('DOMContentLoaded', () => {
  window.stellar = {};
  window.stellar.boot = new Promise(resolve => {
    chrome.storage.local.get(
      [
        'nextImage',
        'pausedImage',
        'cloudService',
        'dropbox',
        'onedrive',
        'forecast',
      ],
      d => {
        const data = { ...d };

        window.stellar.nextImage = data.nextImage;

        chrome.storage.sync.get(res => {
          const { photoFrequency } = res;
          const { pausedImage } = data;

          if (photoFrequency === 'paused') {
            data.nextImage = pausedImage;
          }

          const { nextImage } = data;

          if (nextImage) {
            const body = $('body');
            body.style.backgroundImage = `url(${nextImage.base64})`;
          }

          delete data.nextImage.base64;
          delete data.pausedImage;

          const result = Object.assign(res, data);
          resolve(result);
        });
      }
    );
  });

  chrome.runtime.sendMessage({ command: 'load-data' });

  const loadCss = url =>
    new Promise((resolve, reject) => {
      const link = document.createElement('link');
      link.type = 'text/css';
      link.rel = 'stylesheet';
      link.href = url;
      link.onload = resolve;
      link.onerror = reject;
      document.getElementsByTagName('head')[0].appendChild(link);
    });

  const loadJs = url =>
    new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url;
      script.onload = resolve;
      script.onerror = reject;
      document.getElementsByTagName('head')[0].appendChild(script);
    });

  const loadControls = () => {
    document.removeEventListener('mousemove', loadControls);
    document.removeEventListener('focus', loadControls);

    // CSS first to avoid flash of unstyled content
    loadCss('css/main.css')
      .then(() => loadJs('js/index.bundle.js'))
      .catch(console.error);
  };

  document.addEventListener('mousemove', loadControls);
  document.addEventListener('focus', loadControls);

  chrome.storage.local.get('forecast', r => {
    const { forecast } = r;
    window.forecast = forecast;
  });

  chrome.storage.local.get('cloudService', r => {
    window.cloudService = r.cloudService;
  });
});
<|endoftext|>


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

var util = gamebuilder.util = {};

util.isDef = function(obj) {
  return (typeof obj != 'undefined');
};

util.isDefAndNotNull = function(obj) {
  return util.isDef(obj) && (obj != null);
};

/**
 * Copies all prototype definitions from {@code base} to {@code derived}.
 * Discussion: http://www.crockford.com/javascript/inheritance.html .
 *
 * @param {Function} derived
 * @param {Function} base
 */
util.inherits = function(derived, base) {
  for (proto in base.prototype) {
    derived.prototype[proto] = base.prototype[proto];
  }
};
<commit_msg>Added a trivial implementation of sprintf() .<commit_after>// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var util = gamebuilder.util = {};

/**
 * @param {Object?} obj
 * @return {boolean} Whether obj is defined.
 */
util.isDef = function(obj) {
  return (typeof obj != 'undefined');
};

/**
 * @param {Object?} obj
 * @return {boolean} Whether obj is defined and not null.
 */
util.isDefAndNotNull = function(obj) {
  return util.isDef(obj) && (obj != null);
};

/**
 * Copies all prototype definitions from {@code base} to {@code derived}.
 * Discussion: http://www.crockford.com/javascript/inheritance.html .
 *
 * @param {Function} derived
 * @param {Function} base
 */
util.inherits = function(derived, base) {
  for (proto in base.prototype) {
    derived.prototype[proto] = base.prototype[proto];
  }
};

/**
 * @param {string} fmt
 * @return {string} Formatted string with argument substitution.
 */
util.sprintf = function(fmt) {
  for (var i = 1; i < arguments.length; ++i) {
    if (util.isDefAndNotNull(fmt.match('%s'))) {
      fmt = fmt.replace(/%s/, arguments[i]);
    } else {
      throw new Error('Too many positional arguments to fill format string: ' + fmt);
    }
  }
  if (util.isDefAndNotNull(fmt.match('%s'))) {
    throw new Error('Not enough positional arguments to fill in format string: ' + fmt);
  }
  return fmt;
};
<|endoftext|>


<commit_before>exports = module.exports = require('./utils.js');

// We override this function for browsers, because they print objects nicer
// natively than JSON.stringify can.
exports.logObject = function (msg, obj) {
  console.log(msg, "", obj);
};
<commit_msg>Give more useful console output in IE9.<commit_after>var exports = module.exports = require('./utils.js');

// We override this function for browsers, because they print objects nicer
// natively than JSON.stringify can.
exports.logObject = function (msg, obj) {
  if (/MSIE/.test(navigator.userAgent)) {
    console.log(msg, JSON.stringify(obj));
  } else {
    console.log(msg, "", obj);
  }
};
<|endoftext|>


<commit_before>'use strict';

const path = require("path");
const fs = require("fs");
const spawn = require("child_process").spawn;

const installerConfig = require(path.normalize(process.env.PWD + "/../etc/config.js"));

const SOAJS_RMS = {
	'gateway': "soajs.controller",
	'urac': 'soajs.urac',
	'oauth': 'soajs.oauth',
	'dashboard': 'soajs.dashboard',
	'ui': 'soajs.dashboard.ui'
};

const serviceModule = {

	/**
	 * This command will calculate the needed env variables and
	 * start the requested service if supported in the requested environment
	 * @param args {Array}
	 * @param callback {Function}
	 */
	'start': (args, callback) => {
		if (args.length < 2) {
			return callback();
		}

		//check if service is supported
		let requestedService = args[0];
		let serviceType = (requestedService === 'ui') ? 'SOAJS Console' : 'Service';
		if(!SOAJS_RMS[requestedService]){
			serviceType = (requestedService === 'ui') ? 'SOAJS Console' : 'Service';
			return callback(`${serviceType} ${requestedService} is not supported!`);
		}

			//check for environment
		let requestedEnvironment = args[1];
		if(!requestedEnvironment.includes("--env")){
			return callback(`Specify the environment where you want ${requestedService} to be deployed!`);
		}
		requestedEnvironment = requestedEnvironment.split("=");
		if(!requestedEnvironment[1] || requestedEnvironment[1] === ''){
			return callback(`Specify the environment where you want ${requestedService} to be deployed!`);
		}
		requestedEnvironment = requestedEnvironment[1].toLowerCase();

		//check if service is installed and downloaded
		if(!installerConfig.workingDirectory || installerConfig.workingDirectory === ''){
			return callback(`${serviceType} ${requestedService} is not installed!`);
		}

		//check if service folder exists
		fs.stat(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[requestedService], (error, stats) => {
			if(error || !stats){
				return callback(`${serviceType} ${requestedService} is not installed!`);
			}

			//set and ensure the log directory
			let logLoc;
			switch (process.env.PLATFORM){
				case 'Darwin':
					logLoc = "/usr/local/var/log/soajs/";
					break;
				case 'Linux':
				default:
					logLoc = "/var/log/soajs/";
					break;
			}

			//check log file
			fs.stat(logLoc, (error, stats) => {
				if(error){
					if(error.code === 'ENOENT' && !stats){
						//create log file
						fs.mkdir(logLoc, { 'recursive': true}, (error) => {
							if (error) {
								return callback(`Unable to create a Log File for service ${requestedService}!`);
							}
							launchService(logLoc);
						});
					}
					else{
						return callback(`Unable to create a Log File for service ${requestedService}!`);
					}
				}
				else{
					launchService(logLoc);
				}
			});
		});

		//function that sets the aggregated variables as environment variables and launches the service.
		function launchService(logLoc) {

			process.env.SOAJS_ENV = requestedEnvironment;
			process.env.SOAJS_SRVIP = '127.0.0.1';
			process.env.SOAJS_PROFILE = path.normalize(process.env.PWD + "/../data/soajs_profile.js" );

			//check for custom port
			if(args[2] && args[2].includes("--port")){
				let customServicePort = args[2].split("=");
				if(customServicePort[1] && customServicePort[1] !== ''){
					process.env.SOAJS_SRVPORT = customServicePort[1];
				}
			}

			let outLog = path.normalize(logLoc + `/${requestedEnvironment}-${requestedService}-out.log`);
			let serviceOutLog = fs.openSync(outLog, "w");

			let errLog = path.normalize(logLoc + `/${requestedEnvironment}-${requestedService}-err.log`);
			let serviceErrLog = fs.openSync(errLog, "w");

			let serviceInstance = spawn(process.env.NODE_BIN, ["."], {
				"cwd": installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[requestedService] + "/",
				"env": process.env,
				"stdio": ['ignore', serviceOutLog, serviceErrLog],
				"detached": true,
			});
			serviceInstance.unref();
			let output = `Service ${requestedService} started ...\n`;
			output += "Logs:\n";
			output += `[ out ] -> ${outLog}\n`;
			output += `[ err ] -> ${errLog}\n`;
			return callback(null, output);
		}

		function launchUI() {}
	},

	'stop': (args, callback) => {

	}
};

module.exports = serviceModule;<commit_msg>updated and completed start service<commit_after>'use strict';

const path = require("path");
const fs = require("fs");
const spawn = require("child_process").spawn;

const installerConfig = require(path.normalize(process.env.PWD + "/../etc/config.js"));

const SOAJS_RMS = {
	'gateway': "soajs.controller",
	'urac': 'soajs.urac',
	'oauth': 'soajs.oauth',
	'dashboard': 'soajs.dashboard',
	'ui': 'soajs.dashboard.ui'
};

const serviceModule = {

	/**
	 * This command will calculate the needed env variables and
	 * start the requested service if supported in the requested environment
	 * @param args {Array}
	 * @param callback {Function}
	 */
	'start': (args, callback) => {
		if (args.length < 2) {
			return callback();
		}

		//check if service is supported
		let requestedService = args[0];
		let serviceType = (requestedService === 'ui') ? 'SOAJS Console' : 'Service';
		if(!SOAJS_RMS[requestedService]){
			serviceType = (requestedService === 'ui') ? 'SOAJS Console' : 'Service';
			return callback(`${serviceType} ${requestedService} is not supported!`);
		}

			//check for environment
		let requestedEnvironment = args[1];
		if(!requestedEnvironment.includes("--env")){
			return callback(`Specify the environment where you want ${requestedService} to be deployed!`);
		}
		requestedEnvironment = requestedEnvironment.split("=");
		if(!requestedEnvironment[1] || requestedEnvironment[1] === ''){
			return callback(`Specify the environment where you want ${requestedService} to be deployed!`);
		}
		requestedEnvironment = requestedEnvironment[1].toLowerCase();

		//check if service is installed and downloaded
		if(!installerConfig.workingDirectory || installerConfig.workingDirectory === ''){
			return callback(`${serviceType} ${requestedService} is not installed!`);
		}

		//check if service folder exists
		fs.stat(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[requestedService], (error, stats) => {
			if(error || !stats){
				return callback(`${serviceType} ${requestedService} is not installed!`);
			}

			//set and ensure the log directory
			let logLoc;
			switch (process.env.PLATFORM){
				case 'Darwin':
					logLoc = "/usr/local/var/log/soajs/";
					break;
				case 'Linux':
				default:
					logLoc = "/var/log/soajs/";
					break;
			}

			//check log file
			fs.stat(logLoc, (error, stats) => {
				if(error){
					if(error.code === 'ENOENT' && !stats){
						//create log file
						fs.mkdir(logLoc, { 'recursive': true}, (error) => {
							if (error) {
								return callback(`Unable to create a Log File for ${serviceType} ${requestedService}!`);
							}

							if(requestedService === 'ui'){
								launchUI(logLoc);
							}
							else {
								launchService(logLoc);
							}
						});
					}
					else{
						return callback(`Unable to create a Log File for ${serviceType} ${requestedService}!`);
					}
				}
				else{
					if(requestedService === 'ui'){
						launchUI(logLoc);
					}
					else {
						launchService(logLoc);
					}
				}
			});
		});

		//function that sets the aggregated variables as environment variables and launches the service.
		function launchService(logLoc) {

			process.env.SOAJS_ENV = requestedEnvironment;
			process.env.SOAJS_SRVIP = '127.0.0.1';
			process.env.SOAJS_PROFILE = path.normalize(process.env.PWD + "/../data/soajs_profile.js" );

			//check for custom port
			if(args[2] && args[2].includes("--port")){
				let customServicePort = args[2].split("=");
				if(customServicePort[1] && customServicePort[1] !== ''){
					process.env.SOAJS_SRVPORT = customServicePort[1];
				}
			}

			let outLog = path.normalize(logLoc + `/${requestedEnvironment}-${requestedService}-out.log`);
			let serviceOutLog = fs.openSync(outLog, "w");

			let errLog = path.normalize(logLoc + `/${requestedEnvironment}-${requestedService}-err.log`);
			let serviceErrLog = fs.openSync(errLog, "w");

			let serviceInstance = spawn(process.env.NODE_BIN, [installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[requestedService] + `/index.js`, `--env=${requestedEnvironment}`], {
				"env": process.env,
				"stdio": ['ignore', serviceOutLog, serviceErrLog],
				"detached": true,
			});
			serviceInstance.unref();

			//generate out message for service
			let output = `Service ${requestedService} started ...\n`;
			output += "Logs:\n";
			output += `[ out ] -> ${outLog}\n`;
			output += `[ err ] -> ${errLog}\n`;
			return callback(null, output);
		}

		//function that starts the ui express app which contains the soajs console ui.
		function launchUI(logLoc) {
			let outLog = path.normalize(logLoc + `/${requestedEnvironment}-${requestedService}-out.log`);
			let serviceOutLog = fs.openSync(outLog, "w");

			let errLog = path.normalize(logLoc + `/${requestedEnvironment}-${requestedService}-err.log`);
			let serviceErrLog = fs.openSync(errLog, "w");

			let serviceInstance = spawn(process.env.NODE_BIN, [installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[requestedService] + "/app/index.js"], {
				"env": process.env,
				"stdio": ['ignore', serviceOutLog, serviceErrLog],
				"detached": true,
			});
			serviceInstance.unref();

			//require the ui config to learn the host and the port values
			let uiConfig = require(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[requestedService] + "/app/config.js");

			//generate output message for ui
			let output = `SOAJS Console UI started ...\n`;
			output += `In your Browser, open: http://${uiConfig.host}:${uiConfig.port}/ \n`;
			return callback(null, output);
		}
	},

	'stop': (args, callback) => {

	}
};

module.exports = serviceModule;<|endoftext|>


<commit_before>'use strict';

var path, circle, nodes, links, lastNodeId, force, colors;

function start() {
  // set up SVG for D3
  var width  = 360,
    height = 350;
  colors = d3.scale.category10();

  var svg = d3.select('#graph-canvas')
    .append('svg')
    //.attr('oncontextmenu', 'return false;')
    .attr('width', width)
    .attr('height', height);

  var msgHist = createMockupActorHistory();

  /*
   function createMockupActorHistory() {
   var actors = {
   a1 : new Actor("a1", "Master",   "Master"),
   a2 : new Actor("a2", "Producer", "Producer"),
   a3 : new Actor("a3", "Sort 1",   "Sort"),
   a4 : new Actor("a4", "Sort 2",   "Sort"),
   a5 : new Actor("a5", "Sort 3",   "Sort"),
   a6 : new Actor("a6", "Sort 4",   "Sort"),
   a7 : new Actor("a7", "Validator", "Validator")};

   var messages = {};
   messages.a2 = [new Message("ma2-0", "a1", "a2")];

   function create1000Messages(sender, rcvr) {
   var messages = [];
   for (var i = 0; i < 1000; i += 1) {
   messages.push(new Message("m-" + rcvr + "-" + i, sender, rcvr));
   }
   return messages;
   }
   messages.a3 = create1000Messages("a2", "a3");
   messages.a4 = create1000Messages("a3", "a4");
   messages.a5 = create1000Messages("a4", "a5");
   messages.a6 = create1000Messages("a5", "a6");
   messages.a7 = create1000Messages("a6", "a7");
   messages.a1 = [new Message("final", "a7", "a1")];

   return new MessageHistory(messages, actors);
   }
   */

  // function Message(id, sender, receiver) {
  //   this.id       = id;
  //   this.sender   = sender;
  //   this.receiver = receiver;
  // }
  // function Actor(id, name, typeName) {
  //   this.id       = id;
  //   this.name     = name;
  //   this.typeName = typeName;
  // }

  function hasSelfSends(actorId, messages) {
    for (var i in messages) {
      if (messages[i].sender == "actorId") {
        return true;
      }
    }
    return false;
  }

  var horizontalDistance = 100,
    verticalDistance = 100;

  function determineNodes(msgHist) {
    var actorsPerType = {};
    var nodes = [];
    for (var aId in msgHist.actors) {
      var actor = msgHist.actors[aId];
      if (actorsPerType.hasOwnProperty(actor.typeName)) {
        actorsPerType[actor.typeName] += 1;
      } else {
        actorsPerType[actor.typeName] = 0;
      }

      var selfSends = hasSelfSends(aId, msgHist.messages);
      var node = {
        id: actor.name,
        reflexive: selfSends,
        x: horizontalDistance + horizontalDistance * actorsPerType[actor.typeName],
        y: verticalDistance * Object.keys(actorsPerType).length,
        type: actor.typeName
      };

      nodes.push(node);
    }
    return nodes;
  }

  // set up initial nodes and links
  //  - nodes are known by 'id', not by index in array.
  //  - reflexive edges are indicated on the node (as a bold black circle).
  //  - links are always source < target; edge directions are set by 'left' and 'right'.
  nodes = determineNodes(msgHist);

  // nodes = [
  //   {id: "Master", reflexive: false,     x: 100, y: 0,   type: "Master"},   // 0
  //   {id: "Producer", reflexive: false,   x: 100, y: 100, type: "Producer"}, // 1
  //   {id: "Sort 1", reflexive: false,     x: 100, y: 200, type: "Sort"}, // 2
  //   {id: "Sort 2", reflexive: false,     x: 200, y: 200, type: "Sort"}, // 3
  //   {id: "Sort 3", reflexive: false,     x: 300, y: 200, type: "Sort"},
  //   {id: "Sort 4", reflexive: false,     x: 400, y: 200, type: "Sort"},
  //   {id: "Validator", reflexive: false,  x: 100, y: 300, type: "Validator"},
  // ];
  lastNodeId = 5;
  links = [
    {source: nodes[0], target: nodes[1], left: false, right: true, messageCount: 1 },
    {source: nodes[1], target: nodes[2], left: false, right: true, messageCount: 1000 },
    {source: nodes[2], target: nodes[3], left: false, right: true, messageCount: 1000 },
    {source: nodes[3], target: nodes[4], left: false, right: true, messageCount: 1000 },
    {source: nodes[4], target: nodes[5], left: false, right: true, messageCount: 1000 },
    {source: nodes[5], target: nodes[6], left: false, right: true, messageCount: 1000 },
    {source: nodes[6], target: nodes[0], left: false, right: true, messageCount: 1 },
  ];

  // init D3 force layout
  force = d3.layout.force()
    .nodes(nodes)
    .links(links)
    .size([width, height])
    .linkDistance(70)
    .charge(-500)
    .on('tick', tick);

  force.linkStrength(function(link) {
    if (link.messageCount === 1000) {
      return 1;
    } else {
      return 0.001;
    }
  });

  // define arrow markers for graph links
  svg.append('svg:defs').append('svg:marker')
    .attr('id', 'end-arrow')
    .attr('viewBox', '0 -5 10 10')
    .attr('refX', 6)
    .attr('markerWidth', 3)
    .attr('markerHeight', 3)
    .attr('orient', 'auto')
    .append('svg:path')
    .attr('d', 'M0,-5L10,0L0,5')
    .attr('fill', '#000');

  svg.append('svg:defs').append('svg:marker')
    .attr('id', 'start-arrow')
    .attr('viewBox', '0 -5 10 10')
    .attr('refX', 4)
    .attr('markerWidth', 3)
    .attr('markerHeight', 3)
    .attr('orient', 'auto')
    .append('svg:path')
    .attr('d', 'M10,-5L0,0L10,5')
    .attr('fill', '#000');

  // handles to link and node element groups
  path = svg.append('svg:g').selectAll('path');
  circle = svg.append('svg:g').selectAll('g');

  restart();
}

// update force layout (called automatically each iteration)
function tick() {
  // draw directed edges with proper padding from node centers
  path.attr('d', function(d) {
    var deltaX = d.target.x - d.source.x,
      deltaY = d.target.y - d.source.y,
      dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
      normX = deltaX / dist,
      normY = deltaY / dist,
      sourcePadding = d.left ? 17 : 12,
      targetPadding = d.right ? 17 : 12,
      sourceX = d.source.x + (sourcePadding * normX),
      sourceY = d.source.y + (sourcePadding * normY),
      targetX = d.target.x - (targetPadding * normX),
      targetY = d.target.y - (targetPadding * normY);
    return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
  });

  circle.attr('transform', function(d) {
    return 'translate(' + d.x + ',' + d.y + ')';
  });
}

// update graph (called when needed)
function restart() {
  // path (link) group
  path = path.data(links);

  // update existing links
  path.classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });

  // add new links
  path.enter().append('svg:path')
    .attr('class', 'link')
    // .classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });

  // remove old links
  path.exit().remove();

  // circle (node) group
  // NB: the function arg is crucial here! nodes are known by id, not by index!
  circle = circle.data(nodes, function(d) { return d.id; });

  // update existing nodes (reflexive & selected visual states)
  circle.selectAll('circle')
    .style('fill', function(d) {
      return (d === selected_node) ? d3.rgb(colors(d.id)).brighter().toString() : colors(d.id);
    })
    .classed('reflexive', function(d) { return d.reflexive; });

  // add new nodes
  var g = circle.enter().append('svg:g');

  g.append("rect")
    .attr("rx", 6)
    .attr("ry", 6)
    .attr("x", -12.5)
    .attr("y", -12.5)
    .attr("width", 50)
    .attr("height", 25)

    //   g.append('svg:circle')
    .attr('class', 'node')
    //     .attr('r', 12)
    .style('fill', function(d) {
      return colors(d.type);
    })
    .style('stroke', function(d) { return d3.rgb(colors(d.id)).darker().toString(); })
    .classed('reflexive', function(d) { return d.reflexive; });

  // show node IDs
  g.append('svg:text')
    .attr('x', 8)
    .attr('y', 4)
    .attr('class', 'id')
    .text(function(d) { return d.id; });

  // remove old nodes
  circle.exit().remove();

  // set the graph in motion
  force.start();

  // execute enough steps that the graph looks static
  for (var i = 0; i < 1000; i++) {
    force.tick();
  }
//   force.stop();
}
<commit_msg>Determine communication links form message history<commit_after>'use strict';

var path, circle, nodes, links, force, colors;

function start() {
  // set up SVG for D3
  var width  = 360,
    height = 350;
  colors = d3.scale.category10();

  var svg = d3.select('#graph-canvas')
    .append('svg')
    //.attr('oncontextmenu', 'return false;')
    .attr('width', width)
    .attr('height', height);

  var msgHist = createMockupActorHistory();

  function hasSelfSends(actorId, messages) {
    for (var i in messages) {
      if (messages[i].sender == "actorId") {
        return true;
      }
    }
    return false;
  }

  var horizontalDistance = 100,
    verticalDistance = 100;

  function hashAtInc(hash, idx, inc) {
    if (hash.hasOwnProperty(idx)) {
      hash[idx] += inc;
    } else {
      hash[idx] = inc;
    }
  }

  function determineNodes(msgHist) {
    var actorsPerType = {};
    var nodes = {};
    for (var aId in msgHist.actors) {
      var actor = msgHist.actors[aId];
      hashAtInc(actorsPerType, actor.typeName, 1);

      var selfSends = hasSelfSends(aId, msgHist.messages);
      var node = {
        id: actor.id,
        name: actor.name,
        reflexive: selfSends,
        x: horizontalDistance + horizontalDistance * actorsPerType[actor.typeName],
        y: verticalDistance * Object.keys(actorsPerType).length,
        type: actor.typeName
      };

      nodes[aId] = node;
    }
    return nodes;
  }

  function mapToArray(map) {
    var arr = [];
    for (var i in map) {
      arr.push(map[i]);
    }
    return arr;
  }

  // set up initial nodes and links
  //  - nodes are known by 'id', not by index in array.
  //  - reflexive edges are indicated on the node (as a bold black circle).
  //  - links are always source < target; edge directions are set by 'left' and 'right'.
  var nodeMap = determineNodes(msgHist);
  nodes = mapToArray(nodeMap);

  function determineLinks(msgHist, nodeMap) {
    var msgSends = {};

    for (var aId in msgHist.messages) {
      for (var msg of msgHist.messages[aId]) {
        if (!msgSends.hasOwnProperty(msg.sender)) {
          msgSends[msg.sender] = {};
        }
        hashAtInc(msgSends[msg.sender], msg.receiver, 1);
      }
    }

    var links = [];
    for (var sendId in msgSends) {
      for (var rcvrId in msgSends[sendId]) {
        links.push({
          source: nodeMap[sendId],
          target: nodeMap[rcvrId],
          left: false, right: true,
          messageCount: msgSends[sendId][rcvrId]
        });
      }
    }
    return links;
  }
  links = determineLinks(msgHist, nodeMap);

  // init D3 force layout
  force = d3.layout.force()
    .nodes(nodes)
    .links(links)
    .size([width, height])
    .linkDistance(70)
    .charge(-500)
    .on('tick', tick);

  force.linkStrength(function(link) {
    if (link.messageCount === 1000) {
      return 1;
    } else {
      return 0.001;
    }
  });

  // define arrow markers for graph links
  svg.append('svg:defs').append('svg:marker')
    .attr('id', 'end-arrow')
    .attr('viewBox', '0 -5 10 10')
    .attr('refX', 6)
    .attr('markerWidth', 3)
    .attr('markerHeight', 3)
    .attr('orient', 'auto')
    .append('svg:path')
    .attr('d', 'M0,-5L10,0L0,5')
    .attr('fill', '#000');

  svg.append('svg:defs').append('svg:marker')
    .attr('id', 'start-arrow')
    .attr('viewBox', '0 -5 10 10')
    .attr('refX', 4)
    .attr('markerWidth', 3)
    .attr('markerHeight', 3)
    .attr('orient', 'auto')
    .append('svg:path')
    .attr('d', 'M10,-5L0,0L10,5')
    .attr('fill', '#000');

  // handles to link and node element groups
  path = svg.append('svg:g').selectAll('path');
  circle = svg.append('svg:g').selectAll('g');

  restart();
}

// update force layout (called automatically each iteration)
function tick() {
  // draw directed edges with proper padding from node centers
  path.attr('d', function(d) {
    var deltaX = d.target.x - d.source.x,
      deltaY = d.target.y - d.source.y,
      dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
      normX = deltaX / dist,
      normY = deltaY / dist,
      sourcePadding = d.left ? 17 : 12,
      targetPadding = d.right ? 17 : 12,
      sourceX = d.source.x + (sourcePadding * normX),
      sourceY = d.source.y + (sourcePadding * normY),
      targetX = d.target.x - (targetPadding * normX),
      targetY = d.target.y - (targetPadding * normY);
    return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
  });

  circle.attr('transform', function(d) {
    return 'translate(' + d.x + ',' + d.y + ')';
  });
}

// update graph (called when needed)
function restart() {
  // path (link) group
  path = path.data(links);

  // update existing links
  path.classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });

  // add new links
  path.enter().append('svg:path')
    .attr('class', 'link')
    // .classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });

  // remove old links
  path.exit().remove();

  // circle (node) group
  // NB: the function arg is crucial here! nodes are known by id, not by index!
  circle = circle.data(nodes, function(d) { return d.id; });

  // update existing nodes (reflexive & selected visual states)
  circle.selectAll('circle')
    .style('fill', function(d) {
      return (d === selected_node) ? d3.rgb(colors(d.id)).brighter().toString() : colors(d.id);
    })
    .classed('reflexive', function(d) { return d.reflexive; });

  // add new nodes
  var g = circle.enter().append('svg:g');

  g.append("rect")
    .attr("rx", 6)
    .attr("ry", 6)
    .attr("x", -12.5)
    .attr("y", -12.5)
    .attr("width", 50)
    .attr("height", 25)

    //   g.append('svg:circle')
    .attr('class', 'node')
    //     .attr('r', 12)
    .style('fill', function(d) {
      return colors(d.type);
    })
    .style('stroke', function(d) { return d3.rgb(colors(d.id)).darker().toString(); })
    .classed('reflexive', function(d) { return d.reflexive; });

  // show node IDs
  g.append('svg:text')
    .attr('x', 8)
    .attr('y', 4)
    .attr('class', 'id')
    .text(function(d) { return d.name; });

  // remove old nodes
  circle.exit().remove();

  // set the graph in motion
  force.start();

  // execute enough steps that the graph looks static
  for (var i = 0; i < 1000; i++) {
    force.tick();
  }
//   force.stop();
}
<|endoftext|>


<commit_before>
(function($){

  window.enableBlame = function(url, original_path) {
    var message = null;
    var message_rev = null;

    /* for each blame cell containing a changeset link... */
    var rev_paths = {};
    $("table.code th.blame a").each(function() {
      href = $(this).attr("href");
      $(this).removeAttr("href");
      rev_href = href.substr(href.indexOf("changeset/") + 10);
      elts = rev_href.split("/");
      var path = elts.slice(1).join("/");
      if (path != original_path)
        rev_paths["r"+elts[0]] = path;
    });

    /* for each blame cell... */
    $("table.code th.blame").each(function() {
      var rev = $(this).attr("class").split(" ")[1]; // "blame r123"
      var path = rev_paths[rev] || original_path; // only found if != orig

      if (!rev)
        return;

      $(this).css("cursor", "pointer").click(function() {
        var row = this.parentNode;
        var message_is_visible = message && message.css("display") == "block";
        var highlight_rev = null;

        function show() {
          /* Display commit message for the selected revision */

          var message_w = message.get(0).offsetWidth;

          // limit message panel width to 3/5 of the row width
          var row_w = row.offsetWidth;
          var max_w = (3.0 * row_w / 5.0);
          if (!message_w || message_w > max_w) {
            message_w = max_w;
            var borderw = (3+8)*2; // borderwidth + padding on both sides
            message.css({width: message_w - borderw + "px"});
          }

          var row_offset = $(row).offset();
          var left = row_offset.left + row.offsetWidth - message_w;
          message.css({display: "block", top: row_offset.top+"px", left: left-2+"px"});
        }

        function hide() {
          /* Hide commit message */
          message.css({display: "none"});

          /* Remove highlighting for lines of the current revision */
          $("table.code th."+message_rev).each(function() {
            $(this.parentNode).removeClass("hilite")
          });
        }

        if (message_rev != rev) {              // fetch a new revision
          if (message_is_visible) {
            hide();
          }
          message_rev = rev;
          highlight_rev = message_rev;

          $.get(url + rev.substr(1), {annotate: path}, function(data) {
            // remove former message panel if any
            if (message)
              message.remove();
            // create new message panel
            message = $('
').css("position", "absolute")
                .append($('
')
                  .append($('<input value="Close" type="button">').click(hide)))
                .append($('
').html(data || "(no changeset information)"))
              .appendTo("body");

            // workaround non-clickable "Close" issue in Firefox
            if ($.browser.mozilla)
              message.find("div.inlinebuttons").next().css("clear", "right");

            show();
          });
        } else if (message_is_visible) {
          hide();
        } else {
          show();
          highlight_rev = message_rev;
        }

        /* Highlight all lines of the current revision */
        $("table.code th."+highlight_rev).each(function() {
          $(this.parentNode).addClass("hilite")
        });

      });
    });
  }

})(jQuery);
<commit_msg>Make sure the ''Close'' button on the changeset panel in the annotate view works for some versions of Safari and Chrome.<commit_after>
(function($){

  window.enableBlame = function(url, original_path) {
    var message = null;
    var message_rev = null;

    /* for each blame cell containing a changeset link... */
    var rev_paths = {};
    $("table.code th.blame a").each(function() {
      href = $(this).attr("href");
      $(this).removeAttr("href");
      rev_href = href.substr(href.indexOf("changeset/") + 10);
      elts = rev_href.split("/");
      var path = elts.slice(1).join("/");
      if (path != original_path)
        rev_paths["r"+elts[0]] = path;
    });

    /* for each blame cell... */
    $("table.code th.blame").each(function() {
      var rev = $(this).attr("class").split(" ")[1]; // "blame r123"
      var path = rev_paths[rev] || original_path; // only found if != orig

      if (!rev)
        return;

      $(this).css("cursor", "pointer").click(function() {
        var row = this.parentNode;
        var message_is_visible = message && message.css("display") == "block";
        var highlight_rev = null;

        function show() {
          /* Display commit message for the selected revision */

          var message_w = message.get(0).offsetWidth;

          // limit message panel width to 3/5 of the row width
          var row_w = row.offsetWidth;
          var max_w = (3.0 * row_w / 5.0);
          if (!message_w || message_w > max_w) {
            message_w = max_w;
            var borderw = (3+8)*2; // borderwidth + padding on both sides
            message.css({width: message_w - borderw + "px"});
          }

          var row_offset = $(row).offset();
          var left = row_offset.left + row.offsetWidth - message_w;
          message.css({display: "block", top: row_offset.top+"px", left: left-2+"px"});
        }

        function hide() {
          /* Hide commit message */
          message.css({display: "none"});

          /* Remove highlighting for lines of the current revision */
          $("table.code th."+message_rev).each(function() {
            $(this.parentNode).removeClass("hilite")
          });
        }

        if (message_rev != rev) {              // fetch a new revision
          if (message_is_visible) {
            hide();
          }
          message_rev = rev;
          highlight_rev = message_rev;

          $.get(url + rev.substr(1), {annotate: path}, function(data) {
            // remove former message panel if any
            if (message)
              message.remove();
            // create new message panel
            message = $('
').css("position", "absolute")
                .append($('
')
                  .append($('<input value="Close" type="button">').click(hide)))
                .append($('
').html(data || "(no changeset information)"))
              .appendTo("body");

            // workaround non-clickable "Close" issue in Firefox
            if ($.browser.mozilla || $.browser.safari)
              message.find("div.inlinebuttons").next().css("clear", "right");

            show();
          });
        } else if (message_is_visible) {
          hide();
        } else {
          show();
          highlight_rev = message_rev;
        }

        /* Highlight all lines of the current revision */
        $("table.code th."+highlight_rev).each(function() {
          $(this.parentNode).addClass("hilite")
        });

      });
    });
  }

})(jQuery);
<|endoftext|>


<commit_before>var maxmind    = require('maxmind')        // runk/node-maxmind
  , loader     = require('maxmind-loader') // angleman/maxmind-loader
  , geos       = require('geos-major')     // angleman/geos-major
  , cron       = require('cron')           // ncb000gt/node-cron
  , time       = require('time')           // TooTallNate/node-time
;

var maxminded = function() {

	this.load_begin = function() {
		console.log('load begin');
		loader(this.options, this.load_done);
	};

	this.load_done = function (err, datapath){
		if (err) {
			this.handle_error(err);
		} else {
			maxmind.init(datapath, this.options);
			this.maxmind_initalized = true;
		}
	};

	this.handle_error = function (err){
		console.log(err);
		if (this.retry) {
			// todo: reschedule job
		}
	};

	this.init = function(options) {
		options          = options          || {};

		if (typeof options == 'string') {
			options      = { initLoad: options };
		};

		if (options.initLoad) {
			maxmind.init(options.initLoad, options);
			this.maxmind_initalized = true;
		};

		options.cronTime   = options.cronTime || '00 30 03 * * 3';
		options.start      = options.start    || false;
		this.options       = options;
		options.onTick     = this.load_begin;
		options.onComplete = this.load_done;
		this.job           = new cron.CronJob(options);
		this.job.start();
	};

	// maxmind wrapper
	this.getLocation = function (options, headers) {
		var result;
		if (this.maxmind_initalized) {
			result = maxmind.getLocation(options);
		}
		if (!result && headers) {
			result = geos.country(headers['cf-ipcountry']);
		}
		return result;
	};

	// maxmind pass-thru
	this.getCountry = function (options) {
		return maxmind.getCountry(options);
	};

	this.getOrganization = function (options) {
		return maxmind.getOrganization(options);
	};
}

var minded = new maxminded;

module.exports = minded;<commit_msg>passing initial tests<commit_after>var maxmind    = require('maxmind')        // runk/node-maxmind
  , loader     = require('maxmind-loader') // angleman/maxmind-loader
  , geos       = require('geos-major')     // angleman/geos-major
  , cron       = require('cron')           // ncb000gt/node-cron
  , time       = require('time')           // TooTallNate/node-time
;

var maxmind_initialized = false;

var maxminded = function() {

	this.load_begin = function(start_callback, start_options) {
		start_options = start_options || this.options;

		function load_done(err, datapath){
			if (err) {
				this.handle_error(err);
			} else {
				maxmind.init(datapath, start_options);
				maxmind_initialized = true;
				if (start_callback) {
					start_callback(datapath);
				}
			};
		}

		loader(this.options, load_done);
	};

	this.handle_error = function (err){
		console.log(err);
		if (this.retry) {
			// todo: reschedule job
		}
	};

	this.init = function(options) {
		options          = options          || {};

		if (typeof options == 'string') {
			options      = { initLoad: options };
		};

		if (options.initLoad) {
			maxmind.init(options.initLoad, options);
			maxmind_initialized = true;
		};

		options.cronTime   = options.cronTime || '00 30 03 * * 3';
		this.options       = options;
		options.onTick     = this.load_begin;
		options.onComplete = this.load_done;
		this.job           = new cron.CronJob(options);
		this.job.start();

		if (options.start) {
			this.load_begin(options.start);
		}
	};

	// maxmind wrapper
	this.getLocation = function (ip, headers) {
		var result;
		if (maxmind_initialized) {
			result = maxmind.getLocation(ip);
		}
		if (!result && headers) {
			result = geos.country(headers['cf-ipcountry']);
			if (result) {
				result = {
					countryCode: headers['cf-ipcountry'],
//					countryName: geos.                      // todo: add countryname to geo-minor
					latitude: result.lat,
					longitude: result.lon

				}
			}
		}
		return result;
	};

	// maxmind pass-thru
	this.getCountry = function (options) {
		return maxmind.getCountry(options);
	};

	this.getOrganization = function (options) {
		return maxmind.getOrganization(options);
	};
}

var minded = new maxminded;

module.exports = minded;<|endoftext|>


<commit_before>import { fromJS, is, Map } from 'immutable';
import SelectorFactory from 'SelectorFactory'

describe('create selector factory', () => {
  const state = fromJS({
    entities: {
      jobs: {
        foo: 'bar',
      },
    },
  });
  const selector = SelectorFactory.create('jobs', 'foo');
  it('creates a selector that selects correct state', () => {
    expect(selector(state)).toBe('bar');
  });
});

describe('createWithDefault selector factory', () => {
  const selector = SelectorFactory.createWithDefault('jobs', 'foo', 192939);
  it('creates a selector that selects correct state', () => {
    const state = fromJS({
      entities: {
        jobs: {
          foo: 'bar',
        },
      },
    });
    expect(selector(state)).toBe('bar');
  });
  it('creates a selector that selects a default state', () => {
    const state = fromJS({
      entities: {
        jobs: {},
      },
    });
    expect(selector(state)).toBe(192939);
  });
});

describe('createFiltersSelector selector factory', () => {
  const selector = SelectorFactory.createFiltersSelector('jobs');
  it('creates a selector that selects filters state', () => {
    const state = fromJS({
      entities: {
        jobs: {
          filters: { foo: 'bar' },
        },
      },
    });
    const expected = fromJS({ foo: 'bar' });
    expect(is(selector(state), expected)).toBe(true);
  });
  it('creates a selector that selects a default state', () => {
    const state = fromJS({
      entities: {
        jobs: {},
      },
    });
    expect(is(selector(state), Map())).toBe(true);
  });
});

describe('createPropFiltersSelector selector factory', () => {
  const selector = SelectorFactory.createPropFiltersSelector();
  it('creates a selector that selects a components prop filters', () => {
    const props = { filters: { foo: 'bar', bar: 'foo' }};
    expect(is(selector(undefined, props), Map(props.filters))).toBe(true);
  });
  it('creates a selector that returns a Map by default', () => {
    expect(is(selector(undefined, {}), Map())).toBe(true);
  });
});

describe('createResultSelector selector factory', () => {
 // to do...
});
<commit_msg>case issue son linux platforms…<commit_after>import { fromJS, is, Map } from 'immutable';
import SelectorFactory from 'selectorFactory'

describe('create selector factory', () => {
  const state = fromJS({
    entities: {
      jobs: {
        foo: 'bar',
      },
    },
  });
  const selector = SelectorFactory.create('jobs', 'foo');
  it('creates a selector that selects correct state', () => {
    expect(selector(state)).toBe('bar');
  });
});

describe('createWithDefault selector factory', () => {
  const selector = SelectorFactory.createWithDefault('jobs', 'foo', 192939);
  it('creates a selector that selects correct state', () => {
    const state = fromJS({
      entities: {
        jobs: {
          foo: 'bar',
        },
      },
    });
    expect(selector(state)).toBe('bar');
  });
  it('creates a selector that selects a default state', () => {
    const state = fromJS({
      entities: {
        jobs: {},
      },
    });
    expect(selector(state)).toBe(192939);
  });
});

describe('createFiltersSelector selector factory', () => {
  const selector = SelectorFactory.createFiltersSelector('jobs');
  it('creates a selector that selects filters state', () => {
    const state = fromJS({
      entities: {
        jobs: {
          filters: { foo: 'bar' },
        },
      },
    });
    const expected = fromJS({ foo: 'bar' });
    expect(is(selector(state), expected)).toBe(true);
  });
  it('creates a selector that selects a default state', () => {
    const state = fromJS({
      entities: {
        jobs: {},
      },
    });
    expect(is(selector(state), Map())).toBe(true);
  });
});

describe('createPropFiltersSelector selector factory', () => {
  const selector = SelectorFactory.createPropFiltersSelector();
  it('creates a selector that selects a components prop filters', () => {
    const props = { filters: { foo: 'bar', bar: 'foo' }};
    expect(is(selector(undefined, props), Map(props.filters))).toBe(true);
  });
  it('creates a selector that returns a Map by default', () => {
    expect(is(selector(undefined, {}), Map())).toBe(true);
  });
});

describe('createResultSelector selector factory', () => {
 // to do...
});
<|endoftext|>


<commit_before>/**
 * @fileOverview Extend the aura-core facade
 */
/*global define*/
define(["../libs/aura-core/facade", "./mediator", "./permissions"],
    function (facade, mediator, permissions) {

    facade.backbone = mediator.backbone;
    facade.models = mediator.models;
    facade.collections = mediator.collections;

    return facade;
});<commit_msg>Added local storage<commit_after>/**
 * @fileOverview Extend the aura-core facade
 */
/*global define*/
define(["../libs/aura-core/facade", "./mediator", "./permissions"],
    function (facade, mediator, permissions) {

        facade.data.store = mediator.data.store;
        facade.backbone = mediator.backbone;
        facade.models = mediator.models;
        facade.collections = mediator.collections;

        return facade;
});
<|endoftext|>