<commit_before>/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Dashboard plugin.
 * This plugin is not yet released, but should be when it will be finished.
 *
 * copyright (c) 2010 David Jean Louis <izimobil@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

(function($) {

    $.fn.extend({
        //pass the options variable to the function
        dashboard: function(options) {
            //Set the default values, use comma to separate the settings, example:
            var defaults = {
                panel_id: 'dashboard-panel',
                dashboard_id: this.attr('id'),
                dashboard_module_class: 'dashboard-module',
                columns: 2,
                load_preferences_function: false,
                save_preferences_function: false
            }
            var options = $.extend(defaults, options);

            return this.each(function() {
                // set ids for dashboard modules
                _initialize($(this), options);
                // restore positions, must be done *before* columnize
                _restore_positions($(this), options);
                // columnize the dashboard modules
                _columnize($(this), options);
                // add draggable behaviour
                _set_draggable($(this), options);
                // add collapsible behaviour
                _set_collapsible($(this), options);
                // add deletable behaviour
                _set_deletable($(this), options);
                // add addable behaviour to dashboard panel items
                _set_addable($(this), options);
                // restore user preferences
                _restore_preferences($(this), options);
            });
        }
    });

    var preferences = false;

    var _initialize = function(elt, options) {
        // load preferences
        if (preferences === false) {
            if (options.load_preferences_function) {
                preferences = options.load_preferences_function(options);
            } else {
                var json_str = $.cookie('admin-tools.' + options.dashboard_id);
                preferences = json_str ? JSON.parse(json_str) : {};
            }
        }
        // set ids if not set
        elt.children('div[id!=' + options.panel_id +']').each(function(index) {
            if (!$(this).attr('id')) {
                $(this).attr('id', 'module_' + index);
            }
        });
    };

    var _restore_positions = function(elt, options) {
        // restore positions
        try {
            var saved_positions = _get_preference(options, 'positions');
        } catch (e) {
            return;
        }
        var current_positions = _get_positions(elt, options);
        var new_positions = [];

        for(var v = 0; v < current_positions.length; v++) {
            new_positions[current_positions[v]] = current_positions[v];
        }

        for(var i = 0; i < saved_positions.length; i++) {
            // item id from saved order
            var id = saved_positions[i];
            if (id in new_positions) {
                var item = new_positions[id];
                var child = elt.children('#'+item);
                // select the item according to the saved order
                var saved = elt.children('#'+item);
                child.remove();
                elt.append(saved);
            }
        }
    };

    var _columnize = function(elt, options) {
        var elts = elt.children('div[id!=' + options.panel_id +']');
        var size = Math.ceil(elts.length / options.columns);
        var sizes = _get_preference(options, 'columns');
        var percent = Math.floor(100 / options.columns);
        var start = 0;
        var stop = 0;
        for (i = 0; i < options.columns; i++) {
            if (!sizes[i]) {
                start = i * size;
                stop  = start + size;
            } else {
                start = (i == 0) ? 0 : sizes[i-1];
                stop  = start + sizes[i];
            }
            elts.slice(start, stop).wrapAll(
                '
'
            );
        }
    };

    var _restore_preferences = function(elt, options) {
        elt.children().children('.disabled').each(function() {
            _delete_element($(this), options);
        });
        if (_get_preference(options, 'disabled')) {
            $.each(_get_preference(options, 'disabled'), function(k, v) {
                v ? _delete_element($('#'+k), options) : _add_element($('#'+k), options);
            });
        }
        if (_get_preference(options, 'collapsed')) {
            $.each(_get_preference(options, 'collapsed'), function(k, v) {
                if (v) {
                    _toggle_element($('#'+k), options);
                }
            });
        }
        // if there's no element in the panel, hide it
        if (!$('#' + options.panel_id).find('li').length) {
            $('#' + options.panel_id).hide();
        }
    };

    var _set_draggable = function(elt, options) {
        // the dashboard column
        elt.children('.dashboard-column').sortable({
            handle: 'h2',
            items: '.draggable',
            connectWith: '.dashboard-column',
            placeholder: 'dashboard-placeholder',
            forcePlaceholderSize: true,
            cursor: 'crosshair',
            opacity: 0.7,
            update: function() {
                _set_preference(options, 'positions', false, _get_positions(elt, options));
                var columns = [];
                elt.children('.dashboard-column').each(function() {
                    columns.push($(this).children().length);
                });
                _set_preference(options, 'columns', false, columns, true);
            }
        });
    };

    var _set_collapsible = function(elt, options) {
        elt.find('> .dashboard-column > .collapsible > h2').each(function() {
            $(this).append('Toggle').find('a.toggle-icon').click(function() {
                var prnt = $(this).parent().parent();
                _toggle_element(prnt, options, true);
            });
        });
    };

    var _toggle_element = function(elt, options, save_preference) {
        elt.find('h2 a.toggle-icon').toggleClass('collapsed');
        elt.children('div').slideToggle();
        if (save_preference) {
            _set_preference(options, 'collapsed', elt.attr('id'), elt.find('h2 a.toggle-icon').hasClass('collapsed'), true);
        }
    };

    var _set_deletable = function(elt, options) {
        elt.find('> .dashboard-column > .deletable > h2').each(function() {
            $(this).append('Close').find('a.close-icon').click(function() {
                var prnt = $(this).parent().parent();
                _delete_element(prnt, options, true);
            });
        });
    };

    var _delete_element = function(elt, options, save_preference) {
        var existing = $('#'+options.panel_id).find('li a[rel='+elt.attr('id')+']');
        if (!existing.length) {
            var panel_ul = $('#' + options.panel_id).find('ul');
            if (!panel_ul.length) {
                $('#' + options.panel_id).append('
');
                panel_ul = $('#' + options.panel_id).find('ul');
            }
            panel_ul.append(
                '
'
                + elt.find('h2').contents().first().text()
                + '
'
            );
            _set_addable(elt, options, $('#'+options.panel_id).find('li a[rel='+elt.attr('id')+']'));
        } else {
            existing.parent().show();
        }
        elt.fadeOut('fast');
        $('#' + options.panel_id).show();
        if (save_preference) {
            _set_preference(options, 'disabled', elt.attr('id'), true, true);
        }
    };

    var _set_addable = function(elt, options, elts) {
        if (!elts) {
            elts = $('#'+options.panel_id).find('li a');
        }
        elts.click(function() {
            _add_element($('#'+$(this).attr('rel')), options, true);
        });
    };

    var _add_element = function(elt, options, save_preference) {
        panel_elt = $('#'+options.panel_id).find('li a[rel='+elt.attr('id')+']');
        panel_elt.parent().remove();
        elt.removeClass('disabled');
        elt.fadeIn('fast');
        if (save_preference) {
            _set_preference(options, 'disabled', elt.attr('id'), false, true);
        }
        // if there's no element in the panel, hide it
        if (!$('#' + options.panel_id).find('li').length) {
            $('#' + options.panel_id).hide();
        }
    };

    var load_preferences = function(options) {
        if (options.load_preferences_function) {
            return options.load_preferences_function(options);
        }
        if (preferences === false) {
            var json_str = $.cookie('admin-tools.' + options.dashboard_id);
            preferences = json_str ? JSON.parse(json_str) : {};
        }
        return preferences;
    }

    var _get_preference = function(options, cat, id, defaultval) {
        try {
            if (preferences[cat] == undefined) {
                preferences[cat] = {};
            }
            if (id) {
                return preferences[cat][id];
            }
            return preferences[cat];
        } catch (e) {
            return defaultval ? defaultval : null;
        }
    };

    // quick hack to ensure that we do not save preferences if they are
    // not modified...
    var last_saved_preferences = null;

    var _set_preference = function(options, cat, id, val, save) {
        try {
            if (preferences[cat] == undefined) {
                preferences[cat] = {};
            }
            if (id) {
                preferences[cat][id] = val;
            } else {
                preferences[cat] = val;
            }
        } catch (e) {
        }
        // save preferences
        if (save && JSON.stringify(preferences) != last_saved_preferences) {
            if (options.save_preferences_function) {
                options.save_preferences_function(options, preferences);
            } else {
                $.cookie(cookie_name, JSON.stringify(preferences), {expires: 1825});
            }
            last_saved_preferences = JSON.stringify(preferences);
        }
    };

    var _get_positions = function(elt, options) {
        var modules = [];
        if (!elt.children('.dashboard-column').length) {
            elt.children('div[id!=' + options.panel_id +']').each(function() {
                modules.push($(this).attr('id'));
            });
        } else {
            elt.children('.dashboard-column').each(function() {
                $.each($(this).sortable('toArray'), function(index, item) {
                    modules.push(item);
                });
            });
        }
        return modules;
    }

})(jQuery);
<commit_msg>Fixed issue when all modules are in one columns and the page is reloaded.<commit_after>/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Dashboard plugin.
 * This plugin is not yet released, but should be when it will be finished.
 *
 * copyright (c) 2010 David Jean Louis <izimobil@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

(function($) {

    $.fn.extend({
        //pass the options variable to the function
        dashboard: function(options) {
            //Set the default values, use comma to separate the settings, example:
            var defaults = {
                panel_id: 'dashboard-panel',
                dashboard_id: this.attr('id'),
                dashboard_module_class: 'dashboard-module',
                columns: 2,
                load_preferences_function: false,
                save_preferences_function: false
            }
            var options = $.extend(defaults, options);

            return this.each(function() {
                // set ids for dashboard modules
                _initialize($(this), options);
                // restore positions, must be done *before* columnize
                _restore_positions($(this), options);
                // columnize the dashboard modules
                _columnize($(this), options);
                // add draggable behaviour
                _set_draggable($(this), options);
                // add collapsible behaviour
                _set_collapsible($(this), options);
                // add deletable behaviour
                _set_deletable($(this), options);
                // add addable behaviour to dashboard panel items
                _set_addable($(this), options);
                // restore user preferences
                _restore_preferences($(this), options);
            });
        }
    });

    var preferences = false;

    var _initialize = function(elt, options) {
        // load preferences
        if (preferences === false) {
            if (options.load_preferences_function) {
                preferences = options.load_preferences_function(options);
            } else {
                var json_str = $.cookie('admin-tools.' + options.dashboard_id);
                preferences = json_str ? JSON.parse(json_str) : {};
            }
        }
        // set ids if not set
        elt.children('div[id!=' + options.panel_id +']').each(function(index) {
            if (!$(this).attr('id')) {
                $(this).attr('id', 'module_' + index);
            }
        });
    };

    var _restore_positions = function(elt, options) {
        // restore positions
        try {
            var saved_positions = _get_preference(options, 'positions');
        } catch (e) {
            return;
        }
        var current_positions = _get_positions(elt, options);
        var new_positions = [];

        for(var v = 0; v < current_positions.length; v++) {
            new_positions[current_positions[v]] = current_positions[v];
        }

        for(var i = 0; i < saved_positions.length; i++) {
            // item id from saved order
            var id = saved_positions[i];
            if (id in new_positions) {
                var item = new_positions[id];
                var child = elt.children('#'+item);
                // select the item according to the saved order
                var saved = elt.children('#'+item);
                child.remove();
                elt.append(saved);
            }
        }
    };

    var _columnize = function(elt, options) {
        var elts = elt.children('div[id!=' + options.panel_id +']');
        var size = Math.ceil(elts.length / options.columns);
        var sizes = _get_preference(options, 'columns');
        var percent = Math.floor(100 / options.columns);
        var start = 0;
        var stop = 0;
        for (i = 0; i < options.columns; i++) {
            if (typeof(sizes[i]) == 'undefined') {
                start = i * size;
                stop  = start + size;
            } else if (sizes[i] == 0) {
                elt.append(
                    '
'
                );
                continue;
            } else {
                start = (i == 0) ? 0 : sizes[i-1];
                stop  = start + sizes[i];
            }
            elts.slice(start, stop).wrapAll(
                '
'
            );
        }
    };

    var _restore_preferences = function(elt, options) {
        elt.children().children('.disabled').each(function() {
            _delete_element($(this), options);
        });
        if (_get_preference(options, 'disabled')) {
            $.each(_get_preference(options, 'disabled'), function(k, v) {
                v ? _delete_element($('#'+k), options) : _add_element($('#'+k), options);
            });
        }
        if (_get_preference(options, 'collapsed')) {
            $.each(_get_preference(options, 'collapsed'), function(k, v) {
                if (v) {
                    _toggle_element($('#'+k), options);
                }
            });
        }
        // if there's no element in the panel, hide it
        if (!$('#' + options.panel_id).find('li').length) {
            $('#' + options.panel_id).hide();
        }
    };

    var _set_draggable = function(elt, options) {
        // the dashboard column
        elt.children('.dashboard-column').sortable({
            handle: 'h2',
            items: '.draggable',
            connectWith: '.dashboard-column',
            placeholder: 'dashboard-placeholder',
            forcePlaceholderSize: true,
            cursor: 'crosshair',
            opacity: 0.7,
            update: function() {
                _set_preference(options, 'positions', false, _get_positions(elt, options));
                var columns = [];
                elt.children('.dashboard-column').each(function() {
                    columns.push($(this).children().length);
                });
                _set_preference(options, 'columns', false, columns, true);
            }
        });
    };

    var _set_collapsible = function(elt, options) {
        elt.find('> .dashboard-column > .collapsible > h2').each(function() {
            $(this).append('Toggle').find('a.toggle-icon').click(function() {
                var prnt = $(this).parent().parent();
                _toggle_element(prnt, options, true);
            });
        });
    };

    var _toggle_element = function(elt, options, save_preference) {
        elt.find('h2 a.toggle-icon').toggleClass('collapsed');
        elt.children('div').slideToggle();
        if (save_preference) {
            _set_preference(options, 'collapsed', elt.attr('id'), elt.find('h2 a.toggle-icon').hasClass('collapsed'), true);
        }
    };

    var _set_deletable = function(elt, options) {
        elt.find('> .dashboard-column > .deletable > h2').each(function() {
            $(this).append('Close').find('a.close-icon').click(function() {
                var prnt = $(this).parent().parent();
                _delete_element(prnt, options, true);
            });
        });
    };

    var _delete_element = function(elt, options, save_preference) {
        var existing = $('#'+options.panel_id).find('li a[rel='+elt.attr('id')+']');
        if (!existing.length) {
            var panel_ul = $('#' + options.panel_id).find('ul');
            if (!panel_ul.length) {
                $('#' + options.panel_id).append('
');
                panel_ul = $('#' + options.panel_id).find('ul');
            }
            panel_ul.append(
                '
'
                + elt.find('h2').contents().first().text()
                + '
'
            );
            _set_addable(elt, options, $('#'+options.panel_id).find('li a[rel='+elt.attr('id')+']'));
        } else {
            existing.parent().show();
        }
        elt.fadeOut('fast');
        $('#' + options.panel_id).show();
        if (save_preference) {
            _set_preference(options, 'disabled', elt.attr('id'), true, true);
        }
    };

    var _set_addable = function(elt, options, elts) {
        if (!elts) {
            elts = $('#'+options.panel_id).find('li a');
        }
        elts.click(function() {
            _add_element($('#'+$(this).attr('rel')), options, true);
        });
    };

    var _add_element = function(elt, options, save_preference) {
        panel_elt = $('#'+options.panel_id).find('li a[rel='+elt.attr('id')+']');
        panel_elt.parent().remove();
        elt.removeClass('disabled');
        elt.fadeIn('fast');
        if (save_preference) {
            _set_preference(options, 'disabled', elt.attr('id'), false, true);
        }
        // if there's no element in the panel, hide it
        if (!$('#' + options.panel_id).find('li').length) {
            $('#' + options.panel_id).hide();
        }
    };

    var load_preferences = function(options) {
        if (options.load_preferences_function) {
            return options.load_preferences_function(options);
        }
        if (preferences === false) {
            var json_str = $.cookie('admin-tools.' + options.dashboard_id);
            preferences = json_str ? JSON.parse(json_str) : {};
        }
        return preferences;
    }

    var _get_preference = function(options, cat, id, defaultval) {
        try {
            if (preferences[cat] == undefined) {
                preferences[cat] = {};
            }
            if (id) {
                return preferences[cat][id];
            }
            return preferences[cat];
        } catch (e) {
            return defaultval ? defaultval : null;
        }
    };

    // quick hack to ensure that we do not save preferences if they are
    // not modified...
    var last_saved_preferences = null;

    var _set_preference = function(options, cat, id, val, save) {
        try {
            if (preferences[cat] == undefined) {
                preferences[cat] = {};
            }
            if (id) {
                preferences[cat][id] = val;
            } else {
                preferences[cat] = val;
            }
        } catch (e) {
        }
        // save preferences
        if (save && JSON.stringify(preferences) != last_saved_preferences) {
            if (options.save_preferences_function) {
                options.save_preferences_function(options, preferences);
            } else {
                $.cookie(cookie_name, JSON.stringify(preferences), {expires: 1825});
            }
            last_saved_preferences = JSON.stringify(preferences);
        }
    };

    var _get_positions = function(elt, options) {
        var modules = [];
        if (!elt.children('.dashboard-column').length) {
            elt.children('div[id!=' + options.panel_id +']').each(function() {
                modules.push($(this).attr('id'));
            });
        } else {
            elt.children('.dashboard-column').each(function() {
                $.each($(this).sortable('toArray'), function(index, item) {
                    modules.push(item);
                });
            });
        }
        return modules;
    }

})(jQuery);
<|endoftext|>


<commit_before>/**
 * Created by ingrskar on 3/8/2017.
 */
import React from "react"
import { connect } from "react-redux"
import { bindActionCreators } from 'redux';
import {Thumbnail, Glyphicon} from 'react-bootstrap';
import ActivityModal from '../ActivityModal';

import {getMonth, getDay} from '../DateFunctions';

class ActivityPageContainer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            show: false,
        }
    }

    componentWillMount() {
        this.showMap = this.showMap.bind(this);
        //console.log('mount from ActivityPageContainer');
    }

    // <ActivityModal id={activity.id} show={activity.show}>test</ActivityModal> <-- add between </div< and </Thumbnail>

    createActivityItem(){
        let poster = null;
        return (

                <Thumbnail
                    className="activityBigStyle"
                    src={poster}
                    onClick={this.openActivityModal.bind(this)}
                    title="Klikk på aktiviteten for mer informasjon"
                >

{this.props.activity.title}

<Glyphicon glyph="glyphicon glyphicon-calendar"/>

<Glyphicon glyph="glyphicon glyphicon-time"/>

<Glyphicon glyph="glyphicon glyphicon-map-marker"/>

{this.props.activity.date.getDate()}. {getMonth(this.props.activity.date.getMonth())}

{this.props.activity.time_start} - {this.props.activity.time_end}

{this.props.activity.location}

{this.props.activity.description}

                    <ActivityModal id={this.props.activity.id} show={this.state.show}>test</ActivityModal>
                </Thumbnail>

        );
    };

    render() {
        // if (this.state.images.length > 0 && this.state.images[0] != "") {
        //     poster = "/media/" + this.state.images[0];
        // }
        return (

                {this.createActivityItem()}

        );
    }

    showMap() {
        window.open('https://www.google.no/maps/place/' + this.state.location, '_blank');
    }

    openActivityModal() {
       this.setState({show:true})
    }
}

// connect actually calles the functions so that their purposes are fulfilled
export default ActivityPageContainer;
<commit_msg>removed comment<commit_after>/**
 * Created by ingrskar on 3/8/2017.
 */
import React from "react"
import { connect } from "react-redux"
import { bindActionCreators } from 'redux';
import {Thumbnail, Glyphicon} from 'react-bootstrap';
import ActivityModal from '../ActivityModal';

import {getMonth, getDay} from '../DateFunctions';

class ActivityPageContainer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            show: false,
        }
    }

    componentWillMount() {
        this.showMap = this.showMap.bind(this);
        //console.log('mount from ActivityPageContainer');
    }

    createActivityItem(){
        let poster = null;
        return (

                <Thumbnail
                    className="activityBigStyle"
                    src={poster}
                    onClick={this.openActivityModal.bind(this)}
                    title="Klikk på aktiviteten for mer informasjon"
                >

{this.props.activity.title}

<Glyphicon glyph="glyphicon glyphicon-calendar"/>

<Glyphicon glyph="glyphicon glyphicon-time"/>

<Glyphicon glyph="glyphicon glyphicon-map-marker"/>

{this.props.activity.date.getDate()}. {getMonth(this.props.activity.date.getMonth())}

{this.props.activity.time_start} - {this.props.activity.time_end}

{this.props.activity.location}

{this.props.activity.description}

                    <ActivityModal id={this.props.activity.id} show={this.state.show}>test</ActivityModal>
                </Thumbnail>

        );
    };

    render() {
        // if (this.state.images.length > 0 && this.state.images[0] != "") {
        //     poster = "/media/" + this.state.images[0];
        // }
        return (

                {this.createActivityItem()}

        );
    }

    showMap() {
        window.open('https://www.google.no/maps/place/' + this.state.location, '_blank');
    }

    openActivityModal() {
       this.setState({show:true})
    }
}

// connect actually calles the functions so that their purposes are fulfilled
export default ActivityPageContainer;
<|endoftext|>


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

/**
 * Internal dependencies
 */
import Modules from 'googlesitekit-modules';
import { isFeatureEnabled } from '../../../features';
import { MODULES_ANALYTICS } from './constants';
import {
	rollbackChanges,
	submitChanges,
	validateCanSubmitChanges,
} from './settings';

const baseModuleStore = Modules.createModuleStore( 'analytics', {
	storeName: MODULES_ANALYTICS,
	settingSlugs: [
		'accountID',
		'adsConversionID',
		'anonymizeIP',
		'canUseSnippet',
		'internalWebPropertyID',
		'ownerID',
		'profileID',
		'propertyID',
		'trackingDisabled',
		'useSnippet',
	],
	adminPage: isFeatureEnabled( 'unifiedDashboard' )
		? undefined
		: 'googlesitekit-module-analytics',
	submitChanges,
	rollbackChanges,
	validateCanSubmitChanges,
} );

export default baseModuleStore;
<commit_msg>Reimplement getCanUseSnippet of the analytics module.<commit_after>/**
 * `modules/analytics` base data store
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import Modules from 'googlesitekit-modules';
import { isFeatureEnabled } from '../../../features';
import { CORE_MODULES } from '../../../googlesitekit/modules/datastore/constants';
import { MODULES_TAGMANAGER } from '../../tagmanager/datastore/constants';
import { isValidPropertyID } from '../util';
import { MODULES_ANALYTICS } from './constants';
import {
	rollbackChanges,
	submitChanges,
	validateCanSubmitChanges,
} from './settings';

const { createRegistrySelector } = Data;

let baseModuleStore = Modules.createModuleStore( 'analytics', {
	storeName: MODULES_ANALYTICS,
	settingSlugs: [
		'accountID',
		'adsConversionID',
		'anonymizeIP',
		'canUseSnippet',
		'internalWebPropertyID',
		'ownerID',
		'profileID',
		'propertyID',
		'trackingDisabled',
		'useSnippet',
	],
	adminPage: isFeatureEnabled( 'unifiedDashboard' )
		? undefined
		: 'googlesitekit-module-analytics',
	submitChanges,
	rollbackChanges,
	validateCanSubmitChanges,
} );

baseModuleStore = ( ( { selectors, ...store } ) => {
	return {
		...store,
		selectors: {
			...selectors,
			getCanUseSnippet: createRegistrySelector( ( select ) => () => {
				const analyticsSettings = select(
					MODULES_ANALYTICS
				).getSettings();

				const isTagManagerConnected = select(
					CORE_MODULES
				).isModuleConnected( 'tagmanager' );

				if (
					isTagManagerConnected === undefined ||
					analyticsSettings === undefined
				) {
					return undefined;
				}

				if (
					isTagManagerConnected === null ||
					isTagManagerConnected === false
				) {
					return analyticsSettings.getCanUseSnippet;
				}

				const gtmGAPropertyID = select(
					MODULES_TAGMANAGER
				).getGAPropertyID();

				if (
					isValidPropertyID( gtmGAPropertyID ) &&
					gtmGAPropertyID === analyticsSettings.propertyID
				) {
					return false;
				}

				return analyticsSettings.getCanUseSnippet;
			} ),
		},
	};
} )( baseModuleStore );

export default baseModuleStore;
<|endoftext|>


<commit_before>/**
 * Location
 *
 * @class Backbone model representing a location on the map.
 * @author Joakim Lundin
 * @type {Backbone.Model}
 */
var Autocomplete = Backbone.Model.extend(
    /** @lends Autocomplete */
    {
      defaults: {
        id: 0,
        name: 'unknown'
      }
    }
);

/**
 * Collection of locations.
 *
 * @class Backbone collection of Locations
 * @author Joakim Lundin
 * @type {Backbone.Collection}
 */
var Autocompletes = Backbone.Collection.extend(
    /** @lends Autocompletes */
    {
      /** The model used for this Location. */
      model: Autocomplete,

      /**
       * Intercept method performed after fetch().
       * In this method the bounds and campuses variable are set.
       */
      parse: function (response) {
        return response.locations;
      },

      /**
       * Constructs the URL used for getting locations.
       *
       * @return {string} the URL.
       */
      url: function () {
        return 'http://pgbroker-dev.it.su.se/geo/search';
      }
    }
);
<commit_msg>MOB-81 - Updated comments.<commit_after>/**
 * Autocomplete
 *
 * @class Backbone model representing autocomplete strings in location search.
 * @author Joakim Lundin
 * @type {Backbone.Model}
 */
var Autocomplete = Backbone.Model.extend(
    /** @lends Autocomplete */
    {
      defaults: {
        id: 0,
        name: 'unknown'
      }
    }
);

/**
 * Collection of autocomplete locations.
 *
 * @class Backbone collection of Autocomplete locations
 * @author Joakim Lundin
 * @type {Backbone.Collection}
 */
var Autocompletes = Backbone.Collection.extend(
    /** @lends Autocompletes */
    {
      /** The model used. */
      model: Autocomplete,

      /**
       * Intercept method performed after fetch().
       */
      parse: function (response) {
        return response.locations;
      },

      /**
       * Constructs the URL used for getting autocomplete locations.
       *
       * @return {string} the URL.
       */
      url: function () {
        return 'http://pgbroker-dev.it.su.se/geo/search';
      }
    }
);
<|endoftext|>


<commit_before>(function (site, angular) {

    if (!angular) {
        return;
    }

    site.ng = site.ng || {};

    site.ng.http = {
        defaultError: {
            message: 'Ajax request did not succeed!',
            details: 'Error detail not sent by server.'
        },

        logError: function (error) {
            site.log.error(error);
        },

        showError: function (error) {
            if (error.details) {
                return site.message.error(error.details, error.message || site.ng.http.defaultError.message);
            } else {
                return site.message.error(error.message || site.ng.http.defaultError.message);
            }
        },

        handleTargetUrl: function (targetUrl) {
            location.href = targetUrl;
        },

        handleUnAuthorizedRequest: function (messagePromise, targetUrl) {
            if (messagePromise) {
                messagePromise.done(function () {
                    if (!targetUrl) {
                        location.reload();
                    } else {
                        site.ng.http.handleTargetUrl(targetUrl);
                    }
                });
            } else {
                if (!targetUrl) {
                    location.reload();
                } else {
                    site.ng.http.handleTargetUrl(targetUrl);
                }
            }
        },

        handleResponse: function (response, defer) {
            var originalData = response.data;

            if (originalData.success === true) {
                response.data = originalData.result;
                defer.resolve(response);

                if (originalData.targetUrl) {
                    site.ng.http.handleTargetUrl(originalData.targetUrl);
                }
            } else if (originalData.success === false) {
                var messagePromise = null;

                if (originalData.error) {
                    messagePromise = site.ng.http.showError(originalData.error);
                } else {
                    originalData.error = defaultError;
                }

                site.ng.http.logError(originalData.error);

                response.data = originalData.error;
                defer.reject(response);

                if (originalData.unAuthorizedRequest) {
                    site.ng.http.handleUnAuthorizedRequest(messagePromise, originalData.targetUrl);
                }
            } else { //not wrapped result
                defer.resolve(response);
            }
        }
    }

    function endsWith(str, suffix) {
        if (suffix.length > str.length) {
            return false;
        }

        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }

    var siteModule = angular.module('site', []);

    siteModule.config([
        '$httpProvider', function ($httpProvider) {
            $httpProvider.interceptors.push(['$q', function ($q) {

                return {

                    'request': function (config) {
                        if (endsWith(config.url, '.html')) {
                            config.url = site.appPath + 'AppView/Load?viewUrl=' + config.url + '&_t=' + site.pageLoadTime.getTime();
                        }

                        return config;
                    },

                    'response': function (response) {
                        if (!response.config || !response.config.site || !response.data) {
                            return response;
                        }

                        var defer = $q.defer();

                        site.ng.http.handleResponse(response, defer);

                        return defer.promise;
                    },

                    'responseError': function (ngError) {
                        var error = {
                            message: ngError.data || site.ng.http.defaultError.message,
                            details: ngError.statusText || site.ng.http.defaultError.details,
                            responseError: true
                        }

                        site.ng.http.showError(error);

                        site.ng.http.logError(error);

                        return $q.reject(ngError);
                    }

                };
            }]);
        }
    ]);
})((site || (site = {})), (angular || undefined));<commit_msg>Update site.ng.js<commit_after>(function (site, angular) {

    if (!angular) {
        return;
    }

    site.ng = site.ng || {};

    site.ng.http = {
        defaultError: {
            message: 'Ajax request did not succeed!',
            details: 'Error detail not sent by server.'
        },

        logError: function (error) {
            site.log.error(error);
        },

        showError: function (error) {
            if (error.details) {
                return site.message.error(error.details, error.message || site.ng.http.defaultError.message);
            } else {
                return site.message.error(error.message || site.ng.http.defaultError.message);
            }
        },

        handleTargetUrl: function (targetUrl) {
            location.href = targetUrl;
        },

        handleUnAuthorizedRequest: function (messagePromise, targetUrl) {
            if (messagePromise) {
                messagePromise.done(function () {
                    if (!targetUrl) {
                        location.reload();
                    } else {
                        site.ng.http.handleTargetUrl(targetUrl);
                    }
                });
            } else {
                if (!targetUrl) {
                    location.reload();
                } else {
                    site.ng.http.handleTargetUrl(targetUrl);
                }
            }
        },

        handleResponse: function (response, defer) {
            var originalData = response.data;

            if (originalData.success === true) {
                response.data = originalData.result;
                defer.resolve(response);

                if (originalData.targetUrl) {
                    site.ng.http.handleTargetUrl(originalData.targetUrl);
                }
            } else if (originalData.success === false) {
                var messagePromise = null;

                if (originalData.error) {
                    messagePromise = site.ng.http.showError(originalData.error);
                } else {
                    originalData.error = defaultError;
                }

                site.ng.http.logError(originalData.error);

                response.data = originalData.error;
                defer.reject(response);

                if (originalData.unAuthorizedRequest) {
                    site.ng.http.handleUnAuthorizedRequest(messagePromise, originalData.targetUrl);
                }
            } else { //not wrapped result
                defer.resolve(response);
            }
        }
    }

    function endsWith(str, suffix) {
        if (suffix.length > str.length) {
            return false;
        }

        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }

    var siteModule = angular.module('site', []);

    siteModule.config([
        '$httpProvider', function ($httpProvider) {
            $httpProvider.interceptors.push(['$q', function ($q) {

                return {

                    'request': function (config) {
                        if (endsWith(config.url, '.cshtml')) {
                            config.url = site.appPath + 'AppView/Load?viewUrl=' + config.url + '&_t=' + site.pageLoadTime.getTime();
                        }

                        return config;
                    },

                    'response': function (response) {
                        if (!response.config || !response.config.site || !response.data) {
                            return response;
                        }

                        var defer = $q.defer();

                        site.ng.http.handleResponse(response, defer);

                        return defer.promise;
                    },

                    'responseError': function (ngError) {
                        var error = {
                            message: ngError.data || site.ng.http.defaultError.message,
                            details: ngError.statusText || site.ng.http.defaultError.details,
                            responseError: true
                        }

                        site.ng.http.showError(error);

                        site.ng.http.logError(error);

                        return $q.reject(ngError);
                    }

                };
            }]);
        }
    ]);
})((site || (site = {})), (angular || undefined));
<|endoftext|>


<commit_before>import {
  FeatureDetection,
  Math as CesiumMath,
  ResourceCache,
  Resource,
  ModelExperimental,
  Cartesian3,
  defined,
  when,
  ShaderProgram,
  ModelFeature,
} from "../../../Source/Cesium.js";
import createScene from "../../createScene.js";
import loadAndZoomToModelExperimental from "./loadAndZoomToModelExperimental.js";

describe(
  "Scene/ModelExperimental/ModelExperimental",
  function () {
    var webglStub = !!window.webglStub;

    var boxTexturedGlbUrl =
      "./Data/Models/GltfLoader/BoxTextured/glTF-Binary/BoxTextured.glb";
    var buildingsMetadata =
      "./Data/Models/GltfLoader/BuildingsMetadata/glTF/buildings-metadata.gltf";

    var scene;

    beforeAll(function () {
      scene = createScene();
    });

    afterAll(function () {
      scene.destroyForSpecs();
    });

    afterEach(function () {
      scene.primitives.removeAll();
      ResourceCache.clearForSpecs();
    });

    it("initializes from Uint8Array", function () {
      var resource = Resource.createIfNeeded(boxTexturedGlbUrl);
      var loadPromise = resource.fetchArrayBuffer();
      return loadPromise.then(function (buffer) {
        return loadAndZoomToModelExperimental(
          { gltf: new Uint8Array(buffer) },
          scene
        ).then(function (model) {
          expect(model.ready).toEqual(true);
          expect(model._sceneGraph).toBeDefined();
          expect(model._resourcesLoaded).toEqual(true);
        });
      });
    });

    it("initializes ModelFeatureTable", function () {
      return loadAndZoomToModelExperimental(
        { gltf: buildingsMetadata },
        scene
      ).then(function (model) {
        expect(model.ready).toEqual(true);
        expect(model._featureTable).toBeDefined();

        var modelFeatureTable = model._featureTable;
        expect(modelFeatureTable._featuresLength).toEqual(10);
        expect(modelFeatureTable._batchTexture).toBeDefined();
        expect(modelFeatureTable._batchTexture._featuresLength).toEqual(10);

        var modelFeatures = modelFeatureTable._features;
        for (var i = 0; i < modelFeatures.length; i++) {
          var modelFeature = modelFeatures[i];
          expect(modelFeature instanceof ModelFeature).toEqual(true);
          expect(modelFeature._featureId).toEqual(i);
          expect(modelFeature.primitive).toEqual(model);
          expect(modelFeature.content).toBeUndefined();
        }

        expect(model._resourcesLoaded).toEqual(true);
      });
    });

    it("debugShowBoundingVolume works", function () {
      var resource = Resource.createIfNeeded(boxTexturedGlbUrl);
      var loadPromise = resource.fetchArrayBuffer();
      return loadPromise.then(function (buffer) {
        return loadAndZoomToModelExperimental(
          { gltf: new Uint8Array(buffer), debugShowBoundingVolume: true },
          scene
        ).then(function (model) {
          var i;
          scene.renderForSpecs();
          var commandList = scene.frameState;
          for (i = 0; i < commandList.length; i++) {
            expect(commandList[i].debugShowBoundingVolume).toBe(true);
          }
          model.debugShowBoundingVolume = false;
          expect(model._debugShowBoundingVolumeDirty).toBe(true);
          scene.renderForSpecs();
          for (i = 0; i < commandList.length; i++) {
            expect(commandList[i].debugShowBoundingVolume).toBe(false);
          }
        });
      });
    });

    it("boundingSphere works", function () {
      var resource = Resource.createIfNeeded(boxTexturedGlbUrl);
      var loadPromise = resource.fetchArrayBuffer();
      return loadPromise.then(function (buffer) {
        return loadAndZoomToModelExperimental(
          { gltf: new Uint8Array(buffer), debugShowBoundingVolume: true },
          scene
        ).then(function (model) {
          var boundingSphere = model.boundingSphere;
          expect(boundingSphere).toBeDefined();
          expect(boundingSphere.center).toEqual(new Cartesian3());
          expect(boundingSphere.radius).toEqualEpsilon(
            0.8660254037844386,
            CesiumMath.EPSILON8
          );
        });
      });
    });

    it("fromGltf throws with undefined options", function () {
      expect(function () {
        ModelExperimental.fromGltf();
      }).toThrowDeveloperError();
    });

    it("fromGltf throws with undefined url", function () {
      expect(function () {
        ModelExperimental.fromGltf({});
      }).toThrowDeveloperError();
    });

    it("picks box textured", function () {
      if (FeatureDetection.isInternetExplorer()) {
        // Workaround IE 11.0.9.  This test fails when all tests are ran without a breakpoint here.
        return;
      }

      return loadAndZoomToModelExperimental(
        {
          gltf: boxTexturedGlbUrl,
        },
        scene
      ).then(function (model) {
        expect(scene).toPickAndCall(function (result) {
          expect(result.model).toEqual(model);
        });
      });
    });

    it("doesn't pick when allowPicking is false", function () {
      if (FeatureDetection.isInternetExplorer()) {
        // Workaround IE 11.0.9.  This test fails when all tests are ran without a breakpoint here.
        return;
      }

      return loadAndZoomToModelExperimental(
        {
          gltf: boxTexturedGlbUrl,
          allowPicking: false,
        },
        scene
      ).then(function () {
        expect(scene).toPickAndCall(function (result) {
          expect(result).toBeUndefined();
        });
      });
    });

    it("destroy works", function () {
      spyOn(ShaderProgram.prototype, "destroy").and.callThrough();
      return loadAndZoomToModelExperimental(
        { gltf: boxTexturedGlbUrl },
        scene
      ).then(function (model) {
        var resources = model._resources;
        var loader = model._loader;
        var resource;

        var i;
        for (i = 0; i < resources.length; i++) {
          resource = resources[i];
          if (defined(resource.isDestroyed)) {
            expect(resource.isDestroyed()).toEqual(false);
          }
        }
        expect(loader.isDestroyed()).toEqual(false);
        expect(model.isDestroyed()).toEqual(false);
        scene.primitives.remove(model);
        if (!webglStub) {
          expect(ShaderProgram.prototype.destroy).toHaveBeenCalled();
        }
        for (i = 0; i < resources.length - 1; i++) {
          resource = resources[i];
          if (defined(resource.isDestroyed)) {
            expect(resource.isDestroyed()).toEqual(true);
          }
        }
        expect(loader.isDestroyed()).toEqual(true);
        expect(model.isDestroyed()).toEqual(true);
      });
    });

    it("destroy doesn't destroy resources when they're in use", function () {
      return when
        .all([
          loadAndZoomToModelExperimental({ gltf: boxTexturedGlbUrl }, scene),
          loadAndZoomToModelExperimental({ gltf: boxTexturedGlbUrl }, scene),
        ])
        .then(function (models) {
          var cacheEntries = ResourceCache.cacheEntries;
          var cacheKey;
          var cacheEntry;

          scene.primitives.remove(models[0]);

          for (cacheKey in cacheEntries) {
            if (cacheEntries.hasOwnProperty(cacheKey)) {
              cacheEntry = cacheEntries[cacheKey];
              expect(cacheEntry.referenceCount).toBeGreaterThan(0);
            }
          }

          scene.primitives.remove(models[1]);

          for (cacheKey in cacheEntries) {
            if (cacheEntries.hasOwnProperty(cacheKey)) {
              cacheEntry = cacheEntries[cacheKey];
              expect(cacheEntry.referenceCount).toBe(0);
            }
          }
        });
    });
  },
  "WebGL"
);
<commit_msg>Spec fix<commit_after>import {
  FeatureDetection,
  Math as CesiumMath,
  ResourceCache,
  Resource,
  ModelExperimental,
  Cartesian3,
  defined,
  when,
  ShaderProgram,
  ModelFeature,
} from "../../../Source/Cesium.js";
import createScene from "../../createScene.js";
import loadAndZoomToModelExperimental from "./loadAndZoomToModelExperimental.js";

describe(
  "Scene/ModelExperimental/ModelExperimental",
  function () {
    var webglStub = !!window.webglStub;

    var boxTexturedGlbUrl =
      "./Data/Models/GltfLoader/BoxTextured/glTF-Binary/BoxTextured.glb";
    var buildingsMetadata =
      "./Data/Models/GltfLoader/BuildingsMetadata/glTF/buildings-metadata.gltf";

    var scene;

    beforeAll(function () {
      scene = createScene();
    });

    afterAll(function () {
      scene.destroyForSpecs();
    });

    afterEach(function () {
      scene.primitives.removeAll();
      ResourceCache.clearForSpecs();
    });

    it("initializes from Uint8Array", function () {
      var resource = Resource.createIfNeeded(boxTexturedGlbUrl);
      var loadPromise = resource.fetchArrayBuffer();
      return loadPromise.then(function (buffer) {
        return loadAndZoomToModelExperimental(
          { gltf: new Uint8Array(buffer) },
          scene
        ).then(function (model) {
          expect(model.ready).toEqual(true);
          expect(model._sceneGraph).toBeDefined();
          expect(model._resourcesLoaded).toEqual(true);
        });
      });
    });

    it("initializes feature table", function () {
      return loadAndZoomToModelExperimental(
        { gltf: buildingsMetadata },
        scene
      ).then(function (model) {
        expect(model.ready).toEqual(true);
        expect(model._featureTable).toBeDefined();

        var modelFeatureTable = model._featureTable;
        expect(modelFeatureTable._featuresLength).toEqual(10);
        expect(modelFeatureTable._batchTexture).toBeDefined();
        expect(modelFeatureTable._batchTexture._featuresLength).toEqual(10);

        var modelFeatures = modelFeatureTable._features;
        for (var i = 0; i < modelFeatures.length; i++) {
          var modelFeature = modelFeatures[i];
          expect(modelFeature instanceof ModelFeature).toEqual(true);
          expect(modelFeature._featureId).toEqual(i);
          expect(modelFeature.primitive).toEqual(model);
          expect(modelFeature.content).toEqual(modelFeatureTable);
        }

        expect(model._resourcesLoaded).toEqual(true);
      });
    });

    it("debugShowBoundingVolume works", function () {
      var resource = Resource.createIfNeeded(boxTexturedGlbUrl);
      var loadPromise = resource.fetchArrayBuffer();
      return loadPromise.then(function (buffer) {
        return loadAndZoomToModelExperimental(
          { gltf: new Uint8Array(buffer), debugShowBoundingVolume: true },
          scene
        ).then(function (model) {
          var i;
          scene.renderForSpecs();
          var commandList = scene.frameState;
          for (i = 0; i < commandList.length; i++) {
            expect(commandList[i].debugShowBoundingVolume).toBe(true);
          }
          model.debugShowBoundingVolume = false;
          expect(model._debugShowBoundingVolumeDirty).toBe(true);
          scene.renderForSpecs();
          for (i = 0; i < commandList.length; i++) {
            expect(commandList[i].debugShowBoundingVolume).toBe(false);
          }
        });
      });
    });

    it("boundingSphere works", function () {
      var resource = Resource.createIfNeeded(boxTexturedGlbUrl);
      var loadPromise = resource.fetchArrayBuffer();
      return loadPromise.then(function (buffer) {
        return loadAndZoomToModelExperimental(
          { gltf: new Uint8Array(buffer), debugShowBoundingVolume: true },
          scene
        ).then(function (model) {
          var boundingSphere = model.boundingSphere;
          expect(boundingSphere).toBeDefined();
          expect(boundingSphere.center).toEqual(new Cartesian3());
          expect(boundingSphere.radius).toEqualEpsilon(
            0.8660254037844386,
            CesiumMath.EPSILON8
          );
        });
      });
    });

    it("fromGltf throws with undefined options", function () {
      expect(function () {
        ModelExperimental.fromGltf();
      }).toThrowDeveloperError();
    });

    it("fromGltf throws with undefined url", function () {
      expect(function () {
        ModelExperimental.fromGltf({});
      }).toThrowDeveloperError();
    });

    it("picks box textured", function () {
      if (FeatureDetection.isInternetExplorer()) {
        // Workaround IE 11.0.9.  This test fails when all tests are ran without a breakpoint here.
        return;
      }

      return loadAndZoomToModelExperimental(
        {
          gltf: boxTexturedGlbUrl,
        },
        scene
      ).then(function (model) {
        expect(scene).toPickAndCall(function (result) {
          expect(result.model).toEqual(model);
        });
      });
    });

    it("doesn't pick when allowPicking is false", function () {
      if (FeatureDetection.isInternetExplorer()) {
        // Workaround IE 11.0.9.  This test fails when all tests are ran without a breakpoint here.
        return;
      }

      return loadAndZoomToModelExperimental(
        {
          gltf: boxTexturedGlbUrl,
          allowPicking: false,
        },
        scene
      ).then(function () {
        expect(scene).toPickAndCall(function (result) {
          expect(result).toBeUndefined();
        });
      });
    });

    it("destroy works", function () {
      spyOn(ShaderProgram.prototype, "destroy").and.callThrough();
      return loadAndZoomToModelExperimental(
        { gltf: boxTexturedGlbUrl },
        scene
      ).then(function (model) {
        var resources = model._resources;
        var loader = model._loader;
        var resource;

        var i;
        for (i = 0; i < resources.length; i++) {
          resource = resources[i];
          if (defined(resource.isDestroyed)) {
            expect(resource.isDestroyed()).toEqual(false);
          }
        }
        expect(loader.isDestroyed()).toEqual(false);
        expect(model.isDestroyed()).toEqual(false);
        scene.primitives.remove(model);
        if (!webglStub) {
          expect(ShaderProgram.prototype.destroy).toHaveBeenCalled();
        }
        for (i = 0; i < resources.length - 1; i++) {
          resource = resources[i];
          if (defined(resource.isDestroyed)) {
            expect(resource.isDestroyed()).toEqual(true);
          }
        }
        expect(loader.isDestroyed()).toEqual(true);
        expect(model.isDestroyed()).toEqual(true);
      });
    });

    it("destroy doesn't destroy resources when they're in use", function () {
      return when
        .all([
          loadAndZoomToModelExperimental({ gltf: boxTexturedGlbUrl }, scene),
          loadAndZoomToModelExperimental({ gltf: boxTexturedGlbUrl }, scene),
        ])
        .then(function (models) {
          var cacheEntries = ResourceCache.cacheEntries;
          var cacheKey;
          var cacheEntry;

          scene.primitives.remove(models[0]);

          for (cacheKey in cacheEntries) {
            if (cacheEntries.hasOwnProperty(cacheKey)) {
              cacheEntry = cacheEntries[cacheKey];
              expect(cacheEntry.referenceCount).toBeGreaterThan(0);
            }
          }

          scene.primitives.remove(models[1]);

          for (cacheKey in cacheEntries) {
            if (cacheEntries.hasOwnProperty(cacheKey)) {
              cacheEntry = cacheEntries[cacheKey];
              expect(cacheEntry.referenceCount).toBe(0);
            }
          }
        });
    });
  },
  "WebGL"
);
<|endoftext|>


<commit_before>// Test the widget manager.
casper.notebook_test(function () {
    var index;

    this.then(function () {

        // Check if the WidgetManager class is defined.
        this.test.assert(this.evaluate(function() {
            return IPython.WidgetManager !== undefined;
        }), 'WidgetManager class is defined');

        // Check if the widget manager has been instantiated.
        this.test.assert(this.evaluate(function() {
            return IPython.notebook.kernel.widget_manager !== undefined;
        }), 'Notebook widget manager instantiated');

        // Try creating a widget from Javascript.
        this.evaluate(function() {
            IPython.notebook.kernel.widget_manager.create_model({
                model_name: 'WidgetModel',
                widget_class: 'IPython.html.widgets.widget_int.IntSlider'})
                .then(function(model) {
                    console.log('Create success!', model);
                    window.slider_id = model.id;
                }, function(error) { console.log(error); });
        });
    });

    // Wait for the state to be recieved.
    this.waitFor(function check() {
        return this.evaluate(function() {
            return window.slider_id !== undefined;
        });
    });

    index = this.append_cell(
        'from IPython.html.widgets import Widget\n' +
        'widget = list(Widget.widgets.values())[0]\n' +
        'print(widget.model_id)');
    this.execute_cell_then(index, function(index) {
        var output = this.get_output_cell(index).text.trim();
        var slider_id = this.evaluate(function() { return window.slider_id; });
        this.test.assertEquals(output, slider_id, "Widget created from the front-end.");
    });
});
<commit_msg>Test for persistence.<commit_after>// Test the widget manager.
casper.notebook_test(function () {
    var index;

    this.then(function () {

        // Check if the WidgetManager class is defined.
        this.test.assert(this.evaluate(function() {
            return IPython.WidgetManager !== undefined;
        }), 'WidgetManager class is defined');

        // Check if the widget manager has been instantiated.
        this.test.assert(this.evaluate(function() {
            return IPython.notebook.kernel.widget_manager !== undefined;
        }), 'Notebook widget manager instantiated');

        // Try creating a widget from Javascript.
        this.evaluate(function() {
            IPython.notebook.kernel.widget_manager.create_model({
                model_name: 'WidgetModel',
                widget_class: 'IPython.html.widgets.widget_int.IntSlider'})
                .then(function(model) {
                    console.log('Create success!', model);
                    window.slider_id = model.id;
                }, function(error) { console.log(error); });
        });
    });

    // Wait for the state to be recieved.
    this.waitFor(function check() {
        return this.evaluate(function() {
            return window.slider_id !== undefined;
        });
    });

    index = this.append_cell(
        'from IPython.html.widgets import Widget\n' +
        'widget = list(Widget.widgets.values())[0]\n' +
        'print(widget.model_id)');
    this.execute_cell_then(index, function(index) {
        var output = this.get_output_cell(index).text.trim();
        var slider_id = this.evaluate(function() { return window.slider_id; });
        this.test.assertEquals(output, slider_id, "Widget created from the front-end.");
    });

    // Widget persistence tests.
    index = this.append_cell(
        'from IPython.html.widgets import HTML\n' +
        'from IPython.display import display\n' +
        'display(HTML(value="

"))');
    this.execute_cell_then(index, function() {});

    index = this.append_cell(
        'display(HTML(value="

"))');
    this.execute_cell_then(index, function() {});

    var that = this;
    this.then(function() {
        // Wait for the widgets to be shown.
        that.waitForSelector('#hello', function() {
            that.waitForSelector('#world', function() {
                that.test.assertExists('#hello', 'Hello HTML widget constructed.');
                that.test.assertExists('#world', 'World HTML widget constructed.');

                // Save the notebook.
                that.evaluate(function() {
                    IPython.notebook.save_notebook(false).then(function() {
                        window.was_saved = true;
                    });
                });
                that.waitFor(function check() {
                    return that.evaluate(function() {
                        return window.was_saved;
                    });
                }, function then() {

                    // Reload the page
                    that.reload(function() {

                        // Wait for the elements to show up again.
                        that.waitForSelector('#hello', function() {
                            that.waitForSelector('#world', function() {
                                that.test.assertExists('#hello', 'Hello HTML widget persisted.');
                                that.test.assertExists('#world', 'World HTML widget persisted.');
                            });
                        });
                    });
                });
            });
        });
    });

});
<|endoftext|>


<commit_before><commit_msg>remove scripts folder<commit_after><|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router';

export default function () {
  return (

{'What\'s this about?'}

      <Link to={'/repo/michaelBenin/react-ssr-spa'}>react-ssr-spa</Link>

  );
}
<commit_msg>[MISC] updated copy in about<commit_after>import React from 'react';
import { Link } from 'react-router';

export default function () {
  return (

{'What\'s this about?'}

        This project aims to do one thing well: make server side rendering simple
        in a react application using only mature community maintained libraries.

      <Link to={'/repo/michaelBenin/react-ssr-spa'}>react-ssr-spa</Link>

  );
}
<|endoftext|>


<commit_before>/**
 * @class Denkmal_Layout_Default
 * @extends CM_Layout_Abstract
 */
var Denkmal_Layout_Default = CM_Layout_Abstract.extend({

  /** @type String */
  _class: 'Denkmal_Layout_Default',

  childrenEvents: {
    'Denkmal_Page_Events ready': function(view) {
      var $layout = this.$el;
      var $pageScrollables = view.$('.scrollable');

      var onScroll = function() {
        var scrolledNotTop = view.$('.active .scrollable').scrollTop() > 20;
        $layout.toggleClass('scrolledNotTop', scrolledNotTop);
      };

      $pageScrollables.bind('scroll', onScroll);
      view.on('destruct', function() {
        $pageScrollables.unbind('scroll', onScroll);
      });
      view.on('swipe', function() {
        onScroll();
      });
      onScroll();

      $layout.addClass('menu-visible');
    },

    'Denkmal_Page_Events destruct': function(view) {
      var $layout = this.$el;
      $layout.removeClass('menu-visible');

      var headerBar = cm.findView('Denkmal_Component_HeaderBar');
      headerBar.toggleMenu(false);
    }
  }
});
<commit_msg>Add basic chat indication logic<commit_after>/**
 * @class Denkmal_Layout_Default
 * @extends CM_Layout_Abstract
 */
var Denkmal_Layout_Default = CM_Layout_Abstract.extend({

  /** @type String */
  _class: 'Denkmal_Layout_Default',

  childrenEvents: {
    'Denkmal_Page_Events ready': function(view) {
      var $layout = this.$el;
      var $pageScrollables = view.$('.scrollable');

      var onScroll = function() {
        var scrolledNotTop = view.$('.active .scrollable').scrollTop() > 20;
        $layout.toggleClass('scrolledNotTop', scrolledNotTop);
      };

      $pageScrollables.bind('scroll', onScroll);
      view.on('destruct', function() {
        $pageScrollables.unbind('scroll', onScroll);
      });
      view.on('swipe', function() {
        onScroll();
      });
      onScroll();

      $layout.addClass('menu-visible');
    },

    'Denkmal_Page_Events destruct': function(view) {
      var $layout = this.$el;
      $layout.removeClass('menu-visible');

      var headerBar = cm.findView('Denkmal_Component_HeaderBar');
      headerBar.toggleMenu(false);
    },

    'Denkmal_Page_Now ready': function() {
      this.setChatIndication(false);
    }
  },

  ready: function() {
    this.bindStream('global-internal', cm.model.types.CM_Model_StreamChannel_Message, 'message-create', function(message) {
      var page = cm.getLayout().findPage();
      var isChat = page && page.hasClass('Denkmal_Page_Now');
      if (!isChat) {
        this.setChatIndication(true);
      }
    });
  },

  /**
   * @param {Boolean} state
   */
  setChatIndication: function(state) {
    console.log('indication', state);
  }
});
<|endoftext|>


<commit_before>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210', 'snap.svg_030'],
    function (ext, $, Raphael, Snap) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide = {};
            cur_slide["in"] = data[0];
            this_e.addAnimationSlide(cur_slide);
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }

            //YOUR FUNCTION NAME
            var fname = 'checkio';

            var checkioInput = data.in || ["51°28′48″N 0°0′0″E", "46°12′0″N, 6°9′0″E"];
            var checkioInputStr = fname + '(u' + JSON.stringify(checkioInput) + ')';

            var failError = function (dError) {
                $content.find('.call').html(checkioInputStr);
                $content.find('.output').html(dError.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
            };

            if (data.error) {
                failError(data.error);
                return false;
            }

            if (data.ext && data.ext.inspector_fail) {
                failError(data.ext.inspector_result_addon);
                return false;
            }

            $content.find('.call').html(checkioInputStr);
            $content.find('.output').html('Working...');

            if (data.ext) {
                var rightResult = data.ext["answer"];
                var userResult = data.out;
                var result = data.ext["result"];
                var result_addon = data.ext["result_addon"];

                //if you need additional info from tests (if exists)
                var explanation = data.ext["explanation"];
                $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));
                if (!result) {
                    $content.find('.answer').html('Right result: ' + ext.JSON.encode(rightResult));
                    $content.find('.answer').addClass('error');
                    $content.find('.output').addClass('error');
                    $content.find('.call').addClass('error');
                }
                else {
                    $content.find('.answer').remove();
                }
            }
            else {
                $content.find('.answer').remove();
            }

            //Your code here about test explanation animation
            //$content.find(".explanation").html("Something text for example");
            //
            //
            //
            //
            //

            this_e.setAnimationHeight($content.height() + 60);

        });

        //This is for Tryit (but not necessary)
//        var $tryit;
//        ext.set_console_process_ret(function (this_e, ret) {
//            $tryit.find(".checkio-result").html("Result
" + ret);
//        });
//
//        ext.set_generate_animation_panel(function (this_e) {
//            $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content');
//            $tryit.find('.bn-check').click(function (e) {
//                e.preventDefault();
//                this_e.sendToConsoleCheckiO("something");
//            });
//        });

        var colorOrange4 = "#F0801A";
        var colorOrange3 = "#FA8F00";
        var colorOrange2 = "#FAA600";
        var colorOrange1 = "#FABA00";

        var colorBlue4 = "#294270";
        var colorBlue3 = "#006CA9";
        var colorBlue2 = "#65A1CF";
        var colorBlue1 = "#8FC7ED";

        var colorGrey4 = "#737370";
        var colorGrey3 = "#9D9E9E";
        var colorGrey2 = "#C5C6C6";
        var colorGrey1 = "#EBEDED";

        var colorWhite = "#FFFFFF";
        //Your Additional functions or objects inside scope
        //
        //
        //

    }
);
<commit_msg>Update init.js<commit_after>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210', 'snap.svg_030'],
    function (ext, $, Raphael, Snap) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide = {};
            cur_slide["in"] = data[0];
            this_e.addAnimationSlide(cur_slide);
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }

            //YOUR FUNCTION NAME
            var fname = 'checkio';

            var checkioInput = data.in || ["51°28′48″N 0°0′0″E", "46°12′0″N, 6°9′0″E"];
            var checkioInputStr = fname + '(' + JSON.stringify(checkioInput) + ')';

            var failError = function (dError) {
                $content.find('.call').html(checkioInputStr);
                $content.find('.output').html(dError.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
            };

            if (data.error) {
                failError(data.error);
                return false;
            }

            if (data.ext && data.ext.inspector_fail) {
                failError(data.ext.inspector_result_addon);
                return false;
            }

            $content.find('.call').html(checkioInputStr);
            $content.find('.output').html('Working...');

            if (data.ext) {
                var rightResult = data.ext["answer"];
                var userResult = data.out;
                var result = data.ext["result"];
                var result_addon = data.ext["result_addon"];

                //if you need additional info from tests (if exists)
                var explanation = data.ext["explanation"];
                $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));
                if (!result) {
                    $content.find('.answer').html('Right result: ' + ext.JSON.encode(rightResult));
                    $content.find('.answer').addClass('error');
                    $content.find('.output').addClass('error');
                    $content.find('.call').addClass('error');
                }
                else {
                    $content.find('.answer').remove();
                }
            }
            else {
                $content.find('.answer').remove();
            }

            //Your code here about test explanation animation
            //$content.find(".explanation").html("Something text for example");
            //
            //
            //
            //
            //

            this_e.setAnimationHeight($content.height() + 60);

        });

        //This is for Tryit (but not necessary)
//        var $tryit;
//        ext.set_console_process_ret(function (this_e, ret) {
//            $tryit.find(".checkio-result").html("Result
" + ret);
//        });
//
//        ext.set_generate_animation_panel(function (this_e) {
//            $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content');
//            $tryit.find('.bn-check').click(function (e) {
//                e.preventDefault();
//                this_e.sendToConsoleCheckiO("something");
//            });
//        });

        var colorOrange4 = "#F0801A";
        var colorOrange3 = "#FA8F00";
        var colorOrange2 = "#FAA600";
        var colorOrange1 = "#FABA00";

        var colorBlue4 = "#294270";
        var colorBlue3 = "#006CA9";
        var colorBlue2 = "#65A1CF";
        var colorBlue1 = "#8FC7ED";

        var colorGrey4 = "#737370";
        var colorGrey3 = "#9D9E9E";
        var colorGrey2 = "#C5C6C6";
        var colorGrey1 = "#EBEDED";

        var colorWhite = "#FFFFFF";
        //Your Additional functions or objects inside scope
        //
        //
        //

    }
);
<|endoftext|>


<commit_before>/**
 * Constant that identifies the map canvas.
 * @type {string}
 */
var MAP_ELEMENT = "map_canvas";

/**
 * Callback that is called when the location is successfully retrieved.
 * @param position
 */
function successLocationCallback (position) {
	//success callback
	userLocation.moveToLocation(position.coords.latitude, position.coords.longitude);
	if (!userLocation.positionMarker) {
		userLocation.positionMarker = new google.maps.Marker({
			position: userLocation.map.getCenter(),
			map: userLocation.map,
			clickable: false,
			icon: "static/stadtgedaechtnis/img/marker_position.png"
		});
	}
	//TODO: maybe add accuracy?
}

/**
 * Callback that is called when the location couldn't be retrieved.
 * @param error
 */
function errorLocationCallback (error) {
	// error callback
	alert(error.id);
	userLocation.moveToLocation(this.DEFAULT_LAT, this.DEFAULT_LONG);
	//TODO: show hint that location couldn't be retrieved
}

/**
 * Location object to enable/disable tracking the location and to retrieve the current or fallback location.
 * @param trackLocation
 * @constructor
 */
function Location() {
	this.DEFAULT_LAT = 50.258;
	this.DEFAULT_LONG = 10.965;
	this.DEFAULT_LOCATION = new google.maps.LatLng(50.258, 10.965);

	this.currentLocation = this.DEFAULT_LOCATION;
	this.positionMarker = null;

	var trackingID;
	var tracking = false;

	/**
	 * enable location tracking
	 */
	this.__defineGetter__("trackLocation", function () {
		return tracking;
	})

	/**
	 * disable location tracking
	 */
	this.__defineSetter__("trackLocation", function (trackLocation) {
		if (Modernizr.geolocation) {
			if (trackLocation) {
				trackingID = navigator.geolocation.watchPosition(successLocationCallback, errorLocationCallback, {enableHighAccuracy: true});
			} else if (!trackLocation) {
				navigator.geolocation.clearWatch(trackingID);
			}
			tracking = trackLocation;
		}
	})

}

/**
 * Move the map to the current location or the fallback
 * @returns {google.maps.LatLng|*}
 */
Location.prototype.moveToCurrentLocationOrFallback = function () {
	if (Modernizr.geolocation) {
		navigator.geolocation.getCurrentPosition(successLocationCallback, errorLocationCallback,{enableHighAccuracy: true});
	} else {
		this.moveToLocation(this.DEFAULT_LAT, this.DEFAULT_LONG);
		//TODO: show hint that browser doesn't support location
	}
};

/**
 * Moves the map to the given location
 * @param lat
 * @param long
 */
Location.prototype.moveToLocation = function(lat, long) {
	if (this.map) {
		var newLocation = new google.maps.LatLng(lat, long);
		this.currentLocation = newLocation;
		this.map.panTo(newLocation);
		if (this.map.positionMarker) {
			this.map.positionMarker.setPosition(newLocation);
		}
	}
}

var userLocation = new Location();

/**
 * Global map Options
 * @type {{center: google.maps.LatLng, zoom: number, mapTypeId: *, disableDefaultUI: boolean, zoomControl: boolean}}
 */
var mapOptions = {
	center: userLocation.DEFAULT_LOCATION,
	zoom: 17,
	mapTypeId: google.maps.MapTypeId.SATELLITE,
	disableDefaultUI: false,
	zoomControl: true
};

/**
 * Initializes the map
 */
function initialize_Map() {
	userLocation.map = new google.maps.Map(document.getElementById(MAP_ELEMENT),
		mapOptions);
	userLocation.moveToCurrentLocationOrFallback();
	userLocation.trackLocation = true;
}<commit_msg>update map type control<commit_after>/**
 * Constant that identifies the map canvas.
 * @type {string}
 */
var MAP_ELEMENT = "map_canvas";

/**
 * Callback that is called when the location is successfully retrieved.
 * @param position
 */
function successLocationCallback (position) {
	//success callback
	userLocation.moveToLocation(position.coords.latitude, position.coords.longitude);
	if (!userLocation.positionMarker) {
		userLocation.positionMarker = new google.maps.Marker({
			position: userLocation.map.getCenter(),
			map: userLocation.map,
			clickable: false,
			icon: "static/stadtgedaechtnis/img/marker_position.png"
		});
	}
	//TODO: maybe add accuracy?
}

/**
 * Callback that is called when the location couldn't be retrieved.
 * @param error
 */
function errorLocationCallback (error) {
	// error callback
	alert(error.id);
	userLocation.moveToLocation(this.DEFAULT_LAT, this.DEFAULT_LONG);
	//TODO: show hint that location couldn't be retrieved
}

/**
 * Location object to enable/disable tracking the location and to retrieve the current or fallback location.
 * @param trackLocation
 * @constructor
 */
function Location() {
	this.DEFAULT_LAT = 50.258;
	this.DEFAULT_LONG = 10.965;
	this.DEFAULT_LOCATION = new google.maps.LatLng(50.258, 10.965);

	this.currentLocation = this.DEFAULT_LOCATION;
	this.positionMarker = null;

	var trackingID;
	var tracking = false;

	/**
	 * enable location tracking
	 */
	this.__defineGetter__("trackLocation", function () {
		return tracking;
	})

	/**
	 * disable location tracking
	 */
	this.__defineSetter__("trackLocation", function (trackLocation) {
		if (Modernizr.geolocation) {
			if (trackLocation) {
				trackingID = navigator.geolocation.watchPosition(successLocationCallback, errorLocationCallback, {enableHighAccuracy: true});
			} else if (!trackLocation) {
				navigator.geolocation.clearWatch(trackingID);
			}
			tracking = trackLocation;
		}
	})

}

/**
 * Move the map to the current location or the fallback
 * @returns {google.maps.LatLng|*}
 */
Location.prototype.moveToCurrentLocationOrFallback = function () {
	if (Modernizr.geolocation) {
		navigator.geolocation.getCurrentPosition(successLocationCallback, errorLocationCallback,{enableHighAccuracy: true});
	} else {
		this.moveToLocation(this.DEFAULT_LAT, this.DEFAULT_LONG);
		//TODO: show hint that browser doesn't support location
	}
};

/**
 * Moves the map to the given location
 * @param lat
 * @param long
 */
Location.prototype.moveToLocation = function(lat, long) {
	if (this.map) {
		var newLocation = new google.maps.LatLng(lat, long);
		this.currentLocation = newLocation;
		this.map.panTo(newLocation);
		if (this.map.positionMarker) {
			this.map.positionMarker.setPosition(newLocation);
		}
	}
}

var userLocation = new Location();

/**
 * Global map Options
 * @type {{center: google.maps.LatLng, zoom: number, mapTypeId: *, disableDefaultUI: boolean, zoomControl: boolean}}
 */
var mapOptions = {
	center: userLocation.DEFAULT_LOCATION,
	zoom: 17,
    mapTypeControl: true,
	mapTypeId: google.maps.MapTypeId.SATELLITE,
	disableDefaultUI: true,
	zoomControl: true
};

/**
 * Initializes the map
 */
function initialize_Map() {
	userLocation.map = new google.maps.Map(document.getElementById(MAP_ELEMENT),
		mapOptions);
	userLocation.moveToCurrentLocationOrFallback();
	userLocation.trackLocation = true;
}<|endoftext|>


<commit_before>define([
    'dojo/_base/declare',
    'dojo/_base/array',
    'dojo/_base/lang',
    'JBrowse/View/FeatureGlyph/Alignment',
    'JBrowse/View/FeatureGlyph/AlignmentColoring',
    'JBrowse/Util'
],
function(
    declare,
    array,
    lang,
    Alignment,
    AlignmentColoring,
    Util
) {

return declare(Alignment, {

clearFeat(context, fRect) {
    if( this.track.displayMode != 'collapsed' )
        context.clearRect( Math.floor(fRect.l), fRect.t, Math.ceil(fRect.w), fRect.h );
},
renderFeature(context, fRect) {
    const f = fRect.f
    this.clearFeat(context, fRect)

    if (f.pairedFeature()) {
        this.renderConnector( context, fRect )
        this.renderSegments( context, fRect )
        if (fRect.w > 2) {
            if (fRect.viewInfo.scale > 0.2) {
                this._drawMismatches( context, fRect, this._getMismatches( f.read1 ), f.read1 )
                this._drawMismatches( context, fRect, this._getMismatches( f.read2 ), f.read2 )
            }
            else {
                this._drawMismatches( context, fRect, this._getSkipsAndDeletions( f.read1 ), f.read1 )
                this._drawMismatches( context, fRect, this._getSkipsAndDeletions( f.read2 ), f.read2 )
            }
        }
        const x1 = f.read1.get('start')
        const x2 = f.read1.get('end')
        const y1 = f.read2.get('start')
        const y2 = f.read2.get('end')
        if(Util.intersect(x1, x2, y1, y2)) {
            const s1 = x2 > y2 ? x1 : y1
            const s2 = x1 > y1 ? y2 : x2
            const block = fRect.viewInfo.block
            const l = block.bpToX(s1)
            const r = block.bpToX(s2)
            context.fillStyle = this.getStyle(f, 'overlapColor')
            context.strokeStyle = this.getStyle(f, 'overlapStroke')
            context.rect(
                l, // left
                fRect.rect.t,
                r-l, // width
                fRect.rect.h
            )
            context.fill();
            context.stroke()
            context.strokeStyle = null
            context.fillStyle = null
            var m1 = this._getMismatches( f.read1 );
            var m2 = this._getMismatches( f.read2 );
            if(!m1 && !m2) {
                return;
            } else {
                var mismatches = [];
                for(var i = 0; i < m1.length; i++) {
                    for(var j = 0; j < m2.length; j++) {
                        if(x1+m1[i].start == y1+m2[j].start && s1 < x1+m1[i].start && s2 > x1+m1[i].start) {
                            mismatches.push({ start: m1[i].start, base1: m1[i].base, base2: m2[j].base, type: 'mismatch', length: 1 });
                        }
                    }
                }
                if(mismatches.length !== 0) {
                    this._drawOverlappingMismatches(context, fRect, mismatches, x1)
                }
            }
        }
    } else {
        this.inherited(arguments)
    }
},

renderSegments(context, fRect) {
    this.renderBox(context, fRect.viewInfo, fRect.f.read1,  fRect.t, fRect.rect.h, fRect.f);
    this.renderBox(context, fRect.viewInfo, fRect.f.read2,  fRect.t, fRect.rect.h, fRect.f);
},

renderConnector(context, fRect) {
    // connector
    var connectorColor = this.getStyle( fRect.f, 'connectorColor' );
    if (connectorColor) {
        context.fillStyle = connectorColor;
        var connectorThickness = this.getStyle( fRect.f, 'connectorThickness' );
        context.fillRect(
            fRect.rect.l, // left
            Math.round(fRect.rect.t+(fRect.rect.h-connectorThickness)/2), // top
            fRect.rect.w, // width
            connectorThickness
        );
    }
},

// draw both gaps and mismatches
_drawOverlappingMismatches(context, fRect, mismatches, fstart) {
    var block = fRect.viewInfo.block;
    var scale = block.scale;

    var charSize = this.getCharacterMeasurements( context );
    context.textBaseline = 'middle'; // reset to alphabetic (the default) after loop

    array.forEach( mismatches, function( mismatch ) {
        var start = fstart + mismatch.start;
        var end = fstart + mismatch.start + mismatch.length;

        var mRect = {
            h: (fRect.rect||{}).h || fRect.h,
            l: block.bpToX( start ),
            t: fRect.rect.t
        };
        mRect.w = Math.max( block.bpToX( end ) - mRect.l, 1 );

        if( mismatch.type == 'mismatch' ) {
            if(mismatch.base1 == mismatch.base2) {
                context.fillStyle = this.track.colorForBase( mismatch.type == 'deletion' ? 'deletion' : mismatch.base1 );
            } else {
                context.fillStyle = 'black';
            }
            context.fillRect( mRect.l, mRect.t, mRect.w, mRect.h );

            if( mRect.w >= charSize.w && mRect.h >= charSize.h-3 ) {
                context.font = this.config.style.mismatchFont;
                if(mismatch.base1 == mismatch.base2) {
                    context.fillStyle = 'black'
                    context.fillText( mismatch.base1, mRect.l+(mRect.w-charSize.w)/2+1, mRect.t+mRect.h/2 );
                } else if(scale >= 10) {
                    context.fillStyle = 'white'
                    context.fillText( mismatch.base1 + '/' +mismatch.base2, mRect.l+(mRect.w-charSize.w*2)/2+1, mRect.t+mRect.h/2 );
                }
            }
        }
    },this);

    context.textBaseline = 'alphabetic';
},

_defaultConfig() {
    return this._mergeConfigs(dojo.clone( this.inherited(arguments) ), {
        style: {
            connectorColor: AlignmentColoring.connectorColor,
            connectorThickness: 1,
            overlapColor: 'lightgrey',
            overlapStroke: 'grey',
        },
        strandInlay: false
    });
}

});
});

<commit_msg>Check for mismatches from one list that has nothing in the other and vice versa<commit_after>define([
    'dojo/_base/declare',
    'dojo/_base/array',
    'dojo/_base/lang',
    'JBrowse/View/FeatureGlyph/Alignment',
    'JBrowse/View/FeatureGlyph/AlignmentColoring',
    'JBrowse/Util'
],
function(
    declare,
    array,
    lang,
    Alignment,
    AlignmentColoring,
    Util
) {

return declare(Alignment, {

clearFeat(context, fRect) {
    if( this.track.displayMode != 'collapsed' )
        context.clearRect( Math.floor(fRect.l), fRect.t, Math.ceil(fRect.w), fRect.h );
},
renderFeature(context, fRect) {
    const f = fRect.f
    this.clearFeat(context, fRect)

    if (f.pairedFeature()) {
        this.renderConnector( context, fRect )
        this.renderSegments( context, fRect )
        if (fRect.w > 2) {
            if (fRect.viewInfo.scale > 0.2) {
                this._drawMismatches( context, fRect, this._getMismatches( f.read1 ), f.read1 )
                this._drawMismatches( context, fRect, this._getMismatches( f.read2 ), f.read2 )
            }
            else {
                this._drawMismatches( context, fRect, this._getSkipsAndDeletions( f.read1 ), f.read1 )
                this._drawMismatches( context, fRect, this._getSkipsAndDeletions( f.read2 ), f.read2 )
            }
        }
        const x1 = f.read1.get('start')
        const x2 = f.read1.get('end')
        const y1 = f.read2.get('start')
        const y2 = f.read2.get('end')
        if(Util.intersect(x1, x2, y1, y2)) {
            const s1 = x2 > y2 ? x1 : y1
            const s2 = x1 > y1 ? y2 : x2
            const block = fRect.viewInfo.block
            const l = block.bpToX(s1)
            const r = block.bpToX(s2)
            context.fillStyle = this.getStyle(f, 'overlapColor')
            context.strokeStyle = this.getStyle(f, 'overlapStroke')
            context.rect(
                l, // left
                fRect.rect.t,
                r-l, // width
                fRect.rect.h
            )
            context.fill();
            context.stroke()
            context.strokeStyle = null
            context.fillStyle = null
            var m1 = this._getMismatches( f.read1 );
            var m2 = this._getMismatches( f.read2 );
            if(!m1 && !m2) {
                return;
            } else {
                var mismatches = [];
                for(var i = 0; i < m1.length; i++) {
                    let foundMatching = false;
                    for(var j = 0; j < m2.length; j++) {
                        if(x1+m1[i].start == y1+m2[j].start && s1 < x1+m1[i].start && s2 > x1+m1[i].start) {
                            foundMatching = true
                            mismatches.push({ start: m1[i].start, base1: m1[i].base, base2: m2[j].base, type: 'mismatch', length: 1 });
                        }
                    }
                    if(m1[i].type == 'mismatch' && s1 < x1+m1[i].start && s2 > x1+m1[i].start && !foundMatching ) {
                        mismatches.push({ start: m1[i].start, base1: m1[i].base, base2: '-', type: 'mismatch', length: 1 });
                    }
                }
                if(mismatches.length !== 0) {
                    this._drawOverlappingMismatches(context, fRect, mismatches, x1)
                }
                mismatches = [];
                for(var i = 0; i < m2.length; i++) {
                    let foundMatching = false;
                    for(var j = 0; j < m1.length; j++) {
                        if(x1+m1[j].start == y1+m2[i].start && s1 < y1+m2[i].start && s2 > y1+m2[i].start) {
                            //    mismatches.push({ start: m2[i].start, base1: m2[i].base, base2: m1[j].base, type: 'mismatch', length: 1 });
                            //    would have been found in above loop also previous iteration
                            foundMatching = true
                        }
                    }
                    if(m2[i].type == 'mismatch' && s1 < y1+m2[i].start && s2 > y1+m2[i].start && !foundMatching) {
                        mismatches.push({ start: m2[i].start, base1: m2[i].base, base2: '-', type: 'mismatch', length: 1 });
                    }
                }
                if(mismatches.length !== 0) {
                    this._drawOverlappingMismatches(context, fRect, mismatches, y1)
                }
            }
        }
    } else {
        this.inherited(arguments)
    }
},

renderSegments(context, fRect) {
    this.renderBox(context, fRect.viewInfo, fRect.f.read1,  fRect.t, fRect.rect.h, fRect.f);
    this.renderBox(context, fRect.viewInfo, fRect.f.read2,  fRect.t, fRect.rect.h, fRect.f);
},

renderConnector(context, fRect) {
    // connector
    var connectorColor = this.getStyle( fRect.f, 'connectorColor' );
    if (connectorColor) {
        context.fillStyle = connectorColor;
        var connectorThickness = this.getStyle( fRect.f, 'connectorThickness' );
        context.fillRect(
            fRect.rect.l, // left
            Math.round(fRect.rect.t+(fRect.rect.h-connectorThickness)/2), // top
            fRect.rect.w, // width
            connectorThickness
        );
    }
},

// draw both gaps and mismatches
_drawOverlappingMismatches(context, fRect, mismatches, fstart) {
    var block = fRect.viewInfo.block;
    var scale = block.scale;

    var charSize = this.getCharacterMeasurements( context );
    context.textBaseline = 'middle'; // reset to alphabetic (the default) after loop

    array.forEach( mismatches, function( mismatch ) {
        var start = fstart + mismatch.start;
        var end = fstart + mismatch.start + mismatch.length;

        var mRect = {
            h: (fRect.rect||{}).h || fRect.h,
            l: block.bpToX( start ),
            t: fRect.rect.t
        };
        mRect.w = Math.max( block.bpToX( end ) - mRect.l, 1 );

        if( mismatch.type == 'mismatch' ) {
            if(mismatch.base1 == mismatch.base2) {
                context.fillStyle = this.track.colorForBase( mismatch.type == 'deletion' ? 'deletion' : mismatch.base1 );
            } else {
                context.fillStyle = 'black';
            }
            context.fillRect( mRect.l, mRect.t, mRect.w, mRect.h );

            if( mRect.w >= charSize.w && mRect.h >= charSize.h-3 ) {
                context.font = this.config.style.mismatchFont;
                if(mismatch.base1 == mismatch.base2) {
                    context.fillStyle = 'black'
                    context.fillText( mismatch.base1, mRect.l+(mRect.w-charSize.w)/2+1, mRect.t+mRect.h/2 );
                } else if(scale >= 10) {
                    context.fillStyle = 'white'
                    context.fillText( mismatch.base1 + '/' +mismatch.base2, mRect.l+(mRect.w-charSize.w*2)/2+1, mRect.t+mRect.h/2 );
                }
            }
        }
    },this);

    context.textBaseline = 'alphabetic';
},

_defaultConfig() {
    return this._mergeConfigs(dojo.clone( this.inherited(arguments) ), {
        style: {
            connectorColor: AlignmentColoring.connectorColor,
            connectorThickness: 1,
            overlapColor: 'lightgrey',
            overlapStroke: 'grey',
        },
        strandInlay: false
    });
}

});
});

<|endoftext|>