<commit_before>var JSEditor = Backbone.View.extend({
    className: "block-editor",

    initialize: function(options) {
        this.setCode(options.code);
    },

    setCode: function(code) {
        if (typeof code === "string") {
            code = JSRules.parseProgram(code);
        }

        this.code = code;

        this.code.on({
            "updated": function() {
                this.trigger("updated");
            }.bind(this)
        });
    },

    toScript: function() {
        return this.code.toScript();
    },

    render: function() {
        this.$el.html(this.code.render().$el);
        return this;
    }
});

var JSToolbox = Backbone.View.extend({
    className: "block-toolbox",

    initialize: function(options) {
        var toolbox = options.toolbox || [];

        toolbox = toolbox.map(function(item) {
            if (typeof item === "function") {
                item = JSRules.parseStructure(item);
            }

            return JSRules.findRule(item);
        });

        this.toolbox = toolbox;
    },

    render: function() {
        this.$el.html(this.toolbox.map(function(item) {
            var $item = item.render().$el;

            $item.data("drag-data", item.toAST());

            $item.draggable({
                connectToSortable: ".block-statements",
                helper: function() {
                    return $item.clone(true);
                },
                revert: "invalid"
            });

            return $item;
        }));
        return this;
    }
});

var JSToolboxEditor = Backbone.View.extend({
    initialize: function(options) {
        this.editor = new JSEditor({
            code: options.code
        });

        this.editor.on("updated", function(code) {
            this.trigger("updated", code);
        }.bind(this));

        this.toolbox = new JSToolbox({
            toolbox: options.toolbox
        });

        this.render();
    },

    setCode: function(code) {
        this.editor.setCode(code);
        this.editor.render();
    },

    toScript: function() {
        return this.editor.toScript();
    },

    render: function() {
        this.$el.children().detach();
        this.$el.append([
            this.editor.render().$el,
            this.toolbox.render().$el
        ]);
    }
});

var JSRules = {
    rules: [],

    findRule: function(node, parent) {
        if (typeof node !== "object") {
            return;
        }

        for (var r = 0; r < this.rules.length; r++) {
            var Rule = this.rules[r];
            var match = Structured.matchNode(node, Rule.prototype.structure);

            if (match) {
                return new Rule({
                    node: node,
                    match: match,
                    parent: parent
                });
            }
        }

        throw new Error("No rule found for: " + JSON.stringify(node));
    },

    addRule: function(rule) {
        rule.prototype.tokens = this.tokenize(rule.prototype.structure);

        if (typeof rule.prototype.structure === "function") {
            rule.prototype.structure =
                this.parseStructure(rule.prototype.structure);
        }

        this.rules.push(rule);
        return rule;
    },

    tokenize: function(fn) {
        if (typeof fn === "object") {
            return [];
        }

        if (typeof fn === "function") {
            fn = fn.toString().replace(/function.*?{\s*/, "")
                .replace(/\s*}$/, "");
        }

        return esprima.tokenize(fn);
    },

    parseProgram: function(code) {
        return new JSProgram({
            node: esprima.parse(code)
        });
    },

    parseStructure: function(fn) {
        return esprima.parse("(" + fn + ")").body[0].expression.body.body[0];
    }
};

var JSStatements = Backbone.Collection.extend({
    initialize: function(options) {
        this.parent = options.parent;
    },

    model: function(attrs) {
        // Ignore objects that are already a JSRule model
        if (attrs instanceof JSRule) {
            return attrs;
        }

        return JSRules.findRule(attrs, this.parent);
    }
});

var JSRule = Backbone.View.extend({
    baseEvents: {
        "sort-update": "sortUpdate",
        "sort-added": "sortAdded",
        "sort-removed": "sortRemoved",
        "inside": "inside",
        "outside": "outside",
        "drop": "drop"
    },

    events: function() {
        return _.extend({}, this.baseEvents, this.additionalEvents);
    },

    initialize: function(options) {
        this.node = options.node;
        this.match = _.defaults(this.genMatch(options), {
            _: [],
            vars: {}
        });
        this.children = this.getChildModels();
        this.parent = options.parent;
    },

    inside: function() {
        this.$el.removeClass("outside");
    },

    outside: function() {
        this.$el.addClass("outside");
    },

    drop: function() {
        // Ignore the cases where this isn't a new draggable coming in
        if (!this.$el.hasClass("ui-draggable")) {
            return;
        }

        // Remove the draggable related classes/styling
        this.$el.removeClass("ui-draggable ui-draggable-handle")
            .css({width: "", height: ""});

        // Re-render after dropping the element, to avoid any dummy
        // element shenanigans from jQuery UI
        this.render();

        this.$el.parent().sortable("refresh");
    },

    sortUpdate: function(e, index) {
        var collection = this.collection;

        if (this.collection) {
            // Ignore cases where the model isn't in this collection
            if (collection.indexOf(this) < 0) {
                return;
            }

            collection.remove(this);
            collection.add(this, {at: index});
        }

        this.triggerUpdate();
    },

    sortAdded: function(e, data, index, elem) {
        var collection = this.findChildCollection();

        if (collection) {
            var newModel = JSRules.findRule(data, this);
            newModel.setElement(elem);
            collection.add(newModel, {at: index});
        }

        this.triggerUpdate();
    },

    sortRemoved: function(e, index) {
        var collection = this.findChildCollection();

        if (collection) {
            var model = collection.at(index);
            collection.remove(model);
        }

        this.triggerUpdate();
    },

    triggerUpdate: function() {
        this.trigger("updated");

        if (this.parent) {
            this.parent.triggerUpdate();
        }
    },

    findChildCollection: function() {
        // TODO: Eventually support multiple collections per model
        var children = this.children;

        for (var i = 0, l = children._.length; i < l; i++) {
            if (children._[i] instanceof JSStatements) {
                return children._[i]
            }
        }

        for (var name in children.vars) {
            if (children.vars[name] instanceof JSStatements) {
                return children.vars[name];
            }
        }
    },

    getChildModels: function(state) {
        state = state || this.match;
        var ret = {_: [], vars: {}};

        for (var i = 0; i < state._.length; i++) {
            var match = state._[i];
            ret._[i] = _.isArray(match) ?
                this.modelMatchArray(match) :
                this.modelMatch(match);
        }

        for (var name in state.vars) {
            var match = state.vars[name];
            ret.vars[name] = _.isArray(match) ?
                this.modelMatchArray(match) :
                this.modelMatch(match);
        }

        return ret;
    },

    modelMatch: function(match) {
        return JSRules.findRule(match, this);
    },

    modelMatchArray: function(matches) {
        return new JSStatements(matches, {
            parent: this
        });
    },

    genMatch: function() {
        throw new Error("No genMatch method implemented.");
    },

    toAST: function() {
        throw new Error("No toAST method implemented.");
    },

    toScript: function() {
        return escodegen.generate(this.toAST());
    },

    getAST: function() {
        var state = this.match;
        var ret = {_: [], vars: {}};

        for (var i = 0; i < state._.length; i++) {
            var match = state._[i];
            ret._[i] = _.isArray(match) ?
                this.astComponentArray(match, "_", i) :
                this.astComponent(match, "_", i);
        }

        for (var name in state.vars) {
            var match = state.vars[name];
            ret.vars[name] = _.isArray(match) ?
                this.astComponentArray(match, "vars", name) :
                this.astComponent(match, "vars", name);
        }

        return ret;
    },

    astComponent: function(match, ns, id) {
        return this.children[ns][id].toAST();
    },

    astComponentArray: function(matches, ns, id) {
        return this.children[ns][id].map(function(model) {
            return model.toAST();
        });
    },

    renderStatements: function(collection) {
        var $div = $("
").addClass("block block-statements");

        $div.html(collection.map(function(statement) {
            return statement.render().el;
        }));

        var getIndex = function(ui) {
            if (ui.helper) {
                return ui.placeholder.parent().children()
                    .not(".ui-sortable-helper")
                    .not(ui.item)
                    .index(ui.placeholder);
            } else {
                return ui.item.index();
            }
        };

        var outside = false;
        var stopping = false;

        $div.sortable({
            revert: false,
            change: function(e, ui) {
                ui.item.trigger("sort-update", getIndex(ui));
            },
            receive: function(e, ui) {
                if (outside) {
                    ui.item.triggerHandler("inside");
                }
                outside = false;
            },
            over: function(e, ui) {
                if (ui.helper.hasClass("ui-draggable")) {
                    var data = ui.helper.data("drag-data");
                    ui.placeholder.trigger("sort-added",
                        [data, getIndex(ui), ui.item]);
                }

                outside = false;
                ui.item.triggerHandler("inside");
                ui.placeholder.removeClass("outside");
            },
            beforeStop: function(e, ui) {
                stopping = true;

                // Remove item when dropped outside the sortable
                if (outside) {
                    ui.item.trigger("sort-removed", getIndex(ui));
                    ui.item.remove();
                }
            },
            stop: function(e, ui) {
                stopping = false;
                ui.item.triggerHandler("drop");
            },
            out: function(e, ui) {
                // An extra 'out' event fires while stopping, we ignore it
                if (stopping) {
                    return;
                }

                outside = true;

                // Remove the model when the external draggable is moved
                // outside of the sortable (sortable already removes the elem)
                if (ui.helper && ui.helper.hasClass("ui-draggable")) {
                    ui.item.trigger("sort-removed", getIndex(ui));
                }

                ui.placeholder.addClass("outside");
                ui.item.triggerHandler("outside");
            }
        });

        return $div[0];
    },

    renderInput: function(statement) {
        // TODO: Handle the input type
        var $div = $("
").addClass("block block-input");
        $div.html(statement.render().el);
        return $div[0];
    }
});

var JSASTRule = JSRule.extend({
    className: "block block-statement",

    genMatch: function(options) {
        return options.match;
    },

    toAST: function() {
        return Structured.injectData(this.structure, this.getAST());
    },

    render: function() {
        var children = this.children;
        var tokens = this.tokens;
        var _pos = 0;

        var buildTag = function(type, token) {
            return "" + token.value + "";
        };

        tokens = tokens.map(function(token) {
            if (token.type === "Identifier") {
                if (token.value === "_") {
                    return children._[_pos++].render().el;
                } else {
                    return buildTag("entity name function call", token);
                }
            } else if (token.type === "Punctuator") {
                switch(token.value) {
                    case ".":
                        return buildTag("keyword dot", token);
                    case "=":
                    case "+":
                    case "!":
                    case "-":
                    case "|":
                    case "*":
                    case "/":
                        token.value = " " + token.value + " ";
                        return buildTag("keyword operator", token);
                    case ",":
                        return ", ";
                }
            } else if (token.type === "Keyword") {
                token.value += " ";
                return buildTag("keyword", token);

            } else if (token.type === "Boolean") {
                return buildTag("constant language", token);

            } else if (token.type === "Numeric") {
                return buildTag("constant numeric", token);
            }

            return token.value;
        });

        this.$el.html(tokens);

        return this;
    }
});<commit_msg>Fix settings of parent on the collections.<commit_after>var JSEditor = Backbone.View.extend({
    className: "block-editor",

    initialize: function(options) {
        this.setCode(options.code);
    },

    setCode: function(code) {
        if (typeof code === "string") {
            code = JSRules.parseProgram(code);
        }

        this.code = code;

        this.code.on({
            "updated": function() {
                this.trigger("updated");
            }.bind(this)
        });
    },

    toScript: function() {
        return this.code.toScript();
    },

    render: function() {
        this.$el.html(this.code.render().$el);
        return this;
    }
});

var JSToolbox = Backbone.View.extend({
    className: "block-toolbox",

    initialize: function(options) {
        var toolbox = options.toolbox || [];

        toolbox = toolbox.map(function(item) {
            if (typeof item === "function") {
                item = JSRules.parseStructure(item);
            }

            return JSRules.findRule(item);
        });

        this.toolbox = toolbox;
    },

    render: function() {
        this.$el.html(this.toolbox.map(function(item) {
            var $item = item.render().$el;

            $item.data("drag-data", item.toAST());

            $item.draggable({
                connectToSortable: ".block-statements",
                helper: function() {
                    return $item.clone(true);
                },
                revert: "invalid"
            });

            return $item;
        }));
        return this;
    }
});

var JSToolboxEditor = Backbone.View.extend({
    initialize: function(options) {
        this.editor = new JSEditor({
            code: options.code
        });

        this.editor.on("updated", function(code) {
            this.trigger("updated", code);
        }.bind(this));

        this.toolbox = new JSToolbox({
            toolbox: options.toolbox
        });

        this.render();
    },

    setCode: function(code) {
        this.editor.setCode(code);
        this.editor.render();
    },

    toScript: function() {
        return this.editor.toScript();
    },

    render: function() {
        this.$el.children().detach();
        this.$el.append([
            this.editor.render().$el,
            this.toolbox.render().$el
        ]);
    }
});

var JSRules = {
    rules: [],

    findRule: function(node, parent) {
        if (typeof node !== "object") {
            return;
        }

        for (var r = 0; r < this.rules.length; r++) {
            var Rule = this.rules[r];
            var match = Structured.matchNode(node, Rule.prototype.structure);

            if (match) {
                return new Rule({
                    node: node,
                    match: match,
                    parent: parent
                });
            }
        }

        throw new Error("No rule found for: " + JSON.stringify(node));
    },

    addRule: function(rule) {
        rule.prototype.tokens = this.tokenize(rule.prototype.structure);

        if (typeof rule.prototype.structure === "function") {
            rule.prototype.structure =
                this.parseStructure(rule.prototype.structure);
        }

        this.rules.push(rule);
        return rule;
    },

    tokenize: function(fn) {
        if (typeof fn === "object") {
            return [];
        }

        if (typeof fn === "function") {
            fn = fn.toString().replace(/function.*?{\s*/, "")
                .replace(/\s*}$/, "");
        }

        return esprima.tokenize(fn);
    },

    parseProgram: function(code) {
        return new JSProgram({
            node: esprima.parse(code)
        });
    },

    parseStructure: function(fn) {
        return esprima.parse("(" + fn + ")").body[0].expression.body.body[0];
    }
};

var JSStatements = Backbone.Collection.extend({
    model: function(attrs, options) {
        // Ignore objects that are already a JSRule model
        if (attrs instanceof JSRule) {
            return attrs;
        }

        return JSRules.findRule(attrs, options.parent);
    }
});

var JSRule = Backbone.View.extend({
    baseEvents: {
        "sort-update": "sortUpdate",
        "sort-added": "sortAdded",
        "sort-removed": "sortRemoved",
        "inside": "inside",
        "outside": "outside",
        "drop": "drop"
    },

    events: function() {
        return _.extend({}, this.baseEvents, this.additionalEvents);
    },

    initialize: function(options) {
        this.node = options.node;
        this.match = _.defaults(this.genMatch(options), {
            _: [],
            vars: {}
        });
        this.children = this.getChildModels();
        this.parent = options.parent;
    },

    inside: function() {
        this.$el.removeClass("outside");
    },

    outside: function() {
        this.$el.addClass("outside");
    },

    drop: function() {
        // Ignore the cases where this isn't a new draggable coming in
        if (!this.$el.hasClass("ui-draggable")) {
            return;
        }

        // Remove the draggable related classes/styling
        this.$el.removeClass("ui-draggable ui-draggable-handle")
            .css({width: "", height: ""});

        // Re-render after dropping the element, to avoid any dummy
        // element shenanigans from jQuery UI
        this.render();

        this.$el.parent().sortable("refresh");
    },

    sortUpdate: function(e, index) {
        var collection = this.collection;

        if (this.collection) {
            // Ignore cases where the model isn't in this collection
            if (collection.indexOf(this) < 0) {
                return;
            }

            collection.remove(this);
            collection.add(this, {at: index});
        }

        this.triggerUpdate();
    },

    sortAdded: function(e, data, index, elem) {
        var collection = this.findChildCollection();

        if (collection) {
            var newModel = JSRules.findRule(data, this);
            newModel.setElement(elem);
            collection.add(newModel, {at: index});
        }

        this.triggerUpdate();
    },

    sortRemoved: function(e, index) {
        var collection = this.findChildCollection();

        if (collection) {
            var model = collection.at(index);
            collection.remove(model);
        }

        this.triggerUpdate();
    },

    triggerUpdate: function() {
        this.trigger("updated");

        if (this.parent) {
            this.parent.triggerUpdate();
        }
    },

    findChildCollection: function() {
        // TODO: Eventually support multiple collections per model
        var children = this.children;

        for (var i = 0, l = children._.length; i < l; i++) {
            if (children._[i] instanceof JSStatements) {
                return children._[i]
            }
        }

        for (var name in children.vars) {
            if (children.vars[name] instanceof JSStatements) {
                return children.vars[name];
            }
        }
    },

    getChildModels: function(state) {
        state = state || this.match;
        var ret = {_: [], vars: {}};

        for (var i = 0; i < state._.length; i++) {
            var match = state._[i];
            ret._[i] = _.isArray(match) ?
                this.modelMatchArray(match) :
                this.modelMatch(match);
        }

        for (var name in state.vars) {
            var match = state.vars[name];
            ret.vars[name] = _.isArray(match) ?
                this.modelMatchArray(match) :
                this.modelMatch(match);
        }

        return ret;
    },

    modelMatch: function(match) {
        return JSRules.findRule(match, this);
    },

    modelMatchArray: function(matches) {
        return new JSStatements(matches, {
            parent: this
        });
    },

    genMatch: function() {
        throw new Error("No genMatch method implemented.");
    },

    toAST: function() {
        throw new Error("No toAST method implemented.");
    },

    toScript: function() {
        return escodegen.generate(this.toAST());
    },

    getAST: function() {
        var state = this.match;
        var ret = {_: [], vars: {}};

        for (var i = 0; i < state._.length; i++) {
            var match = state._[i];
            ret._[i] = _.isArray(match) ?
                this.astComponentArray(match, "_", i) :
                this.astComponent(match, "_", i);
        }

        for (var name in state.vars) {
            var match = state.vars[name];
            ret.vars[name] = _.isArray(match) ?
                this.astComponentArray(match, "vars", name) :
                this.astComponent(match, "vars", name);
        }

        return ret;
    },

    astComponent: function(match, ns, id) {
        return this.children[ns][id].toAST();
    },

    astComponentArray: function(matches, ns, id) {
        return this.children[ns][id].map(function(model) {
            return model.toAST();
        });
    },

    renderStatements: function(collection) {
        var $div = $("
").addClass("block block-statements");

        $div.html(collection.map(function(statement) {
            return statement.render().el;
        }));

        var getIndex = function(ui) {
            if (ui.helper) {
                return ui.placeholder.parent().children()
                    .not(".ui-sortable-helper")
                    .not(ui.item)
                    .index(ui.placeholder);
            } else {
                return ui.item.index();
            }
        };

        var outside = false;
        var stopping = false;

        $div.sortable({
            revert: false,
            change: function(e, ui) {
                ui.item.trigger("sort-update", getIndex(ui));
            },
            receive: function(e, ui) {
                if (outside) {
                    ui.item.triggerHandler("inside");
                }
                outside = false;
            },
            over: function(e, ui) {
                if (ui.helper.hasClass("ui-draggable")) {
                    var data = ui.helper.data("drag-data");
                    ui.placeholder.trigger("sort-added",
                        [data, getIndex(ui), ui.item]);
                }

                outside = false;
                ui.item.triggerHandler("inside");
                ui.placeholder.removeClass("outside");
            },
            beforeStop: function(e, ui) {
                stopping = true;

                // Remove item when dropped outside the sortable
                if (outside) {
                    ui.item.trigger("sort-removed", getIndex(ui));
                    ui.item.remove();
                }
            },
            stop: function(e, ui) {
                stopping = false;
                ui.item.triggerHandler("drop");
            },
            out: function(e, ui) {
                // An extra 'out' event fires while stopping, we ignore it
                if (stopping) {
                    return;
                }

                outside = true;

                // Remove the model when the external draggable is moved
                // outside of the sortable (sortable already removes the elem)
                if (ui.helper && ui.helper.hasClass("ui-draggable")) {
                    ui.item.trigger("sort-removed", getIndex(ui));
                }

                ui.placeholder.addClass("outside");
                ui.item.triggerHandler("outside");
            }
        });

        return $div[0];
    },

    renderInput: function(statement) {
        // TODO: Handle the input type
        var $div = $("
").addClass("block block-input");
        $div.html(statement.render().el);
        return $div[0];
    }
});

var JSASTRule = JSRule.extend({
    className: "block block-statement",

    genMatch: function(options) {
        return options.match;
    },

    toAST: function() {
        return Structured.injectData(this.structure, this.getAST());
    },

    render: function() {
        var children = this.children;
        var tokens = this.tokens;
        var _pos = 0;

        var buildTag = function(type, token) {
            return "" + token.value + "";
        };

        tokens = tokens.map(function(token) {
            if (token.type === "Identifier") {
                if (token.value === "_") {
                    return children._[_pos++].render().el;
                } else {
                    return buildTag("entity name function call", token);
                }
            } else if (token.type === "Punctuator") {
                switch(token.value) {
                    case ".":
                        return buildTag("keyword dot", token);
                    case "=":
                    case "+":
                    case "!":
                    case "-":
                    case "|":
                    case "*":
                    case "/":
                        token.value = " " + token.value + " ";
                        return buildTag("keyword operator", token);
                    case ",":
                        return ", ";
                }
            } else if (token.type === "Keyword") {
                token.value += " ";
                return buildTag("keyword", token);

            } else if (token.type === "Boolean") {
                return buildTag("constant language", token);

            } else if (token.type === "Numeric") {
                return buildTag("constant numeric", token);
            }

            return token.value;
        });

        this.$el.html(tokens);

        return this;
    }
});<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var Base64 = require('js-base64').Base64;
  var moment = require('moment-timezone');
  var Timezone = app.Timezone || require('./timezone.js');

  var TimezoneList = function() {
    this.KEY_CURRENT_LOCATION = 'Current_Location';
    this.data = {};
    this.selected = [];
  };

  TimezoneList.prototype.get = function() {
    if (Object.keys(this.data).length === 0 || this.selected.length === 0) {
      return [];
    }

    var selected_timezone = this.selected.map(function(key) {
      return [key, this.data[key]];
    }.bind(this));

    return this._getTimelist(selected_timezone);
  };

  TimezoneList.prototype.updateData = function() {
    var params = this._getUrlSearchParams();
    var customList = this._decodeTimezoneList(params.custom_tzlist);
    var hiddenList = this._decodeTimezoneList(params.hidden_tzlist);
    this.data = this._createTimezoneData(Timezone.LOCATION_NAMES, customList, hiddenList);
  };

  TimezoneList.prototype.setCustomTimezoneList = function(list) {
    this._setUrlSearchParam('custom_tzlist', Base64.encodeURI(list.join(',')));
  };

  TimezoneList.prototype.setHiddenTimezoneList = function(list) {
    this._setUrlSearchParam('hidden_tzlist', Base64.encodeURI(list.join(',')));
  };

  TimezoneList.prototype.getLocationName = function(tzName) {
    return tzName.substring(tzName.lastIndexOf('/') + 1).replace(/_/g, ' ');
  };

  TimezoneList.prototype._getTimelist = function(timezone) {
    var date = new Date();
    var currentTime = date.getTime();
    var currentTimezoneOffset = date.getTimezoneOffset();

    return timezone.map(function(item) {
      var name = this.getLocationName(item[0]);
      var time = parseInt(item[1], 10);
      time = new Date(currentTime + time * 1000 + currentTimezoneOffset * 60 * 1000);
      return [name, time];
    }.bind(this));
  };

  TimezoneList.prototype._createTimezoneData = function(defaultList, customList, hiddenList) {
    var data  = {};
    var now = Date.now();

    defaultList.forEach(function(name) {
      data[name] = moment.tz.zone(name.split('#/')[0]).utcOffset(now) * (-60);
    });

    data[this.KEY_CURRENT_LOCATION] = new Date().getTimezoneOffset() * (-60);

    customList.forEach(function(name) {
      if (name in data) {
        return;
      }
      var tz = moment.tz.zone(name.split('#/')[0]);
      if (tz) {
        data[name] = tz.utcOffset(now) * (-60);
      }
    });

    hiddenList.forEach(function(name) {
      delete data[name];
    });

    return data;
  };

  TimezoneList.prototype._decodeTimezoneList = function(value) {
    return (value ? Base64.decode(value).split(',') : []);
  };

  TimezoneList.prototype._getUrlSearchParams = function() {
    return location.search.substring(1).split('&').reduce(function(ret, pair) {
      var items = pair.split('=');
      var key = decodeURIComponent(items[0] || '');
      var value = decodeURIComponent(items[1] || '');
      ret[key] = value;
      return ret;
    }, {});
  };

  TimezoneList.prototype._setUrlSearchParam = function(name, value) {
    var params = this._getUrlSearchParams();
    params[name] = value;
    var search = '?' + Object.keys(params).map(function(name) {
      return encodeURIComponent(name) + '=' + encodeURIComponent(params[name]);
    }).join('&');
    history.replaceState(null, null, search + location.hash);
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = TimezoneList;
  } else {
    app.TimezoneList = TimezoneList;
  }
})(this.app || (this.app = {}));
<commit_msg>Remove code of updating timezone data with url query parameters<commit_after>(function(app) {
  'use strict';

  var moment = require('moment-timezone');
  var Timezone = app.Timezone || require('./timezone.js');

  var TimezoneList = function() {
    this.KEY_CURRENT_LOCATION = 'Current_Location';
    this.data = {};
    this.selected = [];
  };

  TimezoneList.prototype.get = function() {
    if (Object.keys(this.data).length === 0 || this.selected.length === 0) {
      return [];
    }

    var selected_timezone = this.selected.map(function(key) {
      return [key, this.data[key]];
    }.bind(this));

    return this._getTimelist(selected_timezone);
  };

  TimezoneList.prototype.updateData = function() {
    this.data = this._createTimezoneData(Timezone.LOCATION_NAMES);
  };

  TimezoneList.prototype.getLocationName = function(tzName) {
    return tzName.substring(tzName.lastIndexOf('/') + 1).replace(/_/g, ' ');
  };

  TimezoneList.prototype._getTimelist = function(timezone) {
    var date = new Date();
    var currentTime = date.getTime();
    var currentTimezoneOffset = date.getTimezoneOffset();

    return timezone.map(function(item) {
      var name = this.getLocationName(item[0]);
      var time = parseInt(item[1], 10);
      time = new Date(currentTime + time * 1000 + currentTimezoneOffset * 60 * 1000);
      return [name, time];
    }.bind(this));
  };

  TimezoneList.prototype._createTimezoneData = function(defaultList) {
    var data  = {};
    var now = Date.now();

    defaultList.forEach(function(name) {
      data[name] = moment.tz.zone(name.split('#/')[0]).utcOffset(now) * (-60);
    });

    data[this.KEY_CURRENT_LOCATION] = new Date().getTimezoneOffset() * (-60);

    return data;
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = TimezoneList;
  } else {
    app.TimezoneList = TimezoneList;
  }
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>/**
 * Created by dat on 4/5/17.
 */
var hic = (function (hic) {

    hic.TrackRenderer = function (browser, size, $container, trackRenderPair, trackPair, axis, order) {

        this.browser = browser;

        this.trackRenderPair = trackRenderPair;

        this.track = trackPair[axis];

        this.id = _.uniqueId('trackRenderer_');
        this.axis = axis;
        this.initializationHelper($container, size, order);
    };

    hic.TrackRenderer.prototype.initializationHelper = function ($container, size, order) {

        var self = this,
            str,
            doShowLabelAndGear,
            $x_track_label,
            $x_track_menu_container,
            spinner;

        // track canvas container
        this.$viewport = ('x' === this.axis) ? $('
') : $('
');
        if (size.width) {
            this.$viewport.width(size.width);
        }
        if (size.height) {
            this.$viewport.height(size.height);
        }
        $container.append(this.$viewport);
        this.$viewport.css({order: order});

        // canvas
        this.$canvas = $('<canvas>');
        this.$viewport.append(this.$canvas);
        this.ctx = this.$canvas.get(0).getContext("2d");

        if ('x' === this.axis) {

            // label
            this.$label = $('
');
            str = this.track.name || 'untitled';
            this.$label.text(str);

            // note the pre-existing state of track labels/gear. hide/show accordingly.
            $x_track_label = $container.find(this.$label);
            doShowLabelAndGear = (0 === _.size($x_track_label)) ? true : $x_track_label.is(':visible');

            this.$viewport.append(this.$label);
        }

        // IGV STYLE SPINNER
        // spinner = igv.spinner("24px")
        // if ('x' === this.axis) {
        //     spinner.style.position = "absolute";
        //     spinner.style.left = "0px";
        //     spinner.style.top = "0px"
        // }
        // this.$viewport[0].appendChild(spinner);

        // track spinner container
        this.$spinner = ('x' === this.axis) ? $('
') : $('
');
        this.$viewport.append(this.$spinner);

        // throbber
        // size: see $hic-viewport-spinner-size in .scss files
        this.throbber = Throbber({color: 'rgb(64, 64, 64)', size: 32, padding: 7});
        this.throbber.appendTo(this.$spinner.get(0));
        this.stopSpinner();

        if ('x' === this.axis) {

            // igvjs compatibility
            this.track.trackView = this;
            this.track.trackView.trackDiv = this.$viewport.get(0);

            igv.appendRightHandGutter.call(this, this.$viewport);

            // this.$menu_container = $('
');
            // this.$viewport.append(this.$menu_container);

            // this.$menu_button = $('');
            // this.$menu_container.append(this.$menu_button);

            // this.$menu_button.click(function (e) {
            //     e.stopPropagation();
            //     igv.popover.presentTrackGearMenu(e.pageX, e.pageY, self, igv.browser);
            // });

            // this.$viewport.on('click', function (e) {
            //     e.stopPropagation();
            //     $container.find('.x-track-label').toggle();
            //     $container.find('.x-track-menu-container').toggle();
            // });

            // if (doShowLabelAndGear) {
            //     this.$label.show();
            //     // this.$menu_container.show();
            // } else {
            //     this.$label.hide();
            //     // this.$menu_container.hide();
            // }

        }

        this.configTrackTransforms();

    };

    hic.TrackRenderer.prototype.configTrackTransforms = function () {

        this.canvasTransform = ('y' === this.axis) ? hic.reflectionRotationWithContext : hic.identityTransformWithContext;

        this.labelReflectionTransform = ('y' === this.axis) ? hic.reflectionAboutYAxisAtOffsetWithContext : function (context, exe) { /* nuthin */
        };

    };

    hic.TrackRenderer.prototype.syncCanvas = function () {

        this.$canvas.width(this.$viewport.width());
        this.$canvas.attr('width', this.$viewport.width());

        this.$canvas.height(this.$viewport.height());
        this.$canvas.attr('height', this.$viewport.height());

    };

    hic.TrackRenderer.prototype.setTrackName = function (name) {

        if ('x' === this.axis) {
            this.track.name = name;
            this.$label.text(name);
        }

    };

    hic.TrackRenderer.prototype.setColor = function (color) {

        setColor(this.trackRenderPair.x);
        setColor(this.trackRenderPair.y);

        function setColor(trackRenderer) {
            trackRenderer.tile = undefined;
            trackRenderer.track.color = color;
        }

        this.browser.renderTrackXY(this.trackRenderPair);

    };

    // hic.TrackRenderer.prototype.dataRange = function () {
    //     return this.track.dataRange ? this.track.dataRange : undefined;
    // };

    // hic.TrackRenderer.prototype.setDataRange = function (min, max, autoscale) {
    //
    //     setDataRange.call(this.trackRenderPair.x);
    //     setDataRange.call(this.trackRenderPair.y);
    //
    //     function setDataRange() {
    //
    //         this.tile = undefined
    //
    //         this.track.dataRange = {
    //             min: min,
    //             max: max
    //         }
    //
    //         this.track.autscale = autoscale;
    //     }
    //
    //     this.browser.renderTrackXY(this.trackRenderPair);
    //
    // };

    hic.TrackRenderer.prototype.dataRange = function () {
        return this.track.dataRange ? this.track.dataRange : undefined;
    };

    hic.TrackRenderer.prototype.setDataRange = function (min, max, autoscale) {

        if (min !== undefined) {
            this.track.dataRange.min = min;
            this.track.config.min = min;
        }

        if (max !== undefined) {
            this.track.dataRange.max = max;
            this.track.config.max = max;
        }

        this.track.autoscale = autoscale;
        this.track.config.autoScale = autoscale;

        this.repaintViews();
    };

    /**
     * Return a promise to get the renderer ready to paint,  that is with a valid tile, loading features
     * and drawing tile if neccessary.
     *
     * @returns {*}
     */
    hic.TrackRenderer.prototype.readyToPaint = function () {
        var self = this,
            genomicState, chrName, lengthPixel, lengthBP, startBP, endBP;

        genomicState = self.browser.genomicState(self.axis);
        chrName = genomicState.chromosome.name;

        if (self.tile && self.tile.containsRange(chrName, genomicState.startBP, genomicState.endBP, genomicState.bpp)) {

            return Promise.resolve();

        } else if (genomicState.bpp * Math.max(self.$canvas.width(), self.$canvas.height()) > self.track.visibilityWindow) {

            return Promise.resolve();

        } else {

            // Expand the requested range so we can pan a bit without reloading
            lengthPixel = 3 * Math.max(self.$canvas.width(), self.$canvas.height());
            lengthBP = Math.round(genomicState.bpp * lengthPixel);
            startBP = Math.max(0, Math.round(genomicState.startBP - lengthBP / 3));
            endBP = startBP + lengthBP;

            self.startSpinner();

            return self.track

                .getFeatures(genomicState.chromosome.name, startBP, endBP, genomicState.bpp)

                .then(function (features) {

                    var buffer, ctx;
                    buffer = document.createElement('canvas');
                    buffer.width = 'x' === self.axis ? lengthPixel : self.$canvas.width();
                    buffer.height = 'x' === self.axis ? self.$canvas.height() : lengthPixel;
                    ctx = buffer.getContext("2d");
                    if (features) {

                        if (features.length === 0) {
                            console.log("Zero");
                        }

                        self.canvasTransform(ctx);

                        self.drawConfiguration =
                            {
                                features: features,
                                context: ctx,
                                pixelWidth: lengthPixel,
                                pixelHeight: Math.min(buffer.width, buffer.height),
                                bpStart: startBP,
                                bpEnd: endBP,
                                bpPerPixel: genomicState.bpp,
                                genomicState: genomicState,
                                viewportContainerX: (genomicState.startBP - startBP) / genomicState.bpp,
                                viewportContainerWidth: Math.max(self.$canvas.width(), self.$canvas.height()),
                                labelTransform: self.labelReflectionTransform
                            };

                        self.track.draw(self.drawConfiguration);

                    } else {
                        ctx.clearRect(0, 0, self.$canvas.width(), self.$canvas.height());
                    }

                    self.tile = new Tile(chrName, startBP, endBP, genomicState.bpp, buffer);
                    return "OK";

                })
        }
    }

    /**
     *
     */
    hic.TrackRenderer.prototype.repaint = function () {

        var self = this,
            genomicState,
            chrName;

        genomicState = self.browser.genomicState(self.axis);
        if (!this.checkZoomIn()) {
                self.tile = undefined;
                self.ctx.clearRect(0, 0, self.$canvas.width(), self.$canvas.height());
            }

        chrName = genomicState.chromosome.name;

        if (self.tile && self.tile.containsRange(chrName, genomicState.startBP, genomicState.endBP, genomicState.bpp)) {
            self.drawTileWithGenomicState(self.tile, genomicState);

        } else {
            self.readyToPaint()
                .then(function (ignore) {
                    self.drawTileWithGenomicState(self.tile, genomicState);
                })
                .catch(function (error) {
                    console.error(error);
                })

        }

    };

    hic.TrackRenderer.prototype.checkZoomIn = function () {

        if (this.track.visibilityWindow && this.track.visibilityWindow > 0) {

            if ((genomicState.bpp * Math.max(this.$canvas.width(), this.$canvas.height()) > this.track.visibilityWindow)) {
                return false;
            }
        }
        return true;
    }

    hic.TrackRenderer.prototype.drawTileWithGenomicState = function (tile, genomicState) {

        if (tile) {

            this.ctx.clearRect(0, 0, this.$canvas.width(), this.$canvas.height());

            this.offsetPixel = Math.round((tile.startBP - genomicState.startBP) / genomicState.bpp);
            if ('x' === this.axis) {
                this.ctx.drawImage(tile.buffer, this.offsetPixel, 0);
            } else {
                this.ctx.drawImage(tile.buffer, 0, this.offsetPixel);
            }

            // this.ctx.save();
            // this.ctx.restore();
        }
    };

    hic.TrackRenderer.prototype.startSpinner = function () {

        this.browser.startSpinner();

        //igv.startSpinnerAtParentElement(this.$viewport[0]);

        //    this.$spinner.show();
        //    this.throbber.start();
        //    console.log("Spinner show");
    };

    hic.TrackRenderer.prototype.stopSpinner = function () {

        this.browser.stopSpinner();

        //igv.stopSpinnerAtParentElement(this.$viewport[0]);

        //    this.throbber.stop();
        //    this.$spinner.hide();
        //    console.log("Spinner stop");
    };

    hic.TrackRenderer.prototype.isLoading = function () {
        return !(undefined === this.loading);
    };

    Tile = function (chr, startBP, endBP, bpp, buffer) {
        this.chr = chr;
        this.startBP = startBP;
        this.endBP = endBP;
        this.bpp = bpp;
        this.buffer = buffer;
    };

    Tile.prototype.containsRange = function (chr, startBP, endBP, bpp) {
        return chr === this.chr && this.bpp === bpp && this.startBP <= startBP && this.endBP >= endBP;
    };

    return hic;

})
(hic || {});
<commit_msg>fix track autoscale problem<commit_after>/**
 * Created by dat on 4/5/17.
 */
var hic = (function (hic) {

    hic.TrackRenderer = function (browser, size, $container, trackRenderPair, trackPair, axis, order) {

        this.browser = browser;

        this.trackRenderPair = trackRenderPair;

        this.track = trackPair[axis];

        this.id = _.uniqueId('trackRenderer_');
        this.axis = axis;
        this.initializationHelper($container, size, order);
    };

    hic.TrackRenderer.prototype.initializationHelper = function ($container, size, order) {

        var self = this,
            str,
            doShowLabelAndGear,
            $x_track_label,
            $x_track_menu_container,
            spinner;

        // track canvas container
        this.$viewport = ('x' === this.axis) ? $('
') : $('
');
        if (size.width) {
            this.$viewport.width(size.width);
        }
        if (size.height) {
            this.$viewport.height(size.height);
        }
        $container.append(this.$viewport);
        this.$viewport.css({order: order});

        // canvas
        this.$canvas = $('<canvas>');
        this.$viewport.append(this.$canvas);
        this.ctx = this.$canvas.get(0).getContext("2d");

        if ('x' === this.axis) {

            // label
            this.$label = $('
');
            str = this.track.name || 'untitled';
            this.$label.text(str);

            // note the pre-existing state of track labels/gear. hide/show accordingly.
            $x_track_label = $container.find(this.$label);
            doShowLabelAndGear = (0 === _.size($x_track_label)) ? true : $x_track_label.is(':visible');

            this.$viewport.append(this.$label);
        }

        // IGV STYLE SPINNER
        // spinner = igv.spinner("24px")
        // if ('x' === this.axis) {
        //     spinner.style.position = "absolute";
        //     spinner.style.left = "0px";
        //     spinner.style.top = "0px"
        // }
        // this.$viewport[0].appendChild(spinner);

        // track spinner container
        this.$spinner = ('x' === this.axis) ? $('
') : $('
');
        this.$viewport.append(this.$spinner);

        // throbber
        // size: see $hic-viewport-spinner-size in .scss files
        this.throbber = Throbber({color: 'rgb(64, 64, 64)', size: 32, padding: 7});
        this.throbber.appendTo(this.$spinner.get(0));
        this.stopSpinner();

        if ('x' === this.axis) {

            // igvjs compatibility
            this.track.trackView = this;
            this.track.trackView.trackDiv = this.$viewport.get(0);

            igv.appendRightHandGutter.call(this, this.$viewport);

            // this.$menu_container = $('
');
            // this.$viewport.append(this.$menu_container);

            // this.$menu_button = $('');
            // this.$menu_container.append(this.$menu_button);

            // this.$menu_button.click(function (e) {
            //     e.stopPropagation();
            //     igv.popover.presentTrackGearMenu(e.pageX, e.pageY, self, igv.browser);
            // });

            // this.$viewport.on('click', function (e) {
            //     e.stopPropagation();
            //     $container.find('.x-track-label').toggle();
            //     $container.find('.x-track-menu-container').toggle();
            // });

            // if (doShowLabelAndGear) {
            //     this.$label.show();
            //     // this.$menu_container.show();
            // } else {
            //     this.$label.hide();
            //     // this.$menu_container.hide();
            // }

        }

        this.configTrackTransforms();

    };

    hic.TrackRenderer.prototype.configTrackTransforms = function () {

        this.canvasTransform = ('y' === this.axis) ? hic.reflectionRotationWithContext : hic.identityTransformWithContext;

        this.labelReflectionTransform = ('y' === this.axis) ? hic.reflectionAboutYAxisAtOffsetWithContext : function (context, exe) { /* nuthin */
        };

    };

    hic.TrackRenderer.prototype.syncCanvas = function () {

        this.$canvas.width(this.$viewport.width());
        this.$canvas.attr('width', this.$viewport.width());

        this.$canvas.height(this.$viewport.height());
        this.$canvas.attr('height', this.$viewport.height());

    };

    hic.TrackRenderer.prototype.setTrackName = function (name) {

        if ('x' === this.axis) {
            this.track.name = name;
            this.$label.text(name);
        }

    };

    hic.TrackRenderer.prototype.setColor = function (color) {

        setColor(this.trackRenderPair.x);
        setColor(this.trackRenderPair.y);

        function setColor(trackRenderer) {
            trackRenderer.tile = undefined;
            trackRenderer.track.color = color;
        }

        this.browser.renderTrackXY(this.trackRenderPair);

    };

    // hic.TrackRenderer.prototype.dataRange = function () {
    //     return this.track.dataRange ? this.track.dataRange : undefined;
    // };

    // hic.TrackRenderer.prototype.setDataRange = function (min, max, autoscale) {
    //
    //     setDataRange.call(this.trackRenderPair.x);
    //     setDataRange.call(this.trackRenderPair.y);
    //
    //     function setDataRange() {
    //
    //         this.tile = undefined
    //
    //         this.track.dataRange = {
    //             min: min,
    //             max: max
    //         }
    //
    //         this.track.autscale = autoscale;
    //     }
    //
    //     this.browser.renderTrackXY(this.trackRenderPair);
    //
    // };

    hic.TrackRenderer.prototype.dataRange = function () {
        return this.track.dataRange ? this.track.dataRange : undefined;
    };

    hic.TrackRenderer.prototype.setDataRange = function (min, max, autoscale) {

        if (min !== undefined) {
            this.track.dataRange.min = min;
            this.track.config.min = min;
        }

        if (max !== undefined) {
            this.track.dataRange.max = max;
            this.track.config.max = max;
        }

        this.track.autoscale = autoscale;
        this.track.config.autoScale = autoscale;

        this.repaintViews();
    };

    /**
     * Return a promise to get the renderer ready to paint,  that is with a valid tile, loading features
     * and drawing tile if neccessary.
     *
     * @returns {*}
     */
    hic.TrackRenderer.prototype.readyToPaint = function () {
        var self = this,
            genomicState, chrName, lengthPixel, lengthBP, startBP, endBP;

        genomicState = self.browser.genomicState(self.axis);
        chrName = genomicState.chromosome.name;

        if (self.tile && self.tile.containsRange(chrName, genomicState.startBP, genomicState.endBP, genomicState.bpp)) {

            return Promise.resolve();

        } else if (genomicState.bpp * Math.max(self.$canvas.width(), self.$canvas.height()) > self.track.visibilityWindow) {

            return Promise.resolve();

        } else {

            // Expand the requested range so we can pan a bit without reloading
            lengthPixel = 3 * Math.max(self.$canvas.width(), self.$canvas.height());
            lengthBP = Math.round(genomicState.bpp * lengthPixel);
            startBP = Math.max(0, Math.round(genomicState.startBP - lengthBP / 3));
            endBP = startBP + lengthBP;

            self.startSpinner();

            return self.track

                .getFeatures(genomicState.chromosome.name, startBP, endBP, genomicState.bpp)

                .then(function (features) {

                    var buffer, ctx;
                    buffer = document.createElement('canvas');
                    buffer.width = 'x' === self.axis ? lengthPixel : self.$canvas.width();
                    buffer.height = 'x' === self.axis ? self.$canvas.height() : lengthPixel;
                    ctx = buffer.getContext("2d");
                    if (features) {

                        if (typeof self.track.doAutoscale === 'function') {
                            self.track.doAutoscale(allFeatures);
                        } else {
                            self.track.dataRange = igv.doAutoscale(features);
                        }

                        self.canvasTransform(ctx);

                        self.drawConfiguration =
                            {
                                features: features,
                                context: ctx,
                                pixelWidth: lengthPixel,
                                pixelHeight: Math.min(buffer.width, buffer.height),
                                bpStart: startBP,
                                bpEnd: endBP,
                                bpPerPixel: genomicState.bpp,
                                genomicState: genomicState,
                                viewportContainerX: (genomicState.startBP - startBP) / genomicState.bpp,
                                viewportContainerWidth: Math.max(self.$canvas.width(), self.$canvas.height()),
                                labelTransform: self.labelReflectionTransform
                            };

                        self.track.draw(self.drawConfiguration);

                    } else {
                        ctx.clearRect(0, 0, self.$canvas.width(), self.$canvas.height());
                    }

                    self.tile = new Tile(chrName, startBP, endBP, genomicState.bpp, buffer);
                    return "OK";

                })
        }
    }

    /**
     *
     */
    hic.TrackRenderer.prototype.repaint = function () {

        var self = this,
            genomicState,
            chrName;

        genomicState = self.browser.genomicState(self.axis);
        if (!this.checkZoomIn()) {
                self.tile = undefined;
                self.ctx.clearRect(0, 0, self.$canvas.width(), self.$canvas.height());
            }

        chrName = genomicState.chromosome.name;

        if (self.tile && self.tile.containsRange(chrName, genomicState.startBP, genomicState.endBP, genomicState.bpp)) {
            self.drawTileWithGenomicState(self.tile, genomicState);

        } else {
            self.readyToPaint()
                .then(function (ignore) {
                    self.drawTileWithGenomicState(self.tile, genomicState);
                })
                .catch(function (error) {
                    console.error(error);
                })

        }

    };

    hic.TrackRenderer.prototype.checkZoomIn = function () {

        if (this.track.visibilityWindow && this.track.visibilityWindow > 0) {

            if ((genomicState.bpp * Math.max(this.$canvas.width(), this.$canvas.height()) > this.track.visibilityWindow)) {
                return false;
            }
        }
        return true;
    }

    hic.TrackRenderer.prototype.drawTileWithGenomicState = function (tile, genomicState) {

        if (tile) {

            this.ctx.clearRect(0, 0, this.$canvas.width(), this.$canvas.height());

            this.offsetPixel = Math.round((tile.startBP - genomicState.startBP) / genomicState.bpp);
            if ('x' === this.axis) {
                this.ctx.drawImage(tile.buffer, this.offsetPixel, 0);
            } else {
                this.ctx.drawImage(tile.buffer, 0, this.offsetPixel);
            }

            // this.ctx.save();
            // this.ctx.restore();
        }
    };

    hic.TrackRenderer.prototype.startSpinner = function () {

        this.browser.startSpinner();

        //igv.startSpinnerAtParentElement(this.$viewport[0]);

        //    this.$spinner.show();
        //    this.throbber.start();
        //    console.log("Spinner show");
    };

    hic.TrackRenderer.prototype.stopSpinner = function () {

        this.browser.stopSpinner();

        //igv.stopSpinnerAtParentElement(this.$viewport[0]);

        //    this.throbber.stop();
        //    this.$spinner.hide();
        //    console.log("Spinner stop");
    };

    hic.TrackRenderer.prototype.isLoading = function () {
        return !(undefined === this.loading);
    };

    Tile = function (chr, startBP, endBP, bpp, buffer) {
        this.chr = chr;
        this.startBP = startBP;
        this.endBP = endBP;
        this.bpp = bpp;
        this.buffer = buffer;
    };

    Tile.prototype.containsRange = function (chr, startBP, endBP, bpp) {
        return chr === this.chr && this.bpp === bpp && this.startBP <= startBP && this.endBP >= endBP;
    };

    return hic;

})
(hic || {});
<|endoftext|>


<commit_before>//Notes:    Must update database to reflect the records state of published
            //Delete 2nd method

function sendDataToVon(returnedRecord){
   // for (i = 0; i < listOfMedicalRecordIds.length; i++) {
        console.log("test");
        var record = returnedRecord;
        console.log("Most recent record" + JSON.stringify(record));
        var xmlRecord = create2018Xml(record);
        console.log(xmlRecord);

        //transferXmlToVon(xmlRecord);
        console.log("Data for record: "+ listOfMedicalRecordIds[i] + "transfered")
   // }
}

function transferXmlToVon(xmlFile)
{
    var http = new XMLHttpRequest();
    var url = "http://posttestserver.com/post.php";
    http.open("POST", url, true);
    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            toastr.info("Data has sent to test environment");
        }
    }
    http.send(xmlFile);
}

<commit_msg>Auto stash before merge of "master" and "origin/master"<commit_after>//Notes:    Must update database to reflect the records state of published

function sendDataToVon(listOfMedicalRecordIds){
    for (i = 0; i < listOfMedicalRecordIds.length; i++) {
        var record = getRecordFromDatabase(listOfMedicalRecordIds[i]);
        var xmlRecord = create2018Xml(record);
        console.log(xmlRecord);
        transferXmlToVon(xmlRecord);
        console.log("Data for record: "+ listOfMedicalRecordIds[i] + "transfered")
    }
}

function transferXmlToVon(xmlFile)
{
    var http = new XMLHttpRequest();
    var url = "http://posttestserver.com/post.php";
    http.open("POST", url, true);
    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            toastr.info("Data has sent to test environment");
        }
    }
    http.send(xmlFile);
}

<|endoftext|>


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

/**
 * PhET-iO wrapper type for JS's built-in number type.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertTypeOf = require( 'PHET_IO/assertions/assertTypeOf' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var TObject = require( 'PHET_IO/types/TObject' );

  // valid values for options.units
  var VALID_UNITS = [
    'amperes',
    'becquerels',
    'centimeters',
    'centimeters-squared',
    'coulombs',
    'degrees Celsius',
    'farads',
    'kilograms',
    'grams',
    'gray',
    'henrys',
    'henries',
    'hertz',
    'joules',
    'katals',
    'kelvins',
    'liters',
    'liters/second',
    'lumens',
    'lux',
    'meters',
    'meters/second',
    'meters/second/second',
    'moles',
    'moles/liter',
    'nanometers',
    'newtons',
    'newtons/meters',
    'newtons-second/meters',
    'ohms',
    'ohm-centimeters',
    'pascals',
    'percent',
    'radians',
    'radians/second',
    'seconds',
    'siemens',
    'sieverts',
    'steradians',
    'tesla',
    'unitless',
    'volts',
    'watts',
    'webers'
  ];

  var TNumber = function( units, options ) {
    assert && assert( units, 'All TNumbers should specify units' );
    assert && assert( validUnits.indexOf( units ) >= 0, units + ' is not recognized as a valid unit of measurement' );

    options = _.extend( {
        type: 'FloatingPoint', // either 'FloatingPoint' | 'Integer'
        range: new RangeWithValue( -Infinity, Infinity ),
        stepSize: null, // This will be used for slider increments

        // TODO: enforce that values is of Array type
        values: null // null | {Number[]} if it can only take certain possible values, specify them here, like [0,2,8]
      },
      options
    );
    return phetioInherit( TObject, 'TNumber(' + units + ')', function( instance, phetioID ) {
      TObject.call( this, instance, phetioID );
      assertTypeOf( instance, 'number' );
    }, {}, {
      apiElements: { // named differently than api while it means type composite, see phetioInherit.js
        units: units,
        type: options.type,
        range: options.range,
        values: options.values
      },
      documentation: 'Wrapper for the built-in JS number type (floating point, but also represents integers)',

      fromStateObject: function( stateObject ) {
        return stateObject;
      },

      toStateObject: function( value ) {
        return value;
      },

      getAPI: function() {
        return { // named differently than api while it means type composite, see phetioInherit.js
          units: options.units,
          type: options.type,
          range: options.range,
          values: options.values
        };
      }
    } );
  }

  phetioNamespace.register( 'TNumber', TNumber );

  return TNumber;
} );<commit_msg>passed tandem into model and view, https://github.com/phetsims/ohms-law/issues/50<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * PhET-iO wrapper type for JS's built-in number type.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertTypeOf = require( 'PHET_IO/assertions/assertTypeOf' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var TObject = require( 'PHET_IO/types/TObject' );

  // valid values for options.units
  var VALID_UNITS = [
    'amperes',
    'milliamperes',
    'becquerels',
    'centimeters',
    'centimeters-squared',
    'coulombs',
    'degrees Celsius',
    'farads',
    'kilograms',
    'grams',
    'gray',
    'henrys',
    'henries',
    'hertz',
    'joules',
    'katals',
    'kelvins',
    'liters',
    'liters/second',
    'lumens',
    'lux',
    'meters',
    'meters/second',
    'meters/second/second',
    'moles',
    'moles/liter',
    'nanometers',
    'newtons',
    'newtons/meters',
    'newtons-second/meters',
    'ohms',
    'ohm-centimeters',
    'pascals',
    'percent',
    'radians',
    'radians/second',
    'seconds',
    'siemens',
    'sieverts',
    'steradians',
    'tesla',
    'unitless',
    'volts',
    'watts',
    'webers'
  ];

  var TNumber = function( units, options ) {
    assert && assert( units, 'All TNumbers should specify units' );
    assert && assert( validUnits.indexOf( units ) >= 0, units + ' is not recognized as a valid unit of measurement' );

    options = _.extend( {
        type: 'FloatingPoint', // either 'FloatingPoint' | 'Integer'
        range: new RangeWithValue( -Infinity, Infinity ),
        stepSize: null, // This will be used for slider increments

        // TODO: enforce that values is of Array type
        values: null // null | {Number[]} if it can only take certain possible values, specify them here, like [0,2,8]
      },
      options
    );
    return phetioInherit( TObject, 'TNumber(' + units + ')', function( instance, phetioID ) {
      TObject.call( this, instance, phetioID );
      assertTypeOf( instance, 'number' );
    }, {}, {
      apiElements: { // named differently than api while it means type composite, see phetioInherit.js
        units: units,
        type: options.type,
        range: options.range,
        values: options.values
      },
      documentation: 'Wrapper for the built-in JS number type (floating point, but also represents integers)',

      fromStateObject: function( stateObject ) {
        return stateObject;
      },

      toStateObject: function( value ) {
        return value;
      },

      getAPI: function() {
        return { // named differently than api while it means type composite, see phetioInherit.js
          units: options.units,
          type: options.type,
          range: options.range,
          values: options.values
        };
      }
    } );
  }

  phetioNamespace.register( 'TNumber', TNumber );

  return TNumber;
} );<|endoftext|>


<commit_before>// urlParameters module
if (typeof turbo === "undefined") turbo={};
turbo.urlParameters = function(args) {
    t = {
      has_query: false,
      query: undefined,
      has_coords: false,
      coords: undefined,
      has_zoom: false,
      zoom: undefined,
      run_query: false
    }

    if (args.q) { // compressed query set in url
      t.query = lzw_decode(Base64.decode(decodeURIComponent(args.q)));
      t.has_query = true;
    }
    if (args.Q) { // uncompressed query set in url
      t.query = decodeURIComponent(args.Q.replace(/\+/g,"%20"));
      t.has_query = true;
    }
    if (args.c) { // map center & zoom (compressed)
      var tmp = args.c.match(/([A-Za-z0-9\-_]+)([A-Za-z0-9\-_])/);
      var decode_coords = function(str) {
        var coords_cpr = Base64.decodeNum(str);
        var res = {};
        res.lat = coords_cpr % (180*100000) / 100000 - 90;
        res.lng = Math.floor(coords_cpr / (180*100000)) / 100000 - 180;
        return res;
      }
      t.coords = decode_coords(tmp[1]);
      t.has_coords = true;
      t.zoom = Base64.decodeNum(tmp[2]);
      t.has_zoom = true;
    }
    if (args.C) { // map center & zoom (uncompressed)
      var tmp = args.C.match(/(-?[\d.]+);(-?[\d.]+);(\d+)/);
      t.coords = {lat: +tmp[1], lng: +tmp[2]};
      t.has_coords = true;
      t.zoom = +tmp[3];
      t.has_zoom = true;
    }
    if (args.lat && args.lon) { // map center coords (ols style osm.org parameters)
      t.coords = {lat: +args.lat, lng: +args.lon};
      t.has_coords = true;
    }
    if (args.zoom) { // map zoom level (old style osm.org parameter)
      t.zoom = +args.zoom;
      t.has_zoom = true;
    }
    if (args.R !== undefined) { // indicates that the supplied query shall be executed immediately
      t.run_query = true;
    }
    if (args.template) { // load a template
      var template = settings.saves[args.template];
      if (template && template.type == "template") {
        // build query
        var q = template.overpass;
        var params = template.parameters;
        for (var i=0; i<params.length; i++) {
          var param = params[i];
          if (typeof args[param] !== "string") continue;
          var value = decodeURIComponent(args[param].replace(/\+/g,"%20"));
          value = value.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/\t/g,"	").replace(/\n/g,"
").replace(/\r/g,"
");
          // additionally escape curly brackets
          value = value.replace(/\}/g,"}").replace(/\{/g,"{");
          q = q.replace("{{"+param+"=???}}","{{"+param+"="+value+"}}");
        }
        t.query = q;
        t.has_query = true;
      }
    }

    return t;
};<commit_msg>special case for empty tag value in templates<commit_after>// urlParameters module
if (typeof turbo === "undefined") turbo={};
turbo.urlParameters = function(args) {
    t = {
      has_query: false,
      query: undefined,
      has_coords: false,
      coords: undefined,
      has_zoom: false,
      zoom: undefined,
      run_query: false
    }

    if (args.q) { // compressed query set in url
      t.query = lzw_decode(Base64.decode(decodeURIComponent(args.q)));
      t.has_query = true;
    }
    if (args.Q) { // uncompressed query set in url
      t.query = decodeURIComponent(args.Q.replace(/\+/g,"%20"));
      t.has_query = true;
    }
    if (args.c) { // map center & zoom (compressed)
      var tmp = args.c.match(/([A-Za-z0-9\-_]+)([A-Za-z0-9\-_])/);
      var decode_coords = function(str) {
        var coords_cpr = Base64.decodeNum(str);
        var res = {};
        res.lat = coords_cpr % (180*100000) / 100000 - 90;
        res.lng = Math.floor(coords_cpr / (180*100000)) / 100000 - 180;
        return res;
      }
      t.coords = decode_coords(tmp[1]);
      t.has_coords = true;
      t.zoom = Base64.decodeNum(tmp[2]);
      t.has_zoom = true;
    }
    if (args.C) { // map center & zoom (uncompressed)
      var tmp = args.C.match(/(-?[\d.]+);(-?[\d.]+);(\d+)/);
      t.coords = {lat: +tmp[1], lng: +tmp[2]};
      t.has_coords = true;
      t.zoom = +tmp[3];
      t.has_zoom = true;
    }
    if (args.lat && args.lon) { // map center coords (ols style osm.org parameters)
      t.coords = {lat: +args.lat, lng: +args.lon};
      t.has_coords = true;
    }
    if (args.zoom) { // map zoom level (old style osm.org parameter)
      t.zoom = +args.zoom;
      t.has_zoom = true;
    }
    if (args.R !== undefined) { // indicates that the supplied query shall be executed immediately
      t.run_query = true;
    }
    if (args.template) { // load a template
      var template = settings.saves[args.template];
      if (template && template.type == "template") {
        // build query
        var q = template.overpass;
        var params = template.parameters;
        for (var i=0; i<params.length; i++) {
          var param = params[i];
          if (typeof args[param] !== "string") continue;
          var value = decodeURIComponent(args[param].replace(/\+/g,"%20"));
          value = value.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/\t/g,"	").replace(/\n/g,"
").replace(/\r/g,"
");
          // additionally escape curly brackets
          value = value.replace(/\}/g,"}").replace(/\{/g,"{");
          q = q.replace("{{"+param+"=???}}","{{"+param+"="+value+"}}");
          // special case for empty tag value in templates
          // Overpass API doesn't properly support searching for empty tag values. see drolbr/Overpass-API#53
          if (param === "value" && value === "") {
            q = q.replace("{{value=}}\n","");
            q = q.replace(/v="\{\{value\}\}"/g,'regv="^$"');
          }
        }
        t.query = q;
        t.has_query = true;
      } else {
        console.log("template not found");
      }
    }

    return t;
};<|endoftext|>


<commit_before>import React from 'react';
import {
  StyleSheet,
  Platform,
  View,
} from 'react-native';
import _ from 'lodash';

import Styles from '../styles/Styles';
import MapView from 'react-native-maps';

import { loadCachedGeofenceTriggers } from '../api/Triggers';
import { loadCachedFormDataByTriggerId } from '../api/Forms';
import { setActiveMap, clearActiveMap } from '../api/Geofencing';

import Loading from '../components/Loading';

const _styles = StyleSheet.create({
  iosMap: {
    flex: 1,
  },
  androidMap: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
});

const MapPage = React.createClass({
  propTypes: {
    navigator: React.PropTypes.object.isRequired,
    survey: React.PropTypes.object,
  },

  getInitialState() {
    return {
      stage: 'loading',
      updates: 0,
      latitude: 40.782786,
      longitude: -73.965850,
      zoom: 0.01,
      markers: [],
      triggers: [],
    };
  },

  componentDidMount() {
    loadCachedGeofenceTriggers({
      surveyId: this.props.survey ? this.props.survey.id : false,
      excludeCompleted: true,
    }, (err, response) => {
      setActiveMap(this);
      this.active = true;
      this.generateTriggerMarkers(response);

      setTimeout(() => {
        if (!this.cancelCallbacks) {
          this.setState({stage: 'ready'});
        }
      }, 300);
    });
  },

  componentWillUnmount() {
    clearActiveMap(this);
    this.active = false;
    this.cancelCallbacks = true;
  },

  /* Methods */
  generateTriggerMarkers(triggers) {
    this.wipeMarkers();
    const geoTriggers = triggers || this.state.triggers;

    let markers = [];
    markers = geoTriggers.map((trigger) => {
      return {
        id: trigger.id,
        title: trigger.title,
        description: trigger.description,
        position: {
          latitude: trigger.latitude,
          longitude: trigger.longitude,
        },
        radius: trigger.radius,
        active: trigger.inRange,
      };
    });

    this.setState({
      triggers: geoTriggers,
      markers: markers,
    });
  },

  updateMarkers(geofence) {
    if (_.lowerCase(geofence.action) === 'enter' || _.lowerCase(geofence.action) === 'dwell') {
      const updatedMarkers = this.state.markers.filter((marker) => {
        return marker.id === geofence.identifier;
      });
      for (let i = 0; i < updatedMarkers.length; i++) {
        updatedMarkers[i].active = true;
      }
    } else if (_.lowerCase(geofence.action) === 'exit') {
      const updatedMarkers = this.state.markers.filter((marker) => {
        return marker.id === geofence.identifier;
      });
      for (let i = 0; i < updatedMarkers.length; i++) {
        updatedMarkers[i].active = false;
      }
    }

    this.setState({updated: this.state.updated + 1});
  },

  wipeMarkers() {
    this.setState({markers: []});
  },

  handleMarkerPress(marker) {
    const data = loadCachedFormDataByTriggerId(marker.id, 'geofence');

    if (marker.active) {
      this.props.navigator.push({
        path: 'form',
        title: data.survey.title,
        survey: data.survey,
        form: data.form,
        type: 'geofence',
      });
    }
  },

  /* Render */
  render() {
    if (this.state.stage === 'loading') {
      return <Loading/>;
    }

    return (
      <View style={[Styles.container.default, { flex: 1, overflow: 'hidden' }]}>
        <MapView
          ref={(ref) => {
            this._map = ref;
          }}
          key='gmap'
          style={Platform.OS === 'ios' ? _styles.iosMap : _styles.androidMap}
          initialRegion={{
            latitude: this.state.latitude,
            longitude: this.state.longitude,
            latitudeDelta: this.state.zoom,
            longitudeDelta: this.state.zoom * 0.5,
          }}
          mapType={'standard'}
          showsUserLocation={true}
          followsUserLocation={true}
          showsPointsOfInterest={false}
          showsCompass={true}
        >
          {
            this.state.markers.map((marker) => {
              return (
                <MapView.Circle
                  key={`circle- + ${marker.id}`}
                  center={marker.position}
                  radius={marker.radius}
                  strokeColor='#700'
                  fillColor={marker.active ? 'rgba(30, 150, 30, 0.5)' : 'rgba(100, 30, 30, 0.5)'}
                />
              );
            })
          }
          {
            this.state.markers.map((marker) => {
              return (
                <MapView.Marker
                  // Android
                  onPress={this.handleMarkerPress.bind(null, marker)}
                  // iOS
                  onSelect={this.handleMarkerPress.bind(null, marker)}
                  key={`marker- + ${marker.id}`}
                  coordinate={marker.position}
                  title={marker.title}
                  description={marker.description}
                />
              );
            })
          }
        </MapView>
      </View>
    );
  },
});

module.exports = MapPage;
<commit_msg>Sync the map's region with the user's location<commit_after>import React from 'react';
import {
  StyleSheet,
  Platform,
  View,
} from 'react-native';
import _ from 'lodash';

import Styles from '../styles/Styles';
import MapView from 'react-native-maps';

import { loadCachedGeofenceTriggers } from '../api/Triggers';
import { loadCachedFormDataByTriggerId } from '../api/Forms';
import { setActiveMap, clearActiveMap, getUserLocationData } from '../api/Geofencing';

import Loading from '../components/Loading';

const _styles = StyleSheet.create({
  iosMap: {
    flex: 1,
  },
  androidMap: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
});

const MapPage = React.createClass({
  propTypes: {
    navigator: React.PropTypes.object.isRequired,
    survey: React.PropTypes.object,
  },

  getInitialState() {
    return {
      stage: 'loading',
      updates: 0,
      latitude: 40.782786,
      longitude: -73.965850,
      zoom: 0.01,
      markers: [],
      triggers: [],
    };
  },

  componentDidMount() {
    loadCachedGeofenceTriggers({
      surveyId: this.props.survey ? this.props.survey.id : false,
      excludeCompleted: true,
    }, (err, response) => {
      setActiveMap(this);
      this.active = true;
      this.generateTriggerMarkers(response);
      getUserLocationData((location) => {
        setTimeout(() => {
          if (!this.cancelCallbacks) {
            this.setState({
              latitude: location.latitude || 40.782786,
              longitude: location.longitude || -73.965850,
              stage: 'ready',
            });
          }
        }, 200);
      });

    });
  },

  componentWillUnmount() {
    clearActiveMap(this);
    this.active = false;
    this.cancelCallbacks = true;
  },

  /* Methods */
  generateTriggerMarkers(triggers) {
    this.wipeMarkers();
    const geoTriggers = triggers || this.state.triggers;

    let markers = [];
    markers = geoTriggers.map((trigger) => {
      return {
        id: trigger.id,
        title: trigger.title,
        description: trigger.description,
        position: {
          latitude: trigger.latitude,
          longitude: trigger.longitude,
        },
        radius: trigger.radius,
        active: trigger.inRange,
      };
    });

    this.setState({
      triggers: geoTriggers,
      markers: markers,
    });
  },

  updateMarkers(geofence) {
    if (_.lowerCase(geofence.action) === 'enter' || _.lowerCase(geofence.action) === 'dwell') {
      const updatedMarkers = this.state.markers.filter((marker) => {
        return marker.id === geofence.identifier;
      });
      for (let i = 0; i < updatedMarkers.length; i++) {
        updatedMarkers[i].active = true;
      }
    } else if (_.lowerCase(geofence.action) === 'exit') {
      const updatedMarkers = this.state.markers.filter((marker) => {
        return marker.id === geofence.identifier;
      });
      for (let i = 0; i < updatedMarkers.length; i++) {
        updatedMarkers[i].active = false;
      }
    }

    this.setState({updated: this.state.updated + 1});
  },

  wipeMarkers() {
    this.setState({markers: []});
  },

  handleMarkerPress(marker) {
    const data = loadCachedFormDataByTriggerId(marker.id, 'geofence');

    if (marker.active) {
      this.props.navigator.push({
        path: 'form',
        title: data.survey.title,
        survey: data.survey,
        form: data.form,
        type: 'geofence',
      });
    }
  },

  /* Render */
  render() {
    if (this.state.stage === 'loading') {
      return <Loading/>;
    }

    return (
      <View style={[Styles.container.default, { flex: 1, overflow: 'hidden' }]}>
        <MapView
          ref={(ref) => {
            this._map = ref;
          }}
          key='gmap'
          style={Platform.OS === 'ios' ? _styles.iosMap : _styles.androidMap}
          region={{
            latitude: this.state.latitude,
            longitude: this.state.longitude,
            latitudeDelta: this.state.zoom,
            longitudeDelta: this.state.zoom * 0.5,
          }}
          mapType={'standard'}
          showsUserLocation={true}
          followsUserLocation={true}
          showsPointsOfInterest={false}
          showsCompass={true}
        >
          {
            this.state.markers.map((marker) => {
              return (
                <MapView.Circle
                  key={`circle- + ${marker.id}`}
                  center={marker.position}
                  radius={marker.radius}
                  strokeColor='#700'
                  fillColor={marker.active ? 'rgba(30, 150, 30, 0.5)' : 'rgba(100, 30, 30, 0.5)'}
                />
              );
            })
          }
          {
            this.state.markers.map((marker) => {
              return (
                <MapView.Marker
                  // Android
                  onPress={this.handleMarkerPress.bind(null, marker)}
                  // iOS
                  onSelect={this.handleMarkerPress.bind(null, marker)}
                  key={`marker- + ${marker.id}`}
                  coordinate={marker.position}
                  title={marker.title}
                  description={marker.description}
                />
              );
            })
          }
        </MapView>
      </View>
    );
  },
});

module.exports = MapPage;
<|endoftext|>


<commit_before>/*
   +----------------------------------------------------------------------+
   |                            HEP Random                                |
   |                      --- RandChiSquare ---                           |
   |                            Module File                               |
   +----------------------------------------------------------------------+

   +----------------------------------------------------------------------+
   | C++                                                                  |
   +----------------------------------------------------------------------+

   +----------------------------------------------------------------------+
   | JavaScript                                                           |
   +----------------------------------------------------------------------+

   F. Quinonez - Created 2015-10-30

*/

define( [], function(){
  "use strict";

  function RandChiSquare( ){

  }

  RandChiSquare.prototype = {
    constructor: RandChiSquare,

  }

  return RandChiSquare;

});

<commit_msg>GenChiSquare, Shoot, ShootArray, Fire, FireArray added<commit_after>/*
   +----------------------------------------------------------------------+
   |                            HEP Random                                |
   |                      --- RandChiSquare ---                           |
   |                            Module File                               |
   +----------------------------------------------------------------------+
   Module defining methods for shooting Chi^2 distributed random values,
   given a number of degrees of freedom a (default=1.0).

   Valid values of a satisfy a > 1. When invalid values are presented,
   the code silently returns -1.0.
   +----------------------------------------------------------------------+
   | JavaScript                                                           |
   +----------------------------------------------------------------------+
   F. Quinonez - Created 2015-10-30
   +----------------------------------------------------------------------+
   | C++                                                                  |
   +----------------------------------------------------------------------+
   John Marraffino - Created: 12th May 1998
   M Fischler     - put and get to/from streams 12/10/04
   M Fischler	      - put/get to/from streams uses pairs of ulongs when
  			+ storing doubles avoid problems with precision
  			4/14/05
*/

define( [ '../Random/JamesRandom' ], function( JamesRandom ){
  "use strict";

  function RandChiSquare( args ){
    this.a = args.a || 1.0;
    this.fengine = args.engine || Object.create( JamesRandom({}) );
  }

  RandChiSquare.Shoot = function( args ){
    var sa = args.a || 1.0;
    var sengine = args.engine || Object.create( JamesRandom({}) );
  };

  RandChiSquare.ShootArray = function( args ){
    var ssize = args.size || 1;
    // var svect = args.vect;
    var sa = args.a || 1.0;
    var sengine = args.engine || Object.create( JamesRandom({}) );
    var argsShoot = { a: sa, engine: sengine };
    for( var i = 0; i < ssize; ++i ){
      args.vect.push( RandBinomial.Shoot( argsShoot ) );
    }
  };

  RandChiSquare.prototype = {
    constructor: RandChiSquare,

    Fire: function(){
      return GenChiSquare();
    },

    FireArray: function( /* size of vect */ size, /* Array */ vect ){
      for( var i = 0; i < size(); i++ ){
        vect.push( this.Fire() );
      }
    },

    GenChiSquare: function(){
      /******************************************************************
       *                                                                *
       *        Chi Distribution - Ratio of Uniforms  with shift        *
       *                                                                *
       ******************************************************************
       *                                                                *
       * FUNCTION :   - chru samples a random number from the Chi       *
       *                distribution with parameter  a > 1.             *
       * REFERENCE :  - J.F. Monahan (1987): An algorithm for           *
       *                generating chi random variables, ACM Trans.     *
       *                Math. Software 13, 168-172.                     *
       * SUBPROGRAM : - anEngine  ... pointer to a (0,1)-Uniform        *
       *                engine                                          *
       *                                                                *
       * Implemented by R. Kremer, 1990                                 *
       ******************************************************************/
      var a_in = -1.0;
      var b,vm,vp,vd; // CLHEP_THREAD_LOCAL double's
      var u,v,z,zz,r; // double's

      // chech for invalid input value
      if( this.fa < 1 ) return -1;

      if( this.fa === 1 ){
        for(;;){
          u = this.fengine.Flat();
          v = this.fengine.Flat() * 0.857763884960707;
          z = v / u;
          if( z < 0 ) continue;
          zz = z * z;
          r = 2.5 - zz;
          if( z < 0.0 ) r += zz * z / ( 3.0 * z );
          if( u < r * 0.3894003915 ) return( z * z );
          if( zz > ( 1.036961043 / u + 1.4 ) ) continue;
          if( 2 * Math.log( u ) < ( - zz * 0.5 ) ) return( z * z );
        }
      } else {
        if( this.fa != a_in ){
          b = Math.sqrt( a - 1.0 );
          vm = - 0.6065306597 * ( 1.0 - 0.25 / ( b * b + 1.0 ) );
          vm = ( -b > vm )? -b: vm;
          vp = 0.6065306597 * (0.7071067812 + b) / (0.5 + b);
          vd = vp - vm;
          a_in = this.fa;
        }
        for(;;){
          u = this.fengine.Flat();
          v = this.fengine.Flat() * vd + vm;
          z = v / u;
          if( z < -b ) continue;
          zz = z * z;
          r = 2.5 - zz;
          if( z < 0.0 ) r += zz * z / ( 3.0 * ( z + b ) );
          if( u < r * 0.3894003915 ) return( ( z + b ) * ( z + b ) );
          if( zz > ( 1.036961043 / u + 1.4 ) ) continue;
          if( 2 * Math.log( u ) < ( Math.log( 1.0 + z / b ) * b * b - zz * 0.5 - z * b ) ) return ( ( z + b ) * ( z + b ) );
        }
      }
    }
  }
  return RandChiSquare;
});

<|endoftext|>