<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
    'base/js/dialog',
    'base/js/keyboard',
    'moment',
], function(IPython, $, utils, dialog, keyboard, moment) {
    "use strict";

    var SaveWidget = function (selector, options) {
        // TODO: Remove circular ref.
        this.notebook = undefined;
        this.selector = selector;
        this.events = options.events;
        this._checkpoint_date = undefined;
        this.keyboard_manager = options.keyboard_manager;
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.bind_events();
        }
    };

    SaveWidget.prototype.bind_events = function () {
        var that = this;
        this.element.find('span#notebook_name').click(function () {
            that.rename_notebook();
        });
        this.element.find('span#notebook_name').hover(function () {
            $(this).addClass("ui-state-hover");
        }, function () {
            $(this).removeClass("ui-state-hover");
        });
        this.events.on('notebook_loaded.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
        });
        this.events.on('notebook_saved.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
        });
        this.events.on('notebook_renamed.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
            that.update_address_bar();
        });
        this.events.on('notebook_save_failed.Notebook', function () {
            that.set_save_status('Autosave Failed!');
        });
        this.events.on('checkpoints_listed.Notebook', function (event, data) {
            that._set_last_checkpoint(data[0]);
        });

        this.events.on('checkpoint_created.Notebook', function (event, data) {
            that._set_last_checkpoint(data);
        });
        this.events.on('set_dirty.Notebook', function (event, data) {
            that.set_autosaved(data.value);
        });
    };

    SaveWidget.prototype.rename_notebook = function (options) {
        options = options || {};
        var that = this;
        var dialog_body = $('
').append(
            $("
").addClass("rename-message")
                .text('Enter a new notebook name:')
        ).append(
            $("
")
        ).append(
            $('<input/>').attr('type','text').attr('size','25').addClass('form-control')
            .val(that.notebook.get_notebook_name())
        );
        dialog.modal({
            title: "Rename Notebook",
            body: dialog_body,
            notebook: options.notebook,
            keyboard_manager: this.keyboard_manager,
            buttons : {
                "Cancel": {},
                "OK": {
                    class: "btn-primary",
                    click: function () {
                    var new_name = $(this).find('input').val();
                    if (!that.notebook.test_notebook_name(new_name)) {
                        $(this).find('.rename-message').text(
                            "Invalid notebook name. Notebook names must "+
                            "have 1 or more characters and can contain any characters " +
                            "except :/\\. Please enter a new notebook name:"
                        );
                        return false;
                    } else {
                        that.notebook.rename(new_name);
                    }
                }}
                },
            open : function (event, ui) {
                var that = $(this);
                // Upon ENTER, click the OK button.
                that.find('input[type="text"]').keydown(function (event, ui) {
                    if (event.which === keyboard.keycodes.enter) {
                        that.find('.btn-primary').first().click();
                        return false;
                    }
                });
                that.find('input[type="text"]').focus().select();
            }
        });
    };

    SaveWidget.prototype.update_notebook_name = function () {
        var nbname = this.notebook.get_notebook_name();
        this.element.find('span#notebook_name').text(nbname);
    };

    SaveWidget.prototype.update_document_title = function () {
        var nbname = this.notebook.get_notebook_name();
        document.title = nbname;
    };

    SaveWidget.prototype.update_address_bar = function(){
        var base_url = this.notebook.base_url;
        var nbname = this.notebook.notebook_name;
        var path = this.notebook.notebook_path;
        var state = {path : path, name: nbname};
        window.history.replaceState(state, "", utils.url_join_encode(
            base_url,
            "notebooks",
            path,
            nbname)
        );
    };

    SaveWidget.prototype.set_save_status = function (msg) {
        this.element.find('span#autosave_status').text(msg);
    };

    SaveWidget.prototype._set_checkpoint_status = function (human_date, iso_date) {
        var el = this.element.find('span#checkpoint_status')
        if(human_date){
            el.text("Last Checkpoint: "+human_date).attr('title',iso_date);
        } else {
            el.text('').attr('title','no-checkpoint')
        }
    };

    // compute (roughly) the remaining time in millisecond until the next
    // moment.js relative time update of the string, which by default
    // happend at
    //  (a few seconds ago)
    //  - 45sec,
    //  (a minute ago)
    //  - 90sec,
    //      ( x minutes ago)
    //      - then every minutes until
    //  - 45 min,
    //      (an hour ago)
    //  - 1h45,
    //      (x hours ago )
    //      - then every hours
    //  - 22 hours ago
    var _next_timeago_update = function(deltatime_ms){
        var s = 1000;
        var m = 60*s;
        var h = 60*m;

        var mtt = moment.relativeTimeThreshold;

        if(deltatime_ms < mtt.s*s){
            return mtt.s*s-deltatime_ms;
        } else if (deltatime_ms < (mtt.s*s+m)) {
            return (mtt.s*s+m)-deltatime_ms;
        } else if (deltatime_ms < mtt.m*m){
            return m;
        } else if (deltatime_ms < (mtt.m*m+h)){
            return (mtt.m*m+h)-deltatime_ms;
        } else  {
            return h;
        }

    }

    SaveWidget.prototype._regularly_update_checkpoint_date = function(){
       if (!this._checkpoint_date) {
            this.set_checkpoint_status(null);
            console.log('no checkpoint done');
            return;
        }
        var chkd = moment(this._checkpoint_date);
        var longdate = chkd.format('llll');

        var that = this;
        var recall  = function(t){
            // recall slightly later (1s) as long timeout in js might be imprecise,
            // and you want to be call **after** the change of formatting should happend.
            return setTimeout($.proxy(that._regularly_update_checkpoint_date, that),(t+1000))
        }
        var tdelta = Math.ceil(new Date()-this._checkpoint_date);

        // update regularly for the first 6hours and show
        // <x time> ago
        if(tdelta < tdelta < 6*3600*1000){
            recall(_next_timeago_update(tdelta));
            this._set_checkpoint_status( chkd.fromNow(), longdate);
        // otherwise update every hour and show
        // <Today | yesterday|...> at hh,mm,ss
        } else  {
            recall(1*3600*1000)
            this._set_checkpoint_status( chkd.calendar(), longdate);
        }

    }

    SaveWidget.prototype._set_last_checkpoint = function (checkpoint) {
        this._checkpoint_date = new Date(checkpoint.last_modified);
        this._regularly_update_checkpoint_date();

    };

    SaveWidget.prototype.set_autosaved = function (dirty) {
        if (dirty) {
            this.set_save_status("(unsaved changes)");
        } else {
            this.set_save_status("(autosaved)");
        }
    };

    // Backwards compatibility.
    IPython.SaveWidget = SaveWidget;

    return {'SaveWidget': SaveWidget};

});
<commit_msg>fix handling of no-checkpoint-defined<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
    'base/js/dialog',
    'base/js/keyboard',
    'moment',
], function(IPython, $, utils, dialog, keyboard, moment) {
    "use strict";

    var SaveWidget = function (selector, options) {
        // TODO: Remove circular ref.
        this.notebook = undefined;
        this.selector = selector;
        this.events = options.events;
        this._checkpoint_date = undefined;
        this.keyboard_manager = options.keyboard_manager;
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.bind_events();
        }
    };

    SaveWidget.prototype.bind_events = function () {
        var that = this;
        this.element.find('span#notebook_name').click(function () {
            that.rename_notebook();
        });
        this.element.find('span#notebook_name').hover(function () {
            $(this).addClass("ui-state-hover");
        }, function () {
            $(this).removeClass("ui-state-hover");
        });
        this.events.on('notebook_loaded.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
        });
        this.events.on('notebook_saved.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
        });
        this.events.on('notebook_renamed.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
            that.update_address_bar();
        });
        this.events.on('notebook_save_failed.Notebook', function () {
            that.set_save_status('Autosave Failed!');
        });
        this.events.on('checkpoints_listed.Notebook', function (event, data) {
            that._set_last_checkpoint(data[0]);
        });

        this.events.on('checkpoint_created.Notebook', function (event, data) {
            that._set_last_checkpoint(data);
        });
        this.events.on('set_dirty.Notebook', function (event, data) {
            that.set_autosaved(data.value);
        });
    };

    SaveWidget.prototype.rename_notebook = function (options) {
        options = options || {};
        var that = this;
        var dialog_body = $('
').append(
            $("
").addClass("rename-message")
                .text('Enter a new notebook name:')
        ).append(
            $("
")
        ).append(
            $('<input/>').attr('type','text').attr('size','25').addClass('form-control')
            .val(that.notebook.get_notebook_name())
        );
        dialog.modal({
            title: "Rename Notebook",
            body: dialog_body,
            notebook: options.notebook,
            keyboard_manager: this.keyboard_manager,
            buttons : {
                "Cancel": {},
                "OK": {
                    class: "btn-primary",
                    click: function () {
                    var new_name = $(this).find('input').val();
                    if (!that.notebook.test_notebook_name(new_name)) {
                        $(this).find('.rename-message').text(
                            "Invalid notebook name. Notebook names must "+
                            "have 1 or more characters and can contain any characters " +
                            "except :/\\. Please enter a new notebook name:"
                        );
                        return false;
                    } else {
                        that.notebook.rename(new_name);
                    }
                }}
                },
            open : function (event, ui) {
                var that = $(this);
                // Upon ENTER, click the OK button.
                that.find('input[type="text"]').keydown(function (event, ui) {
                    if (event.which === keyboard.keycodes.enter) {
                        that.find('.btn-primary').first().click();
                        return false;
                    }
                });
                that.find('input[type="text"]').focus().select();
            }
        });
    };

    SaveWidget.prototype.update_notebook_name = function () {
        var nbname = this.notebook.get_notebook_name();
        this.element.find('span#notebook_name').text(nbname);
    };

    SaveWidget.prototype.update_document_title = function () {
        var nbname = this.notebook.get_notebook_name();
        document.title = nbname;
    };

    SaveWidget.prototype.update_address_bar = function(){
        var base_url = this.notebook.base_url;
        var nbname = this.notebook.notebook_name;
        var path = this.notebook.notebook_path;
        var state = {path : path, name: nbname};
        window.history.replaceState(state, "", utils.url_join_encode(
            base_url,
            "notebooks",
            path,
            nbname)
        );
    };

    SaveWidget.prototype.set_save_status = function (msg) {
        this.element.find('span#autosave_status').text(msg);
    };

    SaveWidget.prototype._set_checkpoint_status = function (human_date, iso_date) {
        var el = this.element.find('span#checkpoint_status');
        if(human_date){
            el.text("Last Checkpoint: "+human_date).attr('title',iso_date);
        } else {
            el.text('').attr('title', 'no-checkpoint');
        }
    };

    // compute (roughly) the remaining time in millisecond until the next
    // moment.js relative time update of the string, which by default
    // happend at
    //  (a few seconds ago)
    //  - 45sec,
    //  (a minute ago)
    //  - 90sec,
    //      ( x minutes ago)
    //      - then every minutes until
    //  - 45 min,
    //      (an hour ago)
    //  - 1h45,
    //      (x hours ago )
    //      - then every hours
    //  - 22 hours ago
    var _next_timeago_update = function(deltatime_ms){
        var s = 1000;
        var m = 60*s;
        var h = 60*m;

        var mtt = moment.relativeTimeThreshold;

        if(deltatime_ms < mtt.s*s){
            return mtt.s*s-deltatime_ms;
        } else if (deltatime_ms < (mtt.s*s+m)) {
            return (mtt.s*s+m)-deltatime_ms;
        } else if (deltatime_ms < mtt.m*m){
            return m;
        } else if (deltatime_ms < (mtt.m*m+h)){
            return (mtt.m*m+h)-deltatime_ms;
        } else  {
            return h;
        }
    };

    SaveWidget.prototype._regularly_update_checkpoint_date = function(){
       if (!this._checkpoint_date) {
            this._set_checkpoint_status(null);
            console.log('no checkpoint done');
            return;
        }
        var chkd = moment(this._checkpoint_date);
        var longdate = chkd.format('llll');

        var that = this;
        var recall  = function(t){
            // recall slightly later (1s) as long timeout in js might be imprecise,
            // and you want to be call **after** the change of formatting should happend.
            return setTimeout(
                $.proxy(that._regularly_update_checkpoint_date, that),
                t + 1000
            );
        }
        var tdelta = Math.ceil(new Date()-this._checkpoint_date);

        // update regularly for the first 6hours and show
        // <x time> ago
        if(tdelta < tdelta < 6*3600*1000){
            recall(_next_timeago_update(tdelta));
            this._set_checkpoint_status(chkd.fromNow(), longdate);
        // otherwise update every hour and show
        // <Today | yesterday|...> at hh,mm,ss
        } else  {
            recall(1*3600*1000);
            this._set_checkpoint_status(chkd.calendar(), longdate);
        }
    };

    SaveWidget.prototype._set_last_checkpoint = function (checkpoint) {
        if (checkpoint) {
            this._checkpoint_date = new Date(checkpoint.last_modified);
        } else {
            this._checkpoint_date = null;
        }
        this._regularly_update_checkpoint_date();

    };

    SaveWidget.prototype.set_autosaved = function (dirty) {
        if (dirty) {
            this.set_save_status("(unsaved changes)");
        } else {
            this.set_save_status("(autosaved)");
        }
    };

    // Backwards compatibility.
    IPython.SaveWidget = SaveWidget;

    return {'SaveWidget': SaveWidget};

});
<|endoftext|>


<commit_before>/* global $ */

$(function () {
    'use strict';

    // layout-specific JS can go here.
    function layoutButton() {
        /* mobile nav button */
        $('#page-header .nav-btn').click(function (event) {
            event.preventDefault();
            var $nav = $('#page-header nav ul');
            $nav.toggleClass('active');
        });
    }
    layoutButton();

    function halos() {
        var haloElements = [];
        var $container = $('.header-bg-fx');

        var haloData = [
            { class: 'halo-2018 halo-orange', x: 815, y: 171, s: 147 },
            { class: 'halo-2018 halo-green', x: 531, y: 6, s: 218 },
            { class: 'halo-2018 halo-blue', x: 202, y: 87, s: 257 },
            { class: 'halo-2018 halo-purple', x: -8, y: -17, s: 220 },
        ];

        haloData.forEach(function(cd) {
            // var src = IMAGE_BASE_PATH + cd.src;
            var $halo = $('
');
            $halo.css('left', cd.x / 2);
            $halo.css('top', cd.y / 2);
            $halo.css('width', cd.s / 2);
            $halo.css('height', cd.s / 2);
            $container.append($halo);
            haloElements.push($halo);
        });

        document.addEventListener('mouseover', function() {
            haloElements.forEach(function(haloElement, index) {
                var val = Math.sin(new Date().valueOf() / 1000 + index);
                haloElement.css('opacity', val * 0.5 + 0.5);
            });
        }, 500);
    }
    halos();

    function backgrounds() {
        var bgElements = [
            '.layer-cyan',
            '.layer-green',
            '.layer-purple',
            '.layer-yellow'
        ].map(function(selector) {
            return $(selector);
        });

        // minimum delay between animations
        var DELAY = 2500;
        // track whether the user is interacting with the page or not
        var interacting = false;

        function update() {
            if(!interacting) {
                return false;
            }
            interacting = false;
            // Using the clock for this keeps the look consistent when navigating.
            var x = new Date().valueOf() / 2000;
            bgElements.forEach(function(bgElement, index) {
                bgElement.css('opacity', 0.5 + 0.5 * Math.sin((x + index) * Math.PI / 4));
            });
        }

        function onInteraction() {
            interacting = true;
        }

        document.addEventListener('mouseover', onInteraction);
        document.addEventListener('mousedown', onInteraction);
        document.addEventListener('keydown', onInteraction);

        // Start the 2 s animation every 2+ s.
        // The transitions sometimes glitch on Firefox if the opacity
        // target value changes mid-transition.
        // The gap isn't too noticeable, especially with ease-in-out.
        setInterval(update, DELAY);
        update();
    }
    backgrounds();
});<commit_msg>main2018: Fix typo<commit_after>/* global $ */

$(function () {
    'use strict';

    // layout-specific JS can go here.
    function layoutButton() {
        /* mobile nav button */
        $('#page-header .nav-btn').click(function (event) {
            event.preventDefault();
            var $nav = $('#page-header nav ul');
            $nav.toggleClass('active');
        });
    }
    layoutButton();

    function halos() {
        var haloElements = [];
        var $container = $('.header-bg-fx');

        var haloData = [
            { class: 'halo-2018 halo-orange', x: 815, y: 171, s: 147 },
            { class: 'halo-2018 halo-green', x: 531, y: 6, s: 218 },
            { class: 'halo-2018 halo-blue', x: 202, y: 87, s: 257 },
            { class: 'halo-2018 halo-purple', x: -8, y: -17, s: 220 },
        ];

        haloData.forEach(function(cd) {
            // var src = IMAGE_BASE_PATH + cd.src;
            var $halo = $('
');
            $halo.css('left', cd.x / 2);
            $halo.css('top', cd.y / 2);
            $halo.css('width', cd.s / 2);
            $halo.css('height', cd.s / 2);
            $container.append($halo);
            haloElements.push($halo);
        });

        document.addEventListener('mouseover', function() {
            haloElements.forEach(function(haloElement, index) {
                var val = Math.sin(new Date().valueOf() / 1000 + index);
                haloElement.css('opacity', val * 0.5 + 0.5);
            });
        }, 500);
    }
    halos();

    function backgrounds() {
        var bgElements = [
            '.layer-cyan',
            '.layer-green',
            '.layer-purple',
            '.layer-yellow'
        ].map(function(selector) {
            return $(selector);
        });

        // minimum delay between animations
        var DELAY = 2500;
        // track whether the user is interacting with the page or not
        var interacting = false;

        function update() {
            if(!interacting) {
                return;
            }
            interacting = false;
            // Using the clock for this keeps the look consistent when navigating.
            var x = new Date().valueOf() / 2000;
            bgElements.forEach(function(bgElement, index) {
                bgElement.css('opacity', 0.5 + 0.5 * Math.sin((x + index) * Math.PI / 4));
            });
        }

        function onInteraction() {
            interacting = true;
        }

        document.addEventListener('mouseover', onInteraction);
        document.addEventListener('mousedown', onInteraction);
        document.addEventListener('keydown', onInteraction);

        // Start the 2 s animation every 2+ s.
        // The transitions sometimes glitch on Firefox if the opacity
        // target value changes mid-transition.
        // The gap isn't too noticeable, especially with ease-in-out.
        setInterval(update, DELAY);
        update();
    }
    backgrounds();
});<|endoftext|>


<commit_before>define([
    "helper/HostApp",
    "helper/Paths",
    "helper/Hmac"
],

function(HostApp, Paths, Hmac) {

    function Oauth() {
        this.app_info = {
            "id": null,
            "name": "Tentia",
            "description": "A small TentStatus client.",
            "url": "http://jabs.nu/Tentia/",
            "icon": "http://jabs.nu/Tentia/icon.png",
            "redirect_uris": [
                "tentia://oauthtoken"
            ],
            "scopes": {
                "read_posts": "Uses posts to show them in a list",
                "write_posts": "Posts on users behalf",
                "read_profile": "Displays your own profile",
                "write_profile": "Updating profile and mentions pointer",
                "read_followers": "Display a list of people who follow you",
                "write_followers": "Be able to block people who follow you",
                "read_followings": "Display following list and their older posts in conversations",
                "write_followings": "Follow ne entities"
            }
        };

        this.register_data = null;
        this.profile = null;
        this.state = null;
    }

    Oauth.prototype.authenticate = function() {
        var entity = HostApp.stringForKey("entity");

        if (entity && (entity.startsWith("http://") || entity.startsWith("https://"))) {
            this.entity = entity;
            this.requestProfileURL(this.entity);
        } else {
            HostApp.authentificationDidNotSucceed("The entity should start with https:// or http://");
        }
    }

    Oauth.prototype.apiRoot = function() {
        return this.profile["https://tent.io/types/info/core/v0.1.0"]["servers"][0];
    }

    Oauth.prototype.requestProfileURL = function (entity) {
        var those = this;
        Paths.findProfileURL(entity,
            function(profile_url) {
                if (profile_url && (profile_url.startsWith("http://") || profile_url.startsWith("https:(("))) {
                    those.register(profile_url);
                } else {
                    HostApp.authentificationDidNotSucceed("Could not find profile for: " + entity);
                }
            },
            function(errorMessage) { // error callback
                HostApp.authentificationDidNotSucceed("Could not find profile for: " + entity);
            }
        );
    }

    Oauth.prototype.register = function (url) {
        var those = this;
        Paths.getURL(url, "GET", function(resp) {
            those.profile = JSON.parse(resp.responseText);
            HostApp.setStringForKey(those.apiRoot(), "api_root");
            var callback = function(resp) {
                var data = JSON.parse(resp.responseText);
                those.authRequest(data);
            }
            Paths.getURL(Paths.mkApiRootPath("/apps"), "POST", callback, JSON.stringify(those.app_info));
        });
    }

    Oauth.prototype.authRequest = function(register_data) {
        // id
        // mac_key_id
        // mac_key
        // mac_algorithm
        this.register_data = register_data;

        // Needed for later App Registration Modification
        HostApp.setStringForKey(register_data["mac_key"], "app_mac_key");
        HostApp.setStringForKey(register_data["mac_key_id"], "app_mac_key_id");
        HostApp.setStringForKey(register_data["id"], "app_id");
        HostApp.setStringForKey(register_data["mac_algorithm"], "app_mac_algorithm");

        this.state = Hmac.makeid(19);
        var auth = "/oauth/authorize?client_id=" + register_data["id"]
                    + "&redirect_uri=" + escape(this.app_info["redirect_uris"][0])
                    + "&scope=" + Object.keys(this.app_info["scopes"]).join(",")
                    + "&state=" + this.state
                    + "&tent_post_types=all";

        HostApp.openURL(this.apiRoot() + auth);
    }

    Oauth.prototype.requestAccessToken = function(responseBody) {
            // /oauthtoken?code=51d0115b04d1ed94001dde751c5b360f&state=aQfH1VEohYsQr86qqyv
            var urlVars = Paths.getUrlVars(responseBody);
            if(this.state && this.state != "" && urlVars["state"] == this.state) {

                var url = Paths.mkApiRootPath("/apps/") + this.register_data["id"] + "/authorizations";

                var requestBody = JSON.stringify({
                    'code' : urlVars["code"],
                    'token_type' : "mac"
                });

                var those = this;
                var http_method = "POST";
                var callback = function(resp) {
                    those.requestAccessTokenTicketFinished(resp.responseText);
                };

                var auth_header = Hmac.makeAuthHeader(
                        url,
                        http_method,
                        HostApp.stringForKey("app_mac_key"),
                        HostApp.stringForKey("app_mac_key_id")
                    );

                Paths.getURL(url, http_method, callback, requestBody, auth_header);

            } else {
                alert("State is not the same: {" + this.state + "} vs {" + urlVars["state"] + "}")
            }

            this.state = null; // reset the state
    }

    Oauth.prototype.requestAccessTokenTicketFinished = function(responseBody) {

        var access = JSON.parse(responseBody);

        HostApp.setStringForKey(access["access_token"], "user_access_token");
        HostApp.setStringForKey(access["mac_key"], "user_mac_key");
        HostApp.setStringForKey(access["mac_algorithm"], "user_mac_algorithm");
        HostApp.setStringForKey(access["token_type"], "user_token_type");

        HostApp.loggedIn();
    }

    Oauth.prototype.logout = function() {

    }

    return Oauth;

});<commit_msg>fixed #56<commit_after>define([
    "helper/HostApp",
    "helper/Paths",
    "helper/Hmac"
],

function(HostApp, Paths, Hmac) {

    function Oauth() {
        this.app_info = {
            "id": null,
            "name": "Tentia",
            "description": "A small TentStatus client.",
            "url": "http://jabs.nu/Tentia/",
            "icon": "http://jabs.nu/Tentia/icon.png",
            "redirect_uris": [
                "tentia://oauthtoken"
            ],
            "scopes": {
                "read_posts": "Uses posts to show them in a list",
                "write_posts": "Posts on users behalf",
                "read_profile": "Displays your own profile",
                "write_profile": "Updating profile and mentions pointer",
                "read_followers": "Display a list of people who follow you",
                "write_followers": "Be able to block people who follow you",
                "read_followings": "Display following list and their older posts in conversations",
                "write_followings": "Follow ne entities"
            }
        };

        this.register_data = null;
        this.profile = null;
        this.state = null;
    }

    Oauth.prototype.authenticate = function() {
        var entity = HostApp.stringForKey("entity");

        if (entity && (entity.startsWith("http://") || entity.startsWith("https://"))) {
            this.entity = entity;
            this.requestProfileURL(this.entity);
        } else {
            HostApp.authentificationDidNotSucceed("The entity should start with https:// or http://");
        }
    }

    Oauth.prototype.apiRoot = function() {
        return this.profile["https://tent.io/types/info/core/v0.1.0"]["servers"][0];
    }

    Oauth.prototype.requestProfileURL = function (entity) {
        var those = this;
        Paths.findProfileURL(entity,
            function(profile_url) {
                if (profile_url && (profile_url.startsWith("http://") || profile_url.startsWith("https://"))) {
                    those.register(profile_url);
                } else {
                    HostApp.authentificationDidNotSucceed("Could not find profile for: " + entity);
                }
            },
            function(errorMessage) { // error callback
                HostApp.authentificationDidNotSucceed("Could not find profile for: " + entity);
            }
        );
    }

    Oauth.prototype.register = function (url) {
        var those = this;
        Paths.getURL(url, "GET", function(resp) {
            those.profile = JSON.parse(resp.responseText);
            HostApp.setStringForKey(those.apiRoot(), "api_root");
            var callback = function(resp) {
                var data = JSON.parse(resp.responseText);
                those.authRequest(data);
            }
            Paths.getURL(Paths.mkApiRootPath("/apps"), "POST", callback, JSON.stringify(those.app_info));
        });
    }

    Oauth.prototype.authRequest = function(register_data) {
        // id
        // mac_key_id
        // mac_key
        // mac_algorithm
        this.register_data = register_data;

        // Needed for later App Registration Modification
        HostApp.setStringForKey(register_data["mac_key"], "app_mac_key");
        HostApp.setStringForKey(register_data["mac_key_id"], "app_mac_key_id");
        HostApp.setStringForKey(register_data["id"], "app_id");
        HostApp.setStringForKey(register_data["mac_algorithm"], "app_mac_algorithm");

        this.state = Hmac.makeid(19);
        var auth = "/oauth/authorize?client_id=" + register_data["id"]
                    + "&redirect_uri=" + escape(this.app_info["redirect_uris"][0])
                    + "&scope=" + Object.keys(this.app_info["scopes"]).join(",")
                    + "&state=" + this.state
                    + "&tent_post_types=all";

        HostApp.openURL(this.apiRoot() + auth);
    }

    Oauth.prototype.requestAccessToken = function(responseBody) {
            // /oauthtoken?code=51d0115b04d1ed94001dde751c5b360f&state=aQfH1VEohYsQr86qqyv
            var urlVars = Paths.getUrlVars(responseBody);
            if(this.state && this.state != "" && urlVars["state"] == this.state) {

                var url = Paths.mkApiRootPath("/apps/") + this.register_data["id"] + "/authorizations";

                var requestBody = JSON.stringify({
                    'code' : urlVars["code"],
                    'token_type' : "mac"
                });

                var those = this;
                var http_method = "POST";
                var callback = function(resp) {
                    those.requestAccessTokenTicketFinished(resp.responseText);
                };

                var auth_header = Hmac.makeAuthHeader(
                        url,
                        http_method,
                        HostApp.stringForKey("app_mac_key"),
                        HostApp.stringForKey("app_mac_key_id")
                    );

                Paths.getURL(url, http_method, callback, requestBody, auth_header);

            } else {
                alert("State is not the same: {" + this.state + "} vs {" + urlVars["state"] + "}")
            }

            this.state = null; // reset the state
    }

    Oauth.prototype.requestAccessTokenTicketFinished = function(responseBody) {

        var access = JSON.parse(responseBody);

        HostApp.setStringForKey(access["access_token"], "user_access_token");
        HostApp.setStringForKey(access["mac_key"], "user_mac_key");
        HostApp.setStringForKey(access["mac_algorithm"], "user_mac_algorithm");
        HostApp.setStringForKey(access["token_type"], "user_token_type");

        HostApp.loggedIn();
    }

    Oauth.prototype.logout = function() {

    }

    return Oauth;

});<|endoftext|>


<commit_before>console.log(['Z', 'a', 'z', 'ä'].sort(new Intl.Collator('de').compare));
// expected output: ["a", "ä", "z", "Z"]

console.log(['Z', 'a', 'z', 'ä'].sort(new Intl.Collator('sv').compare));
// expected output: ["a", "z", "Z", "ä"]

console.log(['Z', 'a', 'z', 'ä'].sort(new Intl.Collator('de', {caseFirst: 'upper'} ).compare));
// expected output: ["a", "ä", "Z", "z"]
<commit_msg>Run --fix on the changed file<commit_after>console.log(['Z', 'a', 'z', 'ä'].sort(new Intl.Collator('de').compare));
// expected output: ["a", "ä", "z", "Z"]

console.log(['Z', 'a', 'z', 'ä'].sort(new Intl.Collator('sv').compare));
// expected output: ["a", "z", "Z", "ä"]

console.log(['Z', 'a', 'z', 'ä'].sort(new Intl.Collator('de', { caseFirst: 'upper' } ).compare));
// expected output: ["a", "ä", "Z", "z"]
<|endoftext|>


<commit_before>/* Reload the aframe dynamically, as needed
 */

var x = "";
var debuging = {};
var gui;

// We describe specific elements using the path from the a-scene,
// as a list of children #'s, from top to bottom.
// This returns a jquery selector
function sceneElementSelector(o) {
  console.log("sceneElementSelector",o)
  if (o == "") { return "a-scene"; }
  return "a-scene > " + o.split(".").map(function(v) {
    return ":nth-child(" + v + ")"
  }).join(" > ");
}

// This returns a textual descriptor
function sceneElementDescription(o) {
 if (o == "") { return ""; }
 var r = o.split(".").map(function(v) {
    var i = (v < 10?" ":"") + v;
    return i;
  }).join(" . ") + " -";
  var j = $(sceneElementSelector(o));
  if (j.prop("tagName")) {
    r += " " + j.prop("tagName");
  }
  if (j.attr("id")) {
    r += " #" + j.attr("id")
  }
  return r
}

function sceneElements() {
  console.log("sceneElements")
  var r = []
  function rec(o) {
    var ch = $(sceneElementSelector(o)).children();
    for(var i = 0;i < ch.length;i++) {
      var p = (o == "")?(o + (i+1)):(o + "." + (i+1))
      if ($(sceneElementSelector(p)).prop("tagName").substring(0,2) == "A-") {
        r.push(p)
        rec(p)
      }
    }
  }
  rec("")
  return r
}

$(function(){
  gui    = new dat.GUI();
  dat.GUI.prototype.removeFolder = function(name) {
    var folder = this.__folders[name];
    if (!folder) {
      return;
    }
    folder.close();
    this.__ul.removeChild(folder.domElement.parentNode);
    delete this.__folders[name];
    this.onResize();
  }
  console.log("Here");
  debug = {}
  var url = window.location

  var defaults =
           { position: new THREE.Vector3( 0, 0, 0 )
           , rotation: new THREE.Vector3( 0, 0, 0 )
           , scale:    new THREE.Vector3( 1, 1, 1 )
           , visible:  true
           };
  var steps =
           { position: 0.025
           , rotation: 1
           , scale:    0.1
           };

  active = { entity: "1"
           , position: defaults.position.clone()
           , rotation: defaults.rotation.clone()
           , scale:    defaults.scale.clone()
           , visible:  defaults.visible
           }

  // Insert a marker. Above the marker is HTML we have inserted, and below the marker is auto-generated.
  //      $("a-scene").prepend("<div aframe-marker></div>");

  var reloadGUI = function() {
    // We already have a gui object

    var changeEntity = function(value) {
      console.log("reloadGUI.entity",value)
      active.entity = value;
      $("[active-entity]").removeAttr("active-entity")
      var me = $(sceneElementSelector(value));
      me.attr("active-entity","true")
      function fillAttr(attr) {
        var a = me[0].getAttribute(attr)
        if (a == null) {
          a = defaults[attr]
        }
        for (var i in active[attr]) {
          active[attr][i] = a[i]
        }
      }
      fillAttr("position")
      fillAttr("rotation")
      fillAttr("scale")
    };
    var se = sceneElements()
    var entityDict = {}
    se.map(function(v) {
      entityDict[sceneElementDescription(v)] = v
    });
    active.entity = "1"
    changeEntity(se[0])

    var changePosition = function(value) {
      var me = $(sceneElementSelector(active.entity));
      me[0].setAttribute("position",active.position)
      me[0].setAttribute("rotation",active.rotation)
      me[0].setAttribute("scale",active.scale)
      me[0].setAttribute("visible",active.visible)
    }

    // Clear the inspector
    reloadGUI.entity && gui.remove(reloadGUI.entity)
    for (var i in defaults) {
      // TODO: if/then/else
      if (typeof(defaults[i]) == "boolean") {
        reloadGUI[i] && gui.remove(reloadGUI[i])
      } else {
        gui.removeFolder(i)
      }
    }

    // And refill it
    reloadGUI.entity = gui.add(active, 'entity', entityDict );
    reloadGUI.entity.onChange(changeEntity);
    for (var i in defaults) {
      if (typeof(defaults[i]) == "boolean") {
        reloadGUI[i] = gui.add(active,i).listen().onChange(changePosition);
      } else {
        var folder = gui.addFolder(i)
        var xyz = ['x','y','z'] // TODO: look this up from a table.
        for(var j in xyz) {
          console.log(i,j,active[i])
          folder.add(active[i],xyz[j]).step(steps[i]).listen().onChange(changePosition);
        }
      }
    }

//        reloadGUI.entity.add(active,'entity', ['A','B'])
  }

  debug.reloadGUI = reloadGUI
  // Every second, update the scene
  var sceneText = "";
  var resetScene = function(data) {
//        console.log("checking")
    if (data == sceneText) {
        setTimeout(loadScene,1000)
        return;
    }
    sceneText = data;
    x = sceneText;

    if ($("a-scene").length == 0) {
      $("body").prepend(data);
    } else {
      var ch = $("a-scene").children();
      for(i = 0;i < ch.length;i++) {
        if (!ch[i].localName
              || ch[i].localName == "canvas"
              || ch[i].localName == "div"
              || !ch[i].attributes
              || ch[i].attributes["data-aframe-default-light"]
              || ch[i].attributes["data-aframe-default-camera"]
        ) {
//              console.log("leaving " + i);
        } else {
//              console.log("removing " + i)
          // This appears to be leaving the Three.js Gemoetries behind.
          // TODO: check into this
          $(ch[i]).remove()
        }
      }
//          console.log("childern",$("a-scene").children())
      // repace a-scene with x-scene to avoid triggering the a-scene callback
      // (which inserts the defaults, and therefor makes two camera, which confuses
      //  the THREE.js sub-system). Note replace only replaces the *first*
      // a-scene of the string, so will not effect any properties.
      var xml = $(data.replace("a-scene","x-scene"));
      console.log(xml)
      xml.children().prependTo("a-scene");
      $("a-scene").attr("version",xml.attr("version"))  // update the version number
    }
    reloadGUI()
    setTimeout(loadScene,1000)
  }
  var updateScene = function(d) {
    console.log("updateScene",d)
    if (d.change && d.change == "HEAD") {
      return loadScene();
    } else {
      loadScene("RELOAD");
    }
  }
  var loadScene = function(ty) {
    var version = $("a-scene").attr("version");
    if (version == undefined || ty == "RELOAD") {
      // do this the slow way
      $.get( "/scene", resetScene);
    } else {
      // check for changes
      $.getJSON( "/status/" + version, updateScene);
    }
  }
  loadScene("RELOAD")
});

<commit_msg>remove the inspector from the push module<commit_after>/* Reload the aframe dynamically, as needed
 */

$(function(){

  // Every second, update the scene
  var sceneText = "";
  var resetScene = function(data) {
//        console.log("checking")
    if (data == sceneText) {
        setTimeout(loadScene,1000)
        return;
    }
    sceneText = data;
    x = sceneText;

    if ($("a-scene").length == 0) {
      $("body").prepend(data);
    } else {
      var ch = $("a-scene").children();
      for(i = 0;i < ch.length;i++) {
        if (!ch[i].localName
              || ch[i].localName == "canvas"
              || ch[i].localName == "div"
              || !ch[i].attributes
              || ch[i].attributes["data-aframe-default-light"]
              || ch[i].attributes["data-aframe-default-camera"]
        ) {
//              console.log("leaving " + i);
        } else {
//              console.log("removing " + i)
          // This appears to be leaving the Three.js Gemoetries behind.
          // TODO: check into this
          $(ch[i]).remove()
        }
      }
//          console.log("childern",$("a-scene").children())
      // repace a-scene with x-scene to avoid triggering the a-scene callback
      // (which inserts the defaults, and therefor makes two camera, which confuses
      //  the THREE.js sub-system). Note replace only replaces the *first*
      // a-scene of the string, so will not effect any properties.
      var xml = $(data.replace("a-scene","x-scene"));
      console.log(xml)
      xml.children().prependTo("a-scene");
      $("a-scene").attr("version",xml.attr("version"))  // update the version number
    }
    setTimeout(loadScene,1000)
  }
  var updateScene = function(d) {
    console.log("updateScene",d)
    if (d.change && d.change == "HEAD") {
      return loadScene();
    } else {
      loadScene("RELOAD");
    }
  }
  var loadScene = function(ty) {
    var version = $("a-scene").attr("version");
    if (version == undefined || ty == "RELOAD") {
      // do this the slow way
      $.get( "/scene", resetScene);
    } else {
      // check for changes
      $.getJSON( "/status/" + version, updateScene);
    }
  }
  loadScene("RELOAD")
});

<|endoftext|>


<commit_before>(function(){

	$( document ).ready(function(){
		if (!window.amnestySSO) {
			window.amnestySSO = {
				init : false
			}
		}

		if (!window.amnestySSO.init) {
			var html = '\

\

\

\

\
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\

\

\
	      	\

\

\

\

\
			';
			$('body').append(html);

			$('#amnesty-sso-modal-login').click(function(){
				$('#amnestySSOModal iframe').attr('src', imServerUrl + '/login/modal');
				$('#amnestySSOModal').modal('show');
			});

			window.addEventListener("message", receiveMessage, false);
			function receiveMessage(event)
			{
				var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
				if (origin !== imServerUrl)
					return;

				$.post('/amnesty/oauth-authorized-with-password', {
						'access_token': event.data['access_token'],
						'csrf_token': $('#ajax_csrf_token').val()
					})
					.done(function(data){
						console.log(data);
					});
				console.log('data:' + event.data['access_token']);
			}
		}
	});

})();
<commit_msg>reload page after login success<commit_after>(function(){

	$( document ).ready(function(){
		if (!window.amnestySSO) {
			window.amnestySSO = {
				init : false
			}
		}

		if (!window.amnestySSO.init) {
			var html = '\

\

\

\

\
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\

\

\
	      	\

\

\

\

\
			';
			$('body').append(html);

			$('#amnesty-sso-modal-login').click(function(){
				$('#amnestySSOModal iframe').attr('src', imServerUrl + '/login/modal');
				$('#amnestySSOModal').modal('show');
			});

			window.addEventListener("message", receiveMessage, false);
			function receiveMessage(event)
			{
				var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
				if (origin !== imServerUrl)
					return;

				$.post('/amnesty/oauth-authorized-with-password', {
						'access_token': event.data['access_token'],
						'csrf_token': $('#ajax_csrf_token').val()
					})
					.done(function(data){
						location.reload();
					})
					.fail(function(data){
        				console.log('failed');
        				console.log(data);
        			})
        			.always(function(){
        			});
			}
		}
	});

})();
<|endoftext|>


<commit_before>var cy = cytoscape();

// {name : position} dict
var prebuilt_model = 'McCormick';
var preset_pos = {};
var preset_pos_static = {};

// {id : position} dict
var id_pos = {};

var scapes = {};
var stmts;
var sentences;
var evidence = {};
var cyjs_elements; //this is set by drawCytoscape with a copy of model_elements
var model_elements;
var mrna;
var mutations;
var cell_line;
var txt_input;
var network_id;

var indra_server_addr = "http://indra-api-72031e2dfde08e09.elb.us-east-1.amazonaws.com:8000";
//var indra_server_addr = "http://0.0.0.0:8080";

var ctxt = {};

var ras_model_promise = grabJSON('static/models/' + prebuilt_model + '/model.json');
var ras_preset_pos_promise = grabJSON('static/models/' + prebuilt_model + '/preset_pos.json');
var mrna_promise = grabJSON('static/models/' + prebuilt_model + '/mrna.json');
var mutations_promise = grabJSON('static/models/' + prebuilt_model + '/mutations.json');
var model_components_promise = Promise.all([ras_model_promise, ras_preset_pos_promise, mrna_promise, mutations_promise]);
model_components_promise.then(function(promises){
  preset_pos = promises[1];
  model_elements = promises[0];
  mrna = promises[2];
  mutations = promises[3];
  drawCytoscape ('cy_1', model_elements);
  qtipNodes(scapes['cy_1']);
  scapes['cy_1'].fit();
  contextualizeNodesCCLEprebuilt(scapes['cy_1'], mrna, mutations)
})
var ras_stmts_promise = grabJSON('static/models/' + prebuilt_model + '/stmts.json');
var ras_stmts_response;
ras_stmts_promise.then(function(res){
  ras_stmts_response = res;
  stmts = ras_stmts_response;
})
var ras_sentences_promise = grabJSON('static/models/' + prebuilt_model + '/sentences.json');
var ras_sentences_response;
ras_sentences_promise.then(function(res){
  ras_sentences_response = res;
  sentences = res;
})

var domain = [2.7, 3.7, 4.7, 5.7, 6.7, 7.7, 8.7, 9.7, 10.7];
var exp_colorscale = d3.scaleThreshold()
    .domain(domain)
    .range(['#f7fcf5','#e5f5e0','#c7e9c0','#a1d99b','#74c476','#41ab5d','#238b45','#006d2c','#00441b']);
var mut_colorscale =  d3.scaleThreshold()
    .domain(domain)
    .range(['#fff5eb','#fee6ce','#fdd0a2','#fdae6b','#fd8d3c','#f16913','#d94801','#a63603','#7f2704']);

var parser = 'reach';

var select_array;
var sub_select_array;
var unique_col_val;

var ctx_select_divs = ['#drug_select', '#conc_select', '#time_select', '#cell_line_select'];
var current_ctx_selection = new Array(ctx_select_divs.length).fill("");

var paths;
var table_data;
var path_uuids_dict = {};
var table;
var path_id;

$(function(){

  var win = $(window);
  var container_fluid_height = ($('body').height());
  var cy_height = String(container_fluid_height/1.2024);
  $('.cy')[0].setAttribute("style", "height:" + cy_height +  "px;");
  $('.cy-container')[0].setAttribute("style", "height:" + cy_height +  "px;");

  // build the dropdown pickers
  grabJSON('static/cell_dict.json').then(
    function(ajax_response){
      var interesting_lines = {"LOXIMVI_SKIN":"model_LOXIMVI_SKIN.json", "A101D_SKIN":"model_A101D_SKIN.json"};
      for (var d of ['#cellSelectStatic', '#cellSelectDynamic']) {
          dropdownFromJSON(d, interesting_lines);
          $(d).append($('<option data-divider="true"/>'));
        }
      for (var d of ['#cellSelectStatic', '#cellSelectDynamic']) {
          dropdownFromJSON(d, ajax_response);
        }
      }
  );

  $("#loadButtonDynamic").click(function(){
    var txt = $('#textArea')[0].value;
    var stmts_promise = txtProcess(txt, parser).then(groundingMapper);
    var cyjs_promise = stmts_promise.then(assembleCyJS);
    var english_promise = stmts_promise.then(assembleEnglish)
    var english_promise;
    stmts_promise.then(function (model_response) {
      stmts = model_response;
    });
    cyjs_promise.then(function (model_response) {
      model_elements = model_response;
      drawCytoscape('cy_1', model_response);
      qtipNodes(scapes['cy_1']);
      $('#menu').modal('hide');
      document.getElementById("loadContextButton").click();
    });
    english_promise.then(function (model_response) {
      sentences = model_response;
    })
  });

  $("#loadContextButton").click(function(){
    cell_line = $('#cellSelectDynamic').val().slice(6,-5);
    contextualizeNodesCCLE(cy, cell_line);
    $('#menu').modal('hide');
  });

  $("#downloadPySB").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assemblePySB).then(function (res) {
      download('model.py', res['model']);
    });
  });

  $("#downloadSBML").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleSBML).then(function (res) {
      download('model.sbml', res['model']);
    });
  });

  $("#downloadSBGN").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleSBGN).then(function (res) {
      download('model.sbgn', res['model']);
    });
  });

  $("#downloadKappa").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleKappa).then(function (res) {
      download('model.ka', res['model']);
    });
  });

  $("#downloadBNGL").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleBNGL).then(function (res) {
      download('model.bngl', res['model']);
    });
  });

  $("#downloadCX").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleCX).then(function (res) {
      download('model.cx', res['model']);
    });
  });

  $("#NDEX_upload_btn").click(function(){
    var modal_body = $('.ndex-upload-container')[0]
    modal_body.innerHTML = null
    var par = document.createElement("p");
    par.textContent = 'Uploading model to NDEX...'
    modal_body.append(par)
    txt_input = $('#textArea')[0].value;
    shareNDEX(cyjs_elements, preset_pos, stmts, sentences, evidence, cell_line, mrna, mutations, txt_input, parser).then(function (res) {
      par.textContent = 'Network uploaded to NDEX.'
      var par2 = document.createElement("p");
      network_id = res['network_id']
      var network_address =  "http://ndexbio.org/#/network/" + network_id
      var temp_link = document.createElement("a");
      temp_link.href = network_address;
      temp_link.text = network_address;
      temp_link.target = '_blank';
      par2.append(temp_link);
      modal_body.append(par2);
    });
  });

  $("#loadNDEX").click(function(){
    var network_id = $("#ndexUUID")[0].value
    getNDEX(network_id).then(function (res) {
      model_elements = JSON.parse(res.model_elements)
      preset_pos = JSON.parse(res.preset_pos)
      stmts = JSON.parse(res.stmts)
      sentences = JSON.parse(res.sentences)
      evidence = JSON.parse(res.evidence)
      cell_line = res.cell_line
      $('#cellSelectDynamic').selectpicker()[0].value = 'model_' + cell_line + '.json'
      $('#cellSelectDynamic').selectpicker('refresh')
      mrna = JSON.parse(res.mrna)
      mutations = JSON.parse(res.mutations)
      txt_input = res.txt_input;
      $('#textArea').val(txt_input);
      parser = res.parser;
      $("#parseReach")[0].classList.remove('active')
      $("#parseTrips")[0].classList.remove('active')
      if (parser == 'trips'){
        $("#parseTrips").addClass("active");
      }
      else {
        $("#parseReach").addClass("active");
      }
      drawCytoscape ('cy_1', model_elements);
      qtipNodes(scapes['cy_1']);
      scapes['cy_1'].fit();
      contextualizeNodesCCLEprebuilt(scapes['cy_1'], mrna, mutations)
    });
  });

  $("#downloadINDRA").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(function (res) {
      download('stmts.json', JSON.stringify(res['statements'], null, 2));
    });
  });

  $("#downloadPNG").click(function(){
    var png_scale = 20;
    var cypng = scapes['cy_1'].png({scale: png_scale, output:'blob'});
    // console.log(cypng.length)
    while (cypng.length < 7) {
      png_scale -= 1;
      cypng = scapes['cy_1'].png({scale: png_scale, output:'blob'});
    }
    download('model.png', cypng);
  });

  $("#loopy").click(function(){
    var txt = $('#textArea')[0].value;

    txtProcess(txt, parser).then(groundingMapper).then(assembleLoopy).then(function (res) {

        window.open(
          res['loopy_url'].toString(),
          "_blank"
        );
    });
  });

$("#loadButtonStatic").click(function(){
  model_promise = grabJSON('static/models/' + prebuilt_model + '/model.json');
  preset_pos_promise = grabJSON('static/models/' + prebuilt_model + '/preset_pos.json');
  txt_input_promise = grabJSON('static/models/' + prebuilt_model + '/txt_input.json', dtype='text');
  var model_components_promise = Promise.all([model_promise, preset_pos_promise, txt_input_promise]);
  model_components_promise.then(function(promises){
    preset_pos = promises[1];
    model_elements = promises[0];
    txt_input = promises[2];
    drawCytoscape ('cy_1', model_elements);
    qtipNodes(scapes['cy_1']);
    $('#textArea').val(txt_input);
    scapes['cy_1'].fit();
    document.getElementById("loadContextButton").click();
  })

});

$(".cyjs2loopy").click(function(){
  var model = loopyFromCyJS("cy_1");
  window.open(
    'http://ncase.me/loopy/v1/?data=' + model,
    "_blank"
  );
});

$(".presetLayout").click(function(){
  if (this.classList.contains("active")){
    $(".presetLayout").removeClass("active");
    preset_pos = {};
  }
  else {
    $(".presetLayout").addClass("active");
    preset_pos = preset_pos_static;
  }
});

$('a[href="#byom"]').click(function(){
  if (this.classList.contains("active") === false){
    preset_pos = {};
  }
});

$("#parseReach").click(function(){
  if (this.classList.contains("active")){
    $("#parseReach").removeClass("active");
    $("#parseTrips").addClass("active");
    parser='trips';
  }
  else {
    $("#parseReach").addClass("active");
    $("#parseTrips").removeClass("active");
    parser='reach';
  }
});

$("#parseTrips").click(function(){
  if (this.classList.contains("active")){
    $("#parseTrips").removeClass("active");
    $("#parseReach").addClass("active");
    parser='reach';
  }
  else {
    $("#parseTrips").addClass("active");
    $("#parseReach").removeClass("active");
    parser='trips';
  }
});

$('a[href="#ras227"]').click(function(){
  preset_pos = preset_pos_static;
});

// change prebuilt_model name every time the user changes dropdown
$('#model_picker').on('changed.bs.select', function(){
  prebuilt_model = $('#model_picker').selectpicker('val');
});

// change prebuilt_model name every time the user changes dropdown
$('.ctx-select').on('changed.bs.select', function(){
  var div_id = "#" + this.id;
  var val = $(div_id).selectpicker('val');
  current_ctx_selection[ctx_select_divs.indexOf(div_id)] = val;
  sub_select_array = array_multifilter(sub_select_array, current_ctx_selection);
  clearCtxtSelects();
  build_ctx_dropdowns(sub_select_array, ctx_select_divs, current_ctx_selection);
});

$("#reset_filter").click(function(){
  sub_select_array = select_array;
  current_ctx_selection = new Array(ctx_select_divs.length).fill("");
  clearCtxtSelects();
  build_ctx_dropdowns(sub_select_array, ctx_select_divs, current_ctx_selection);
  grabJSON('static/models/' + prebuilt_model + '/model.json').then(function (model_response) {
    model_elements = model_response;
    drawCytoscape ('cy_1', model_response);
    qtipNodes(scapes['cy_1']);
  });
});

$("#load_context").click(function(){
  condition = current_ctx_selection.join('_');
  phosphoContextSN(scapes['cy_1'], ctxt, condition);
});

$('#path_table').on( 'click', 'tr', function () {
        if ( $(this).hasClass('selected') ) {
            $(this).removeClass('selected');
        }
        else {
            table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
            path_id = this.childNodes[5].innerText;
            highlightPath(scapes['cy_1'], path_uuids_dict[path_id]);
        }
    } );

$('.cy').each(function(){
  $('.cy')[0].setAttribute("style", "height: 100%;");
  // document.getElementById("loadButtonStatic").click();
  function resize() {
    $(".cy-container").height(win.innerHeight() - 250);
    $(".cy").height(win.innerHeight() - 250);
    if (scapes['cy_1']){
      scapes['cy_1'].center();
    }
  }

  var resizeTimer;
  $(window).on('resize', function(e) {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
      resize();
    }, 250);
  });
  setTimeout(resize, 0);
});

});// dom ready
<commit_msg>clear ndex upload info anytime the drawCytoscape called<commit_after>var cy = cytoscape();

// {name : position} dict
var prebuilt_model = 'McCormick';
var preset_pos = {};
var preset_pos_static = {};

// {id : position} dict
var id_pos = {};

var scapes = {};
var stmts;
var sentences;
var evidence = {};
var cyjs_elements; //this is set by drawCytoscape with a copy of model_elements
var model_elements;
var mrna;
var mutations;
var cell_line;
var txt_input;
var network_id;

var indra_server_addr = "http://indra-api-72031e2dfde08e09.elb.us-east-1.amazonaws.com:8000";
//var indra_server_addr = "http://0.0.0.0:8080";

var ctxt = {};

var ras_model_promise = grabJSON('static/models/' + prebuilt_model + '/model.json');
var ras_preset_pos_promise = grabJSON('static/models/' + prebuilt_model + '/preset_pos.json');
var mrna_promise = grabJSON('static/models/' + prebuilt_model + '/mrna.json');
var mutations_promise = grabJSON('static/models/' + prebuilt_model + '/mutations.json');
var model_components_promise = Promise.all([ras_model_promise, ras_preset_pos_promise, mrna_promise, mutations_promise]);
model_components_promise.then(function(promises){
  preset_pos = promises[1];
  model_elements = promises[0];
  mrna = promises[2];
  mutations = promises[3];
  drawCytoscape ('cy_1', model_elements);
  clearUploadInfo();
  qtipNodes(scapes['cy_1']);
  scapes['cy_1'].fit();
  contextualizeNodesCCLEprebuilt(scapes['cy_1'], mrna, mutations)
})
var ras_stmts_promise = grabJSON('static/models/' + prebuilt_model + '/stmts.json');
var ras_stmts_response;
ras_stmts_promise.then(function(res){
  ras_stmts_response = res;
  stmts = ras_stmts_response;
})
var ras_sentences_promise = grabJSON('static/models/' + prebuilt_model + '/sentences.json');
var ras_sentences_response;
ras_sentences_promise.then(function(res){
  ras_sentences_response = res;
  sentences = res;
})

var domain = [2.7, 3.7, 4.7, 5.7, 6.7, 7.7, 8.7, 9.7, 10.7];
var exp_colorscale = d3.scaleThreshold()
    .domain(domain)
    .range(['#f7fcf5','#e5f5e0','#c7e9c0','#a1d99b','#74c476','#41ab5d','#238b45','#006d2c','#00441b']);
var mut_colorscale =  d3.scaleThreshold()
    .domain(domain)
    .range(['#fff5eb','#fee6ce','#fdd0a2','#fdae6b','#fd8d3c','#f16913','#d94801','#a63603','#7f2704']);

var parser = 'reach';

var select_array;
var sub_select_array;
var unique_col_val;

var ctx_select_divs = ['#drug_select', '#conc_select', '#time_select', '#cell_line_select'];
var current_ctx_selection = new Array(ctx_select_divs.length).fill("");

var paths;
var table_data;
var path_uuids_dict = {};
var table;
var path_id;

$(function(){

  var win = $(window);
  var container_fluid_height = ($('body').height());
  var cy_height = String(container_fluid_height/1.2024);
  $('.cy')[0].setAttribute("style", "height:" + cy_height +  "px;");
  $('.cy-container')[0].setAttribute("style", "height:" + cy_height +  "px;");

  // build the dropdown pickers
  grabJSON('static/cell_dict.json').then(
    function(ajax_response){
      var interesting_lines = {"LOXIMVI_SKIN":"model_LOXIMVI_SKIN.json", "A101D_SKIN":"model_A101D_SKIN.json"};
      for (var d of ['#cellSelectStatic', '#cellSelectDynamic']) {
          dropdownFromJSON(d, interesting_lines);
          $(d).append($('<option data-divider="true"/>'));
        }
      for (var d of ['#cellSelectStatic', '#cellSelectDynamic']) {
          dropdownFromJSON(d, ajax_response);
        }
      }
  );

  $("#loadButtonDynamic").click(function(){
    var txt = $('#textArea')[0].value;
    var stmts_promise = txtProcess(txt, parser).then(groundingMapper);
    var cyjs_promise = stmts_promise.then(assembleCyJS);
    var english_promise = stmts_promise.then(assembleEnglish)
    var english_promise;
    stmts_promise.then(function (model_response) {
      stmts = model_response;
    });
    cyjs_promise.then(function (model_response) {
      model_elements = model_response;
      drawCytoscape('cy_1', model_response);
      clearUploadInfo();
      qtipNodes(scapes['cy_1']);
      $('#menu').modal('hide');
      document.getElementById("loadContextButton").click();
    });
    english_promise.then(function (model_response) {
      sentences = model_response;
    })
  });

  $("#loadContextButton").click(function(){
    cell_line = $('#cellSelectDynamic').val().slice(6,-5);
    contextualizeNodesCCLE(cy, cell_line);
    $('#menu').modal('hide');
  });

  $("#downloadPySB").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assemblePySB).then(function (res) {
      download('model.py', res['model']);
    });
  });

  $("#downloadSBML").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleSBML).then(function (res) {
      download('model.sbml', res['model']);
    });
  });

  $("#downloadSBGN").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleSBGN).then(function (res) {
      download('model.sbgn', res['model']);
    });
  });

  $("#downloadKappa").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleKappa).then(function (res) {
      download('model.ka', res['model']);
    });
  });

  $("#downloadBNGL").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleBNGL).then(function (res) {
      download('model.bngl', res['model']);
    });
  });

  $("#downloadCX").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(assembleCX).then(function (res) {
      download('model.cx', res['model']);
    });
  });

  $("#NDEX_upload_btn").click(function(){
    var modal_body = $('.ndex-upload-container')[0]
    modal_body.innerHTML = null
    var par = document.createElement("p");
    par.textContent = 'Uploading model to NDEX...'
    modal_body.append(par)
    txt_input = $('#textArea')[0].value;
    shareNDEX(cyjs_elements, preset_pos, stmts, sentences, evidence, cell_line, mrna, mutations, txt_input, parser).then(function (res) {
      par.textContent = 'Network uploaded to NDEX.'
      var par2 = document.createElement("p");
      network_id = res['network_id']
      var network_address =  "http://ndexbio.org/#/network/" + network_id
      var temp_link = document.createElement("a");
      temp_link.href = network_address;
      temp_link.text = network_address;
      temp_link.target = '_blank';
      par2.append(temp_link);
      modal_body.append(par2);
    });
  });

  $("#loadNDEX").click(function(){
    var network_id = $("#ndexUUID")[0].value
    getNDEX(network_id).then(function (res) {
      model_elements = JSON.parse(res.model_elements)
      preset_pos = JSON.parse(res.preset_pos)
      stmts = JSON.parse(res.stmts)
      sentences = JSON.parse(res.sentences)
      evidence = JSON.parse(res.evidence)
      cell_line = res.cell_line
      $('#cellSelectDynamic').selectpicker()[0].value = 'model_' + cell_line + '.json'
      $('#cellSelectDynamic').selectpicker('refresh')
      mrna = JSON.parse(res.mrna)
      mutations = JSON.parse(res.mutations)
      txt_input = res.txt_input;
      $('#textArea').val(txt_input);
      parser = res.parser;
      $("#parseReach")[0].classList.remove('active')
      $("#parseTrips")[0].classList.remove('active')
      if (parser == 'trips'){
        $("#parseTrips").addClass("active");
      }
      else {
        $("#parseReach").addClass("active");
      }
      drawCytoscape ('cy_1', model_elements);
      clearUploadInfo();
      qtipNodes(scapes['cy_1']);
      scapes['cy_1'].fit();
      contextualizeNodesCCLEprebuilt(scapes['cy_1'], mrna, mutations)
      $('#ndexModal').modal('hide');
    });
  });

  $("#downloadINDRA").click(function(){
    var txt = $('#textArea')[0].value;
    txtProcess(txt, parser).then(groundingMapper).then(function (res) {
      download('stmts.json', JSON.stringify(res['statements'], null, 2));
    });
  });

  $("#downloadPNG").click(function(){
    var png_scale = 20;
    var cypng = scapes['cy_1'].png({scale: png_scale, output:'blob'});
    // console.log(cypng.length)
    while (cypng.length < 7) {
      png_scale -= 1;
      cypng = scapes['cy_1'].png({scale: png_scale, output:'blob'});
    }
    download('model.png', cypng);
  });

  $("#loopy").click(function(){
    var txt = $('#textArea')[0].value;

    txtProcess(txt, parser).then(groundingMapper).then(assembleLoopy).then(function (res) {

        window.open(
          res['loopy_url'].toString(),
          "_blank"
        );
    });
  });

$("#loadButtonStatic").click(function(){
  model_promise = grabJSON('static/models/' + prebuilt_model + '/model.json');
  preset_pos_promise = grabJSON('static/models/' + prebuilt_model + '/preset_pos.json');
  txt_input_promise = grabJSON('static/models/' + prebuilt_model + '/txt_input.json', dtype='text');
  var model_components_promise = Promise.all([model_promise, preset_pos_promise, txt_input_promise]);
  model_components_promise.then(function(promises){
    preset_pos = promises[1];
    model_elements = promises[0];
    txt_input = promises[2];
    drawCytoscape ('cy_1', model_elements);
    clearUploadInfo();
    qtipNodes(scapes['cy_1']);
    $('#textArea').val(txt_input);
    scapes['cy_1'].fit();
    document.getElementById("loadContextButton").click();
  })

});

$(".cyjs2loopy").click(function(){
  var model = loopyFromCyJS("cy_1");
  window.open(
    'http://ncase.me/loopy/v1/?data=' + model,
    "_blank"
  );
});

$(".presetLayout").click(function(){
  if (this.classList.contains("active")){
    $(".presetLayout").removeClass("active");
    preset_pos = {};
  }
  else {
    $(".presetLayout").addClass("active");
    preset_pos = preset_pos_static;
  }
});

$('a[href="#byom"]').click(function(){
  if (this.classList.contains("active") === false){
    preset_pos = {};
  }
});

$("#parseReach").click(function(){
  if (this.classList.contains("active")){
    $("#parseReach").removeClass("active");
    $("#parseTrips").addClass("active");
    parser='trips';
  }
  else {
    $("#parseReach").addClass("active");
    $("#parseTrips").removeClass("active");
    parser='reach';
  }
});

$("#parseTrips").click(function(){
  if (this.classList.contains("active")){
    $("#parseTrips").removeClass("active");
    $("#parseReach").addClass("active");
    parser='reach';
  }
  else {
    $("#parseTrips").addClass("active");
    $("#parseReach").removeClass("active");
    parser='trips';
  }
});

$('a[href="#ras227"]').click(function(){
  preset_pos = preset_pos_static;
});

// change prebuilt_model name every time the user changes dropdown
$('#model_picker').on('changed.bs.select', function(){
  prebuilt_model = $('#model_picker').selectpicker('val');
});

// change prebuilt_model name every time the user changes dropdown
$('.ctx-select').on('changed.bs.select', function(){
  var div_id = "#" + this.id;
  var val = $(div_id).selectpicker('val');
  current_ctx_selection[ctx_select_divs.indexOf(div_id)] = val;
  sub_select_array = array_multifilter(sub_select_array, current_ctx_selection);
  clearCtxtSelects();
  build_ctx_dropdowns(sub_select_array, ctx_select_divs, current_ctx_selection);
});

$("#reset_filter").click(function(){
  sub_select_array = select_array;
  current_ctx_selection = new Array(ctx_select_divs.length).fill("");
  clearCtxtSelects();
  build_ctx_dropdowns(sub_select_array, ctx_select_divs, current_ctx_selection);
  grabJSON('static/models/' + prebuilt_model + '/model.json').then(function (model_response) {
    model_elements = model_response;
    drawCytoscape ('cy_1', model_response);
    clearUploadInfo();
    qtipNodes(scapes['cy_1']);
  });
});

$("#load_context").click(function(){
  condition = current_ctx_selection.join('_');
  phosphoContextSN(scapes['cy_1'], ctxt, condition);
});

$('#path_table').on( 'click', 'tr', function () {
        if ( $(this).hasClass('selected') ) {
            $(this).removeClass('selected');
        }
        else {
            table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
            path_id = this.childNodes[5].innerText;
            highlightPath(scapes['cy_1'], path_uuids_dict[path_id]);
        }
    } );

$('.cy').each(function(){
  $('.cy')[0].setAttribute("style", "height: 100%;");
  // document.getElementById("loadButtonStatic").click();
  function resize() {
    $(".cy-container").height(win.innerHeight() - 250);
    $(".cy").height(win.innerHeight() - 250);
    if (scapes['cy_1']){
      scapes['cy_1'].center();
    }
  }

  var resizeTimer;
  $(window).on('resize', function(e) {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
      resize();
    }, 250);
  });
  setTimeout(resize, 0);
});

});// dom ready

function clearUploadInfo(){
  var modal_body = $('.ndex-upload-container')[0]
  modal_body.innerHTML = null
}
<|endoftext|>


<commit_before>/* In the Margins Side Panel Functions */
/* Based on https://github.com/AndreaLombardo/BootSideMenu */
function getSide(listClasses){
    var side;
    for (var i = 0; i<listClasses.length; i++) {
        if (listClasses[i]=='sidebar-left') {
            side = "left";
            break;
        } else if (listClasses[i]=='sidebar-right') {
            side = "right";
            break;
        } else {
            side = null;
        }
    }
    return side;
}

function doAnimation(container, containerWidth, sidebarSide, sidebarStatus) {
    var toggler = container.children()[1];
    if (sidebarStatus == "opened") {
        if (sidebarSide == "left") {
            container.animate({
                left: -(containerWidth+2)
            });
            toggleArrow("left");
        } else if (sidebarSide == "right") {
            container.animate({
                right: -(containerWidth +2)
            });
            toggleArrow("right");
        }
        container.attr('data-status', 'closed');
    } else {
        if (sidebarSide == "left") {
            container.animate({
                left:0
            });
            toggleArrow("right");
        } else if (sidebarSide == "right") {
            container.animate({
                right:0
            });
            toggleArrow("left");
        }
        container.attr('data-status', 'opened');
    }
}

function toggleArrow(side){
    if (side=="left") {
        $("#toggler").children(".glyphicon-chevron-right").css('display', 'block');
        $("#toggler").children(".glyphicon-chevron-left").css('display', 'none');
    } else if (side=="right") {
        $("#toggler").children(".glyphicon-chevron-left").css('display', 'block');
        $("#toggler").children(".glyphicon-chevron-right").css('display', 'none');
    }
}

/* In the Margins API Functions */
function callAPI(slug, type) {

    // No reason not to hard code this here since we only need the slug
    var url = "http://scalar.usc.edu/works/lexos/rdf/node/"+slug+"?rec=0&format=json";

    // Ajax call
    $.ajax({
        type:"GET",
        url:url,
        dataType:'jsonp',
        success: function(data){
            processData(data, type, url);
        },
        error: handleError
    });
}

function handleError(XMLHttpRequest, textStatus, errorThrown) {
    $('#status').html(textstatus+'"
"'+errorThrown).show();
}

function processData(data, type, url) {
    for (var nodeProp in data) {
        node = data[nodeProp]
        content_path = node['http://rdfs.org/sioc/ns#content'];
        if (node['http://purl.org/dc/terms/title'] != null) {
            var title = node['http://purl.org/dc/terms/title'][0].value;
            var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
        }
        if (node['http://simile.mit.edu/2003/10/ontologies/artstor#url'] != null) {
            var video_url = node['http://simile.mit.edu/2003/10/ontologies/artstor#url'][0].value;
            //var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
        }
        if (node['http://simile.mit.edu/2003/10/ontologies/artstor#url'] != null) {
            var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
        }
        if (content_path != null) {
            var content = content_path[0].value;
            content = content.replace(new RegExp('\r?\n\r?\n','g'), '

'); // Replace line breaks
        }
    }
    displayITMcontent(content, title, url, type, video_url);
}

function displayITMcontent(content, title, url, type, video_url) {
    // Fork here based on type
    switch (type) {
        case "panel":
        $("#panel-content").remove();
        titleLink = '
'+title+'
';
        $("#itm-content").append('
'+titleLink+content+'

');
        $("#panel-status").hide();
        break;

        case "dialog":
        titleLink = ''+title+'';
        $('#ITM-modal .modal-title').html(titleLink);
        msg = "
This is just a sample modal. Ultimately, it will open a settings dialog, but for now it can be used as a trigger to display In the Margins content. Click the Show Video button to see some sample video content.
";
        $('#ITM-modal .modal-body').empty();
        $('#ITM-modal .modal-body').append(msg);
        $('#ITM-modal .modal-body').append(content);
        $("#dialog-status").hide();
        break;

        // Works only with YouTube videos
        case "video-dialog":
        var youtube_url = video_url.replace("https://www.youtube.com/watch?v=", "https://www.youtube.com/embed/");
        titleLink = ''+title+'';
        $('#ITM-modal .modal-title').html(titleLink);
        msg = "
This is just a sample modal. Ultimately, it will open a settings dialog, but for now it can be used as a trigger to display In the Margins content. Click the Show Video button to see some sample video content.
";
        $('#ITM-modal .modal-body').empty();
        $('#ITM-modal .modal-body').html("");
        $('#ITM-modal .modal-body').append('');
        $("#dialog-status").hide();
        break;
    }
}

/* Document Ready Functions */
$(document).ready(function() {
    /* ITM Panel Setup */
    var container = $("#toggler").parent();
    var containerWidth = container.width();
    container.css({left:-(containerWidth+2)});
    container.attr('data-status', 'closed');

    /* ITM Panel Toggle Events */
    /* Note: This function currentl only works with side-panel toggle icon.
       To enable the use of other triggers, a class trigger should be used. */
    $('#toggler').click(function() {
        var container = $(this).parent();
        var listClasses = $(container[0]).attr('class').split(/\s+/); //IE9 Fix
        var side = getSide(listClasses);
        var containerWidth = container.width();
        var status = container.attr('data-status');
        var dataSlug = $("#ITMPanel-itm-content").attr('data-slug');
        var slug = (dataSlug == "") ? "index" : dataSlug;
        if(!status) {
            status = "opened";
        }
        doAnimation(container, containerWidth, side, status);
        if (status == "closed") {
            $("#panel-status").show();
            callAPI(slug, "panel");
        }
    });

    /* Populate a Bootstrap modal */
    $('#ITM-modal').on('show.bs.modal', function() {
        $("#dialog-status").show();
        callAPI("best-practices", "dialog");
    });

    /* Empty a Bootstrap modal */
    $('#ITM-modal').on('hide.bs.modal', function() {
        $('#ITM-modal').removeData('bs.modal');
        icon = $('#dialog-status').parent().html();
        $('#ITM-modal .modal-body').html("");
        $('#ITM-modal .modal-body').html(icon);
        $("#dialog-status").hide();
        callAPI("best-practices", "dialog");
    });

    /* Handle Show Video Button in Bootstrap Modal */
    $('#show-video').click(function() {
        callAPI("how-to-read-a-dendrogram", "video-dialog")
    });
});

/* Initialise Bootstrap Modal */
$('#ITM-modal').modal();
<commit_msg>Panel height recalculated on window resize<commit_after>/* In the Margins Side Panel Functions */
/* Based on https://github.com/AndreaLombardo/BootSideMenu */
function getSide(listClasses){
    var side;
    for (var i = 0; i<listClasses.length; i++) {
        if (listClasses[i]=='sidebar-left') {
            side = "left";
            break;
        } else if (listClasses[i]=='sidebar-right') {
            side = "right";
            break;
        } else {
            side = null;
        }
    }
    return side;
}

function doAnimation(container, containerWidth, sidebarSide, sidebarStatus) {
    var toggler = container.children()[1];
    if (sidebarStatus == "opened") {
        if (sidebarSide == "left") {
            container.animate({
                left: -(containerWidth+2)
            });
            toggleArrow("left");
        } else if (sidebarSide == "right") {
            container.animate({
                right: -(containerWidth +2)
            });
            toggleArrow("right");
        }
        container.attr('data-status', 'closed');
    } else {
        if (sidebarSide == "left") {
            container.animate({
                left:0
            });
            toggleArrow("right");
        } else if (sidebarSide == "right") {
            container.animate({
                right:0
            });
            toggleArrow("left");
        }
        container.attr('data-status', 'opened');
    }
}

function toggleArrow(side){
    if (side=="left") {
        $("#toggler").children(".glyphicon-chevron-right").css('display', 'block');
        $("#toggler").children(".glyphicon-chevron-left").css('display', 'none');
    } else if (side=="right") {
        $("#toggler").children(".glyphicon-chevron-left").css('display', 'block');
        $("#toggler").children(".glyphicon-chevron-right").css('display', 'none');
    }
}

/* In the Margins API Functions */
function callAPI(slug, type) {

    // No reason not to hard code this here since we only need the slug
    var url = "http://scalar.usc.edu/works/lexos/rdf/node/"+slug+"?rec=0&format=json";

    // Ajax call
    $.ajax({
        type:"GET",
        url:url,
        dataType:'jsonp',
        success: function(data){
            processData(data, type, url);
        },
        error: handleError
    });
}

function handleError(XMLHttpRequest, textStatus, errorThrown) {
    $('#status').html(textstatus+'"
"'+errorThrown).show();
}

function processData(data, type, url) {
    for (var nodeProp in data) {
        node = data[nodeProp]
        content_path = node['http://rdfs.org/sioc/ns#content'];
        if (node['http://purl.org/dc/terms/title'] != null) {
            var title = node['http://purl.org/dc/terms/title'][0].value;
            var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
        }
        if (node['http://simile.mit.edu/2003/10/ontologies/artstor#url'] != null) {
            var video_url = node['http://simile.mit.edu/2003/10/ontologies/artstor#url'][0].value;
            //var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
        }
        if (node['http://simile.mit.edu/2003/10/ontologies/artstor#url'] != null) {
            var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
        }
        if (content_path != null) {
            var content = content_path[0].value;
            content = content.replace(new RegExp('\r?\n\r?\n','g'), '

'); // Replace line breaks
        }
    }
    displayITMcontent(content, title, url, type, video_url);
}

function displayITMcontent(content, title, url, type, video_url) {
    // Fork here based on type
    switch (type) {
        case "panel":
        $("#panel-content").remove();
        titleLink = '
'+title+'
';
        $("#itm-content").append('
'+titleLink+content+'

');
        // Next two lines determine the panel height and change on window resize
        var height = $("#panel-content").visibleHeight()+"px";
        $("#panel-content").css("height", height);
        $("#panel-status").hide();
        break;

        case "dialog":
        titleLink = ''+title+'';
        $('#ITM-modal .modal-title').html(titleLink);
        msg = "
This is just a sample modal. Ultimately, it will open a settings dialog, but for now it can be used as a trigger to display In the Margins content. Click the Show Video button to see some sample video content.
";
        $('#ITM-modal .modal-body').empty();
        $('#ITM-modal .modal-body').append(msg);
        $('#ITM-modal .modal-body').append(content);
        $("#dialog-status").hide();
        break;

        // Works only with YouTube videos
        case "video-dialog":
        var youtube_url = video_url.replace("https://www.youtube.com/watch?v=", "https://www.youtube.com/embed/");
        titleLink = ''+title+'';
        $('#ITM-modal .modal-title').html(titleLink);
        msg = "
This is just a sample modal. Ultimately, it will open a settings dialog, but for now it can be used as a trigger to display In the Margins content. Click the Show Video button to see some sample video content.
";
        $('#ITM-modal .modal-body').empty();
        $('#ITM-modal .modal-body').html("");
        $('#ITM-modal .modal-body').append('');
        $("#dialog-status").hide();
        break;
    }
}

/* Gets the height of the viewport relative to a specified element.
   See http://stackoverflow.com/questions/24768795/get-the-visible-height-of-a-div-with-jquery */
$.fn.visibleHeight = function() {
    var elBottom, elTop, scrollBot, scrollTop, visibleBottom, visibleTop;
    scrollTop = $(window).scrollTop();
    scrollBot = scrollTop + $(window).height();
    elTop = this.offset().top;
    elBottom = elTop + this.outerHeight();
    visibleTop = elTop < scrollTop ? scrollTop : elTop;
    visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
    return visibleBottom - visibleTop
}

/* Document Ready Functions */
$(document).ready(function() {

    /* Get the viewport height after the window is resized */
    $(window).on('scroll resize', getVisible);

    /* ITM Panel Setup */
    var container = $("#toggler").parent();
    var containerWidth = container.width();
    container.css({left:-(containerWidth+2)});
    container.attr('data-status', 'closed');

    /* ITM Panel Toggle Events */
    /* Note: This function currentl only works with side-panel toggle icon.
       To enable the use of other triggers, a class trigger should be used. */
    $('#toggler').click(function() {
        var container = $(this).parent();
        var listClasses = $(container[0]).attr('class').split(/\s+/); //IE9 Fix
        var side = getSide(listClasses);
        var containerWidth = container.width();
        var status = container.attr('data-status');
        var dataSlug = $("#ITMPanel-itm-content").attr('data-slug');
        var slug = (dataSlug == "") ? "index" : dataSlug;
        if(!status) {
            status = "opened";
        }
        doAnimation(container, containerWidth, side, status);
        if (status == "closed") {
            $("#panel-status").show();
            callAPI(slug, "panel");
        }
    });

    /* Populate a Bootstrap modal */
    $('#ITM-modal').on('show.bs.modal', function() {
        $("#dialog-status").show();
        callAPI("best-practices", "dialog");
    });

    /* Empty a Bootstrap modal */
    $('#ITM-modal').on('hide.bs.modal', function() {
        $('#ITM-modal').removeData('bs.modal');
        icon = $('#dialog-status').parent().html();
        $('#ITM-modal .modal-body').html("");
        $('#ITM-modal .modal-body').html(icon);
        $("#dialog-status").hide();
        callAPI("best-practices", "dialog");
    });

    /* Handle Show Video Button in Bootstrap Modal */
    $('#show-video').click(function() {
        callAPI("how-to-read-a-dendrogram", "video-dialog")
    });
});

/* Initialise Bootstrap Modal */
$('#ITM-modal').modal();
<|endoftext|>


<commit_before>/*
 * Licensed under the Apache License, Version 2.0
 * See accompanying LICENSE file.
 */
'use strict';
angular.module('dashboard.apps.appmaster')

  .controller('AppDagCtrl', ['$scope', '$timeout', '$interval', '$filter', 'conf', 'dagStyle', function ($scope, $timeout, $interval, $filter, conf, dagStyle) {
    $scope.displayClock = $scope.app.clock;
    var localClock = moment();
    var updateClockPromise = $interval(function() {
      if (localClock.seconds() % 10 === 0) {
        // synchronize application clock every 10 second
        $scope.displayClock = $scope.app.clock;
      } else {
        $scope.displayClock += moment() - localClock;
      }
      localClock = moment();
    }, 1000);
    $scope.$on('$destroy', function() {
      $interval.cancel(updateClockPromise);
    });

    $scope.visgraph = {
      options: dagStyle.newOptions({depth: $scope.streamingDag.hierarchyDepth()}),
      data: dagStyle.newData(),
      events: {
        doubleClick: function (data) {
          if (data.nodes.length === 1) {
            $scope.switchToTaskTab(data.nodes[0]);
          }
        }
      }
    };

    $scope.updateVisGraphNodes = function () {
      var visNodes = $scope.visgraph.data.nodes;
      var data = $scope.streamingDag.getProcessorsData();
      data.weights[-1] = 0; // weight range from 0 to max weight
      var suggestRadius = _rangeMapper(data.weights, dagStyle.nodeRadiusRange());
      var diff = [];

      angular.forEach(data.processors, function (processor, key) {
        var processorId = parseInt(key);

        var label = '[' + processorId + '] ';
        label += processor.description ? processor.description : $filter('lastPart')(processor.taskClass);

        var weight = parseInt(data.weights[processorId]);
        var hierarchyLevels = data.hierarchyLevels[processorId];
        var visNode = visNodes.get(processorId);
        var newVisRadius = d3.round(suggestRadius(weight), 1);
        if (!visNode || visNode.label !== label || visNode.radius !== newVisRadius) {
          diff.push({
            id: processorId,
            label: label,
            level: hierarchyLevels,
            radius: newVisRadius
          });
        }
      });
      visNodes.update(diff);
    };

    $scope.updateVisGraphEdges = function () {
      var visEdges = $scope.visgraph.data.edges;
      var data = $scope.streamingDag.getEdgesData();
      data.bandwidths[-1] = 0; // bandwidth range from 0 to max bandwidth
      var suggestWidth = _rangeMapper(data.bandwidths, dagStyle.edgeWidthRange());
      var suggestArrowSize = _rangeMapper(data.bandwidths, dagStyle.edgeArrowSizeRange());
      var suggestOpacity = _rangeMapper(data.bandwidths, dagStyle.edgeOpacityRange());
      var diff = [];

      angular.forEach(data.edges, function (edge, edgeId) {
        var bandwidth = parseInt(data.bandwidths[edgeId]);
        var visEdge = visEdges.get(edgeId);
        var newVisWidth = d3.round(suggestWidth(bandwidth), 1);
        if (!visEdge || visEdge.width !== newVisWidth) {
          diff.push({
            id: edgeId, from: edge.source, to: edge.target,
            width: newVisWidth,
            hoverWidth: newVisWidth,
            arrowScaleFactor: d3.round(suggestArrowSize(bandwidth), 1),
            opacity: d3.round(suggestOpacity(bandwidth), 1),
            color: dagStyle.edgeColorSet(bandwidth > 0)
          });
        }
      });
      visEdges.update(diff);
    };

    $scope.updateMetricsCounter = function () {
      $scope.receivedMessages = $scope.streamingDag.getReceivedMessages();
      $scope.sentMessages = $scope.streamingDag.getSentMessages();
      $scope.processingTime = $scope.streamingDag.getProcessingTime();
      $scope.receiveLatency = $scope.streamingDag.getReceiveLatency();
    };

    var timeoutPromise;
    $scope.$on('$destroy', function () {
      $timeout.cancel(timeoutPromise);
    });

    /** Redraw VisGraph on demand */
    var redrawVisGraph = function () {
      $scope.updateVisGraphNodes();
      $scope.updateVisGraphEdges();
      $scope.updateMetricsCounter();
      timeoutPromise = $timeout(redrawVisGraph, conf.updateVisDagInterval);
    };
    redrawVisGraph();

    function _rangeMapper(dict, range) {
      var values = d3.values(dict);
      return d3.scale.linear().domain(d3.extent(values)).range(range);
    }
  }])
;
<commit_msg>fix #907: calculate application clock update frequence for a 30 second time frame<commit_after>/*
 * Licensed under the Apache License, Version 2.0
 * See accompanying LICENSE file.
 */
'use strict';
angular.module('dashboard.apps.appmaster')

  .controller('AppDagCtrl', ['$scope', '$timeout', '$interval', '$filter', 'conf', 'dagStyle', function ($scope, $timeout, $interval, $filter, conf, dagStyle) {
    var updateClockPromise = null;
    $scope.$on('$destroy', function() {
      $interval.cancel(updateClockPromise);
    });

    var detectPeriod = 15;
    var previousDetectPoint = {appClock: $scope.app.clock, local: moment()};
    var appClockRate = 0;
    $scope.$watch('app.clock', function(nowAppClock) {
      var nowLocal = moment();
      if (nowLocal - previousDetectPoint.local > detectPeriod * 1000) {
        $interval.cancel(updateClockPromise);
        if (nowAppClock - previousDetectPoint.appClock > 0) {
          var clockDelta = nowAppClock - $scope.displayClock;
          appClockRate = 1000 * (nowLocal - previousDetectPoint.local) /
            (nowAppClock  - previousDetectPoint.appClock + clockDelta);
          updateClockPromise = $interval(function () {
            $scope.displayClock += 1000;
          }, appClockRate);
        }
        previousDetectPoint = {appClock: nowAppClock, local: nowLocal};
      } else if (updateClockPromise === null) {
        $scope.displayClock = $scope.app.clock;
      }
    });

    $scope.visgraph = {
      options: dagStyle.newOptions({depth: $scope.streamingDag.hierarchyDepth()}),
      data: dagStyle.newData(),
      events: {
        doubleClick: function (data) {
          if (data.nodes.length === 1) {
            $scope.switchToTaskTab(data.nodes[0]);
          }
        }
      }
    };

    $scope.updateVisGraphNodes = function () {
      var visNodes = $scope.visgraph.data.nodes;
      var data = $scope.streamingDag.getProcessorsData();
      data.weights[-1] = 0; // weight range from 0 to max weight
      var suggestRadius = _rangeMapper(data.weights, dagStyle.nodeRadiusRange());
      var diff = [];

      angular.forEach(data.processors, function (processor, key) {
        var processorId = parseInt(key);

        var label = '[' + processorId + '] ';
        label += processor.description ? processor.description : $filter('lastPart')(processor.taskClass);

        var weight = parseInt(data.weights[processorId]);
        var hierarchyLevels = data.hierarchyLevels[processorId];
        var visNode = visNodes.get(processorId);
        var newVisRadius = d3.round(suggestRadius(weight), 1);
        if (!visNode || visNode.label !== label || visNode.radius !== newVisRadius) {
          diff.push({
            id: processorId,
            label: label,
            level: hierarchyLevels,
            radius: newVisRadius
          });
        }
      });
      visNodes.update(diff);
    };

    $scope.updateVisGraphEdges = function () {
      var visEdges = $scope.visgraph.data.edges;
      var data = $scope.streamingDag.getEdgesData();
      data.bandwidths[-1] = 0; // bandwidth range from 0 to max bandwidth
      var suggestWidth = _rangeMapper(data.bandwidths, dagStyle.edgeWidthRange());
      var suggestArrowSize = _rangeMapper(data.bandwidths, dagStyle.edgeArrowSizeRange());
      var suggestOpacity = _rangeMapper(data.bandwidths, dagStyle.edgeOpacityRange());
      var diff = [];

      angular.forEach(data.edges, function (edge, edgeId) {
        var bandwidth = parseInt(data.bandwidths[edgeId]);
        var visEdge = visEdges.get(edgeId);
        var newVisWidth = d3.round(suggestWidth(bandwidth), 1);
        if (!visEdge || visEdge.width !== newVisWidth) {
          diff.push({
            id: edgeId, from: edge.source, to: edge.target,
            width: newVisWidth,
            hoverWidth: newVisWidth,
            arrowScaleFactor: d3.round(suggestArrowSize(bandwidth), 1),
            opacity: d3.round(suggestOpacity(bandwidth), 1),
            color: dagStyle.edgeColorSet(bandwidth > 0)
          });
        }
      });
      visEdges.update(diff);
    };

    $scope.updateMetricsCounter = function () {
      $scope.receivedMessages = $scope.streamingDag.getReceivedMessages();
      $scope.sentMessages = $scope.streamingDag.getSentMessages();
      $scope.processingTime = $scope.streamingDag.getProcessingTime();
      $scope.receiveLatency = $scope.streamingDag.getReceiveLatency();
    };

    var timeoutPromise;
    $scope.$on('$destroy', function () {
      $timeout.cancel(timeoutPromise);
    });

    /** Redraw VisGraph on demand */
    var redrawVisGraph = function () {
      $scope.updateVisGraphNodes();
      $scope.updateVisGraphEdges();
      $scope.updateMetricsCounter();
      timeoutPromise = $timeout(redrawVisGraph, conf.updateVisDagInterval);
    };
    redrawVisGraph();

    function _rangeMapper(dict, range) {
      var values = d3.values(dict);
      return d3.scale.linear().domain(d3.extent(values)).range(range);
    }
  }])
;
<|endoftext|>


<commit_before>var CleanCSS = require('clean-css');
var fs = require('fs');
var path = require('path');

function escape(source) {
  return source
    .replace(/(["\\])/g, '\\$1')
    .replace(/[\f]/g, "\\f")
    .replace(/[\b]/g, "\\b")
    .replace(/[\n]/g, "\\n")
    .replace(/[\t]/g, "\\t")
    .replace(/[\r]/g, "\\r")
    .replace(/[\u2028]/g, "\\u2028")
    .replace(/[\u2029]/g, "\\u2029");
}

var cssInject = "(function(c){var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));})";

module.exports = function bundle(loads, opts) {

  var loader = this;

  var stubDefines = loads.map(function(load) {
    return "System\.register('" + load.name + "', [], false, function() {});";
  }).join('\n');

  var cssOutput = loads.map(function(load) {

    var cssFile = load.address.substring('file:'.length),
      root = (loader.rootURL || loader.baseURL).substring('file:'.length);

    return new CleanCSS({
      target: this.separateCSS ? opts.outFile : '.',
      relativeTo: path.dirname(cssFile),
      root: root
    }).minify(load.source).styles;
  }).reduce(function(s1, s2) {
    return s1 + s2;
  }, '');

  // write a separate CSS file if necessary
  if (this.separateCSS) {
    fs.writeFileSync(opts.outFile.replace(/\.js$/, '.css'), cssOutput);
    return stubDefines;
  }

  return [stubDefines, cssInject, '("' + escape(cssOutput) + '");'].join('\n');
}<commit_msg>fix(relative-paths): fix to allow url rebasing to use relative paths<commit_after>var CleanCSS = require('clean-css');
var fs = require('fs');
var path = require('path');

function escape(source) {
  return source
    .replace(/(["\\])/g, '\\$1')
    .replace(/[\f]/g, "\\f")
    .replace(/[\b]/g, "\\b")
    .replace(/[\n]/g, "\\n")
    .replace(/[\t]/g, "\\t")
    .replace(/[\r]/g, "\\r")
    .replace(/[\u2028]/g, "\\u2028")
    .replace(/[\u2029]/g, "\\u2029");
}

var cssInject = "(function(c){var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));})";

module.exports = function bundle(loads, opts) {

  var loader = this;

  var stubDefines = loads.map(function(load) {
    return "System\.register('" + load.name + "', [], false, function() {});";
  }).join('\n');

  var cssOutput = loads.map(function(load) {

    var cssFile = load.address.substring('file:'.length),
      root = (loader.rootURL || loader.baseURL).substring('file:'.length);

    return new CleanCSS({
      target: loader.separateCSS ? opts.outFile : '.',
      relativeTo: path.dirname(cssFile),
      root: loader.separateCSS ? undefined : root
    }).minify(load.source).styles;
  }).reduce(function(s1, s2) {
    return s1 + s2;
  }, '');

  // write a separate CSS file if necessary
  if (loader.separateCSS) {
    fs.writeFileSync(opts.outFile.replace(/\.js$/, '.css'), cssOutput);
    return stubDefines;
  }

  return [stubDefines, cssInject, '("' + escape(cssOutput) + '");'].join('\n');
}
<|endoftext|>