<commit_before>define([
    'backbone',
    'underscore',
    'find/app/util/model-any-changed-attribute-listener',
    'find/app/util/topic-map-view',
    'i18n!find/nls/bundle',
    'find/app/configuration',
    'text!find/templates/app/page/search/results/entity-topic-map-view.html',
    'text!find/templates/app/page/loading-spinner.html',
    'iCheck',
    'slider/bootstrap-slider'
], function(Backbone, _, addChangeListener, TopicMapView, i18n, configuration, template, loadingTemplate) {

    'use strict';

    var loadingHtml = _.template(loadingTemplate)({i18n: i18n, large: true});

    /**
     * @readonly
     * @enum {String}
     */
    var ViewState = {
        LOADING: 'LOADING',
        ERROR: 'ERROR',
        EMPTY: 'EMPTY',
        MAP: 'MAP'
    };

    var CLUSTER_MODE = 'docsWithPhrase';

    return Backbone.View.extend({
        template: _.template(template),

        events: {
            'slideStop .speed-slider': function(event) {
                var maxResults = event.value;

                this.model.set('maxResults', maxResults);
            }
        },

        initialize: function(options) {
            this.entityCollection = options.entityCollection;
            this.queryModel = options.queryModel;

            this.topicMap = new TopicMapView({
                clickHandler: options.clickHandler
            });

            var viewState;

            if (this.entityCollection.currentRequest) {
                viewState = ViewState.LOADING;
            } else {
                viewState = this.entityCollection.isEmpty() ? ViewState.EMPTY : ViewState.MAP;
            }

            this.viewModel = new Backbone.Model({
                state: viewState
            });

            this.model = new Backbone.Model({
                maxCount: 10
            });

            this.listenTo(this.model, 'change:maxResults', this.fetchRelatedConcepts);

            this.listenTo(this.entityCollection, 'sync', function() {
                this.viewModel.set('state', this.entityCollection.isEmpty() ? ViewState.EMPTY : ViewState.MAP);
                this.updateTopicMapData();
                this.update();
            });

            this.listenTo(this.entityCollection, 'request', function() {
                this.viewModel.set('state', ViewState.LOADING);
            });

            this.listenTo(this.entityCollection, 'error', function(collection, xhr) {
                // Status of zero means the request has been aborted
                this.viewModel.set('state', xhr.status === 0 ? ViewState.LOADING : ViewState.ERROR);
            });

            this.listenTo(this.viewModel, 'change', this.updateViewState);

            this.updateTopicMapData();
        },

        update: function() {
            // If the view is not visible, update will be called again if the user switches to this tab
            if (this.$el.is(':visible')) {
                this.topicMap.draw();
            }
        },

        updateTopicMapData: function() {
            var data = _.chain(this.entityCollection.groupBy('cluster'))
                // Order the concepts in each cluster
                .map(function (cluster) {
                    return _.sortBy(cluster, function (model) {
                        return -model.get(CLUSTER_MODE);
                    });
                })
                // For each related concept give the name and size
                .map(function(cluster) {
                    return cluster.map(function (model) {
                        return {name: model.get('text'), size: model.get(CLUSTER_MODE)};
                    })
                })
                // Give each cluster a name (first concept in list), total size and add all concepts to the children attribute to create the topic map double level
                .map(function(cluster) {
                    var size = _.chain(cluster)
                        .pluck('size')
                        .reduce(function(a,b) {return a + b;})
                        .value();

                    return {
                        name: cluster[0].name,
                        size: size,
                        children: cluster
                    };
                })
                .sortBy(function(clusterNode) {
                    return -clusterNode.size;
                })
                .value();

            this.topicMap.setData(data);
        },

        updateViewState: function() {
            var state = this.viewModel.get('state');
            this.topicMap.$el.toggleClass('hide', state !== ViewState.MAP);
            this.$('.entity-topic-map-error').toggleClass('hide', state !== ViewState.ERROR);
            this.$('.entity-topic-map-empty').toggleClass('hide', state !== ViewState.EMPTY);
            this.$('.entity-topic-map-loading').toggleClass('hide', state !== ViewState.LOADING);
        },

        fetchRelatedConcepts: function() {
            if (this.queryModel.get('queryText') && this.queryModel.get('indexes').length !== 0) {
                var data = {
                    databases: this.queryModel.get('indexes'),
                    queryText: this.queryModel.get('queryText'),
                    fieldText: this.queryModel.get('fieldText'),
                    minDate: this.queryModel.getIsoDate('minDate'),
                    maxDate: this.queryModel.getIsoDate('maxDate'),
                    minScore: this.queryModel.get('minScore'),
                    stateTokens: this.queryModel.get('stateMatchIds'),
                    maxResults: this.model.get('maxResults')
                };

                this.entityCollection.fetch({data: data});
            }
        },

        render: function() {
            this.$el.html(this.template({
                i18n: i18n,
                loadingHtml: loadingHtml,
                cid: this.cid
            }));

            this.$('.speed-slider')
                .slider({
                    id: this.cid + '-speed-slider',
                    min: 50,
                    max: configuration().topicMapMaxResults,
                    value: 50
                });

            this.topicMap.setElement(this.$('.entity-topic-map')).render();
            this.update();
            this.updateViewState();
        }
    });

});

<commit_msg>[FIND-339] updated the inital value [rev Alex Scown]<commit_after>define([
    'backbone',
    'underscore',
    'find/app/util/model-any-changed-attribute-listener',
    'find/app/util/topic-map-view',
    'i18n!find/nls/bundle',
    'find/app/configuration',
    'text!find/templates/app/page/search/results/entity-topic-map-view.html',
    'text!find/templates/app/page/loading-spinner.html',
    'iCheck',
    'slider/bootstrap-slider'
], function(Backbone, _, addChangeListener, TopicMapView, i18n, configuration, template, loadingTemplate) {

    'use strict';

    var loadingHtml = _.template(loadingTemplate)({i18n: i18n, large: true});

    /**
     * @readonly
     * @enum {String}
     */
    var ViewState = {
        LOADING: 'LOADING',
        ERROR: 'ERROR',
        EMPTY: 'EMPTY',
        MAP: 'MAP'
    };

    var CLUSTER_MODE = 'docsWithPhrase';

    return Backbone.View.extend({
        template: _.template(template),

        events: {
            'slideStop .speed-slider': function(event) {
                var maxResults = event.value;

                this.model.set('maxResults', maxResults);
            }
        },

        initialize: function(options) {
            this.entityCollection = options.entityCollection;
            this.queryModel = options.queryModel;

            this.topicMap = new TopicMapView({
                clickHandler: options.clickHandler
            });

            var viewState;

            if (this.entityCollection.currentRequest) {
                viewState = ViewState.LOADING;
            } else {
                viewState = this.entityCollection.isEmpty() ? ViewState.EMPTY : ViewState.MAP;
            }

            this.viewModel = new Backbone.Model({
                state: viewState
            });

            this.model = new Backbone.Model({
                maxCount: 10
            });

            this.listenTo(this.model, 'change:maxResults', this.fetchRelatedConcepts);

            this.listenTo(this.entityCollection, 'sync', function() {
                this.viewModel.set('state', this.entityCollection.isEmpty() ? ViewState.EMPTY : ViewState.MAP);
                this.updateTopicMapData();
                this.update();
            });

            this.listenTo(this.entityCollection, 'request', function() {
                this.viewModel.set('state', ViewState.LOADING);
            });

            this.listenTo(this.entityCollection, 'error', function(collection, xhr) {
                // Status of zero means the request has been aborted
                this.viewModel.set('state', xhr.status === 0 ? ViewState.LOADING : ViewState.ERROR);
            });

            this.listenTo(this.viewModel, 'change', this.updateViewState);

            this.updateTopicMapData();
        },

        update: function() {
            // If the view is not visible, update will be called again if the user switches to this tab
            if (this.$el.is(':visible')) {
                this.topicMap.draw();
            }
        },

        updateTopicMapData: function() {
            var data = _.chain(this.entityCollection.groupBy('cluster'))
                // Order the concepts in each cluster
                .map(function (cluster) {
                    return _.sortBy(cluster, function (model) {
                        return -model.get(CLUSTER_MODE);
                    });
                })
                // For each related concept give the name and size
                .map(function(cluster) {
                    return cluster.map(function (model) {
                        return {name: model.get('text'), size: model.get(CLUSTER_MODE)};
                    })
                })
                // Give each cluster a name (first concept in list), total size and add all concepts to the children attribute to create the topic map double level
                .map(function(cluster) {
                    var size = _.chain(cluster)
                        .pluck('size')
                        .reduce(function(a,b) {return a + b;})
                        .value();

                    return {
                        name: cluster[0].name,
                        size: size,
                        children: cluster
                    };
                })
                .sortBy(function(clusterNode) {
                    return -clusterNode.size;
                })
                .value();

            this.topicMap.setData(data);
        },

        updateViewState: function() {
            var state = this.viewModel.get('state');
            this.topicMap.$el.toggleClass('hide', state !== ViewState.MAP);
            this.$('.entity-topic-map-error').toggleClass('hide', state !== ViewState.ERROR);
            this.$('.entity-topic-map-empty').toggleClass('hide', state !== ViewState.EMPTY);
            this.$('.entity-topic-map-loading').toggleClass('hide', state !== ViewState.LOADING);
        },

        fetchRelatedConcepts: function() {
            if (this.queryModel.get('queryText') && this.queryModel.get('indexes').length !== 0) {
                var data = {
                    databases: this.queryModel.get('indexes'),
                    queryText: this.queryModel.get('queryText'),
                    fieldText: this.queryModel.get('fieldText'),
                    minDate: this.queryModel.getIsoDate('minDate'),
                    maxDate: this.queryModel.getIsoDate('maxDate'),
                    minScore: this.queryModel.get('minScore'),
                    stateTokens: this.queryModel.get('stateMatchIds'),
                    maxResults: this.model.get('maxResults')
                };

                this.entityCollection.fetch({data: data});
            }
        },

        render: function() {
            this.$el.html(this.template({
                i18n: i18n,
                loadingHtml: loadingHtml,
                cid: this.cid
            }));

            this.$('.speed-slider')
                .slider({
                    id: this.cid + '-speed-slider',
                    min: 50,
                    max: configuration().topicMapMaxResults,
                    value: 300
                });

            this.topicMap.setElement(this.$('.entity-topic-map')).render();
            this.update();
            this.updateViewState();
        }
    });

});

<|endoftext|>


<commit_before>// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// Genetic Algorithm, Evolving Shakespeare

// A class to describe a population of virtual organisms
// In this case, each organism is just an instance of a DNA object

function Population(p, m, num) {

	this.timeInitial = new Date().getTime();
	this.time;
	this.updateTime = function() {
		this.time = new Date(new Date().getTime() - this.timeInitial);

		document.querySelector("#time").innerHTML = this.time.getMinutes() + ":" + this.time.getSeconds() + ":" + this.time.getMilliseconds();

		if (this.time.getTime() < 5000)
			document.querySelector("#status").innerHTML = "Procurando";
		else if (this.time.getTime() < 10000)
			document.querySelector("#status").innerHTML = "Procurando.";
		else if (this.time.getTime() < 15000)
			document.querySelector("#status").innerHTML = "Procurando..";
		else if (this.time.getTime() < 20000)
			document.querySelector("#status").innerHTML = "Procurando...";
		else if (this.time.getTime() < 25000)
			document.querySelector("#status").innerHTML = "Procurando....";

		if (this.time.getTime() > 30000)
			document.querySelector("#status").innerHTML = "Procurando....
Já se passou um bom tempo, né?!";

		if (this.time.getTime() > 60000)
			document.querySelector("#status").innerHTML = "Procurando....
Já se passou um bom tempo, né?!
Se o resultado atual não for satisfatório, tente recomeçar =)";
		//console.log(this.time.getHours(), ":", this.time.getMinutes(), ":", this.time.getSeconds(), ":", this.time.getMilliseconds());
	}

	this.population;                   // Array to hold the current population
	this.matingPool;                   // ArrayList which we will use for our "mating pool"
	this.generations = 0;              // Number of generations
	this.searchSteps = p.length * p[0].length * 4;
	this.limitGenerations = this.searchSteps;
	this.finished = false;             // Are we finished evolving?
	this.font = p;                     // Font matrix
	this.mutationRate = m;             // Mutation rate
	//this.perfectScore = 1;
	this.everPhrase = "";
	this.everRecord = 0.0;
	this.everRecordSelect = 0;
	this.everRecordCovereds = 0;
	this.everRecordUseless = 0;

	this.best = [];

	this.population = [];
	for (let i = 0; i < num; i++) {
		this.population[i] = new DNA();
	}
	this.matingPool = [];

	// Fill our fitness array with a value for every member of the population
	this.calcFitness = function() {
		for (let i = 0; i < this.population.length; i++) {
			this.population[i].reduceUseless();
			this.population[i].calcFitness(font);
		}
	}
	this.calcFitness();

	// Create a new generation
	this.generate = function() {

		// Calculate the probabilits of all elements
		let sumFitness = 0;
		for (let i = 0; i < this.population.length; i++) {
			sumFitness += this.population[i].fitness;
		}
		for (let i = 0; i < this.population.length; i++) {
			this.population[i].prob = this.population[i].fitness / sumFitness;
		}

		// Generate the children
		let newPopulation = [];
		for (let i = 0; i < this.population.length; i++) {
			let partnerA = this.pickOne();
			let partnerB = this.pickOne();
			let child = partnerA.crossover(partnerB);
			child.mutate(this.mutationRate);
			newPopulation.push(child);
		}
		this.population = newPopulation;

		this.generations++;
	}

	this.pickOne = function() {
		let index = 0;
		let r = random(1);

		while (r > 0) {
			r -= this.population[index].prob;
			index++;
		}
		index--;
		return this.population[index];
	}

	this.getBest = function() {
		//return this.best;
		return this.everPhrase;
	}

	// Compute the current "most fit" member of the population
	this.evaluate = function() {
		let worldrecord = 0.0;
		let index = 0;
		for (let i = 0; i < this.population.length; i++) {
			if (this.population[i].fitness > worldrecord) {
				index = i;
				worldrecord = this.population[i].fitness;
			}
		}
		if (worldrecord > this.everRecord) {
			this.everPhrase = this.population[index].getPhrase();
			this.everRecord = worldrecord;
			this.everRecordSelect = this.population[index].calcSelect();
			this.everRecordCovereds = this.population[index].calcCovereds();
			this.everRecordUseless = 0;//this.population[index].calcUseless();

			this.limitGenerations += this.generations + this.searchSteps;

			newBetter(font, this.everPhrase, this.everRecordSelect, {t: this.everRecordCovereds, a: wantCovered});
		}

		this.best = this.population[index].getPhrase();
		//if (worldrecord === this.perfectScore) {
		//if (this.generations >= this.limitGenerations) {
		//	this.finished = true;
		//}
	}

	this.isFinished = function() {
		return this.finished;
	}

	this.getGenerations = function() {
		return this.generations;
	}

	// Compute average fitness for the population
	this.getAverageFitness = function() {
		let total = 0;
		for (let i = 0; i < this.population.length; i++) {
			total += this.population[i].fitness;
		}
		return total / (this.population.length);
	}

	this.allPhrases = function() {
		let everything = "";

		let displayLimit = min(this.population.length,50);

		for (let i = 0; i < displayLimit; i++) {
			everything += this.population[i].getPhrase() + "
";
		}
		return everything;
	}
}

<commit_msg>Removido variáveis de parada<commit_after>// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// Genetic Algorithm, Evolving Shakespeare

// A class to describe a population of virtual organisms
// In this case, each organism is just an instance of a DNA object

function Population(p, m, num) {

	this.timeInitial = new Date().getTime();
	this.time;
	this.updateTime = function() {
		this.time = new Date(new Date().getTime() - this.timeInitial);

		document.querySelector("#time").innerHTML = this.time.getMinutes() + ":" + this.time.getSeconds() + ":" + this.time.getMilliseconds();

		if (this.time.getTime() < 5000)
			document.querySelector("#status").innerHTML = "Procurando";
		else if (this.time.getTime() < 10000)
			document.querySelector("#status").innerHTML = "Procurando.";
		else if (this.time.getTime() < 15000)
			document.querySelector("#status").innerHTML = "Procurando..";
		else if (this.time.getTime() < 20000)
			document.querySelector("#status").innerHTML = "Procurando...";
		else if (this.time.getTime() < 25000)
			document.querySelector("#status").innerHTML = "Procurando....";

		if (this.time.getTime() > 30000)
			document.querySelector("#status").innerHTML = "Procurando....
Já se passou um bom tempo, né?!";

		if (this.time.getTime() > 60000)
			document.querySelector("#status").innerHTML = "Procurando....
Já se passou um bom tempo, né?!
Se o resultado atual não for satisfatório, tente recomeçar =)";
		//console.log(this.time.getHours(), ":", this.time.getMinutes(), ":", this.time.getSeconds(), ":", this.time.getMilliseconds());
	}

	this.population;                   // Array to hold the current population
	this.matingPool;                   // ArrayList which we will use for our "mating pool"
	this.generations = 0;              // Number of generations
	this.finished = false;             // Are we finished evolving?
	this.font = p;                     // Font matrix
	this.mutationRate = m;             // Mutation rate
	//this.perfectScore = 1;
	this.everPhrase = "";
	this.everRecord = 0.0;
	this.everRecordSelect = 0;
	this.everRecordCovereds = 0;
	this.everRecordUseless = 0;

	this.best = [];

	this.population = [];
	for (let i = 0; i < num; i++) {
		this.population[i] = new DNA();
	}
	this.matingPool = [];

	// Fill our fitness array with a value for every member of the population
	this.calcFitness = function() {
		for (let i = 0; i < this.population.length; i++) {
			this.population[i].reduceUseless();
			this.population[i].calcFitness(font);
		}
	}
	this.calcFitness();

	// Create a new generation
	this.generate = function() {

		// Calculate the probabilits of all elements
		let sumFitness = 0;
		for (let i = 0; i < this.population.length; i++) {
			sumFitness += this.population[i].fitness;
		}
		for (let i = 0; i < this.population.length; i++) {
			this.population[i].prob = this.population[i].fitness / sumFitness;
		}

		// Generate the children
		let newPopulation = [];
		for (let i = 0; i < this.population.length; i++) {
			let partnerA = this.pickOne();
			let partnerB = this.pickOne();
			let child = partnerA.crossover(partnerB);
			child.mutate(this.mutationRate);
			newPopulation.push(child);
		}
		this.population = newPopulation;

		this.generations++;
	}

	this.pickOne = function() {
		let index = 0;
		let r = random(1);

		while (r > 0) {
			r -= this.population[index].prob;
			index++;
		}
		index--;
		return this.population[index];
	}

	this.getBest = function() {
		//return this.best;
		return this.everPhrase;
	}

	// Compute the current "most fit" member of the population
	this.evaluate = function() {
		let worldrecord = 0.0;
		let index = 0;
		for (let i = 0; i < this.population.length; i++) {
			if (this.population[i].fitness > worldrecord) {
				index = i;
				worldrecord = this.population[i].fitness;
			}
		}
		if (worldrecord > this.everRecord) {
			this.everPhrase = this.population[index].getPhrase();
			this.everRecord = worldrecord;
			this.everRecordSelect = this.population[index].calcSelect();
			this.everRecordCovereds = this.population[index].calcCovereds();
			this.everRecordUseless = 0;//this.population[index].calcUseless();

			newBetter(font, this.everPhrase, this.everRecordSelect, {t: this.everRecordCovereds, a: wantCovered});
		}

		this.best = this.population[index].getPhrase();
	}

	this.isFinished = function() {
		return this.finished;
	}

	this.getGenerations = function() {
		return this.generations;
	}

	// Compute average fitness for the population
	this.getAverageFitness = function() {
		let total = 0;
		for (let i = 0; i < this.population.length; i++) {
			total += this.population[i].fitness;
		}
		return total / (this.population.length);
	}

	this.allPhrases = function() {
		let everything = "";

		let displayLimit = min(this.population.length,50);

		for (let i = 0; i < displayLimit; i++) {
			everything += this.population[i].getPhrase() + "
";
		}
		return everything;
	}
}

<|endoftext|>


<commit_before>/**
 * @ngdoc object
 * @name anol.layer.StaticGeoJSON
 *
 * @param {Object} options AnOl Layer options
 * @param {Object} options.olLayer Options for ol.layer.Vector
 * @param {Object} options.olLayer.source Options for ol.source.Vector
 * @param {Object} options.olLayer.source.url Url to GeoJSON
 * @param {String} options.olLayer.source.dataProjection Projection if GeoJSON
 *
 * @description
 * Inherits from {@link anol.layer.Layer anol.layer.Layer}.
 */

import FeatureLayer from './feature.js';

import GML2 from 'ol/format/GML2';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';

import VectorSource from 'ol/source/Vector';

class GMLLayer extends FeatureLayer {

    constructor(_options) {
        if(_options === false) {
            super();
            return;
        }
        // TODO use openlayers gml filter
        if (_options.filter) {
            var filter = '';

            if (!angular.isArray(_options.filter.literal)) {
                _options.filter.literal = [_options.filter.literal];
            }

            angular.forEach(_options.filter.literal, function(literal) {
                filter +=
                        '<PropertyIsEqualTo>' +
                            '<PropertyName>' + _options.filter.propertyName +'</PropertyName>'+
                            '<Literal>'+ literal +'</Literal>'+
                        '</PropertyIsEqualTo>';
            })
            if (angular.isDefined(_options.filter.filterType)) {
                filter =
                    '<Filter>'+
                        '<'+_options.filter.filterType + '>' +
                            filter +
                        '</'+ _options.filter.filterType +'>'+
                    '</Filter>';
            } else {
                filter = '<Filter>'+ filter + '</Filter>';
            }
            _options.olLayer.source.url = _options.olLayer.source.url + 'FILTER=' + filter;
        }

        var defaults = {
            olLayer: {
                source: {
                    format: new GML2()
                },
                style: new Style({
                    stroke: new Stroke({
                        color: 'rgba(255,0,0,1)',
                        width: 1
                    }),
                    fill: new Fill({
                        color: 'rgba(255,0,0,0.3)'
                    })
                })
            }
        };
        var options = $.extend(true, {}, defaults, _options);
        super(options);
        this.method = options.method || 'GET';
        this.CLASS_NAME = 'anol.layer.GML';
    }

    _createSourceOptions(srcOptions) {
        var self = this;
        srcOptions.loader = function() {
            self.loader(
                srcOptions.url
            );
        };
        return super._createSourceOptions(srcOptions);
    }

    loader(url) {
        var self = this;
        $.ajax({
            method: this.method,
            url: url
        }).done(function(response) {
            self.responseHandler(response);
        });
    }
    responseHandler(response) {
        var self = this;
        var sourceFeatures = self.olLayer.getSource().getFeatures();
        for(var i = 0; i < sourceFeatures.length; i++) {
            self.olLayer.getSource().removeFeature(sourceFeatures[i]);
        }

        var format = new GML2();
        var features = format.readFeatures(response);
        self.olLayer.getSource().addFeatures(features);
    }
}

export default GMLLayer;
<commit_msg>gml: support wfs request with post<commit_after>/**
 * @ngdoc object
 * @name anol.layer.StaticGeoJSON
 *
 * @param {Object} options AnOl Layer options
 * @param {Object} options.olLayer Options for ol.layer.Vector
 * @param {Object} options.olLayer.source Options for ol.source.Vector
 * @param {Object} options.olLayer.source.url Url to GeoJSON
 * @param {String} options.olLayer.source.dataProjection Projection if GeoJSON
 *
 * @description
 * Inherits from {@link anol.layer.Layer anol.layer.Layer}.
 */

import FeatureLayer from './feature.js';

import GML2 from 'ol/format/GML2';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';

import VectorSource from 'ol/source/Vector';

class GMLLayer extends FeatureLayer {

    constructor(_options) {
        if(_options === false) {
            super();
            return;
        }
        // TODO use openlayers gml filter
        if (_options.filter) {
            var filter = '';

            if (!angular.isArray(_options.filter.literal)) {
                _options.filter.literal = [_options.filter.literal];
            }

            angular.forEach(_options.filter.literal, function(literal) {
                filter +=
                        '<PropertyIsEqualTo>' +
                            '<PropertyName>' + _options.filter.propertyName +'</PropertyName>'+
                            '<Literal>'+ literal +'</Literal>'+
                        '</PropertyIsEqualTo>';
            })
            if (angular.isDefined(_options.filter.filterType)) {
                filter =
                    '<Filter>'+
                        '<'+_options.filter.filterType + '>' +
                            filter +
                        '</'+ _options.filter.filterType +'>'+
                    '</Filter>';
            } else {
                filter = '<Filter>'+ filter + '</Filter>';
            }
            _options.olLayer.source.filter = filter;
        }

        var defaults = {
            olLayer: {
                source: {
                    format: new GML2()
                },
                style: new Style({
                    stroke: new Stroke({
                        color: 'rgba(255,0,0,1)',
                        width: 1
                    }),
                    fill: new Fill({
                        color: 'rgba(255,0,0,0.3)'
                    })
                })
            }
        };
        var options = $.extend(true, {}, defaults, _options);
        super(options);
        this.method = options.method || 'GET';
        this.CLASS_NAME = 'anol.layer.GML';
    }

    _createSourceOptions(srcOptions) {
        var self = this;
        srcOptions.loader = function() {
            self.loader(
                srcOptions.url, srcOptions.params, srcOptions.filter
            );
        };
        return super._createSourceOptions(srcOptions);
    }

    loader(url, params, filter) {
        var self = this;
        if (this.method === 'GET') {
            url = url + params + '&FILTER=' + filter;
            $.ajax({
                method: this.method,
                url: url
            }).done(function(response) {
                self.responseHandler(response);
            });
        } else {
            var data = JSON.parse('{"' + params.replace(/&/g, '","').replace(/=/g,'":"') + '"}',
                function(key, value) { return key==="" ? value:decodeURIComponent(value) })
            data.FILTER = filter;
            $.ajax({
                method: this.method,
                url: url,
                data: data,
            }).done(function(response) {
                self.responseHandler(response);
            });
        }
    }
    responseHandler(response) {
        var self = this;
        var sourceFeatures = self.olLayer.getSource().getFeatures();
        for(var i = 0; i < sourceFeatures.length; i++) {
            self.olLayer.getSource().removeFeature(sourceFeatures[i]);
        }

        var format = new GML2();
        var features = format.readFeatures(response);
        self.olLayer.getSource().addFeatures(features);
    }
}

export default GMLLayer;
<|endoftext|>


<commit_before>/**
 * https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/StyleSheet.js
 */
const StyleSheet = {
  create(styles) {
    return styles;
  },
};

module.exports = StyleSheet;
<commit_msg>Add StyleSheet.flatten<commit_after>/**
 * https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/StyleSheet.js
 */
const StyleSheet = {
  create(styles) {
    return styles;
  },
  flatten(styles) {
    return styles;
  }
};

module.exports = StyleSheet;
<|endoftext|>


<commit_before>/*************************************************************************
 * NODE.JS SCRIPT TO POPULATE A MONGODB 'fnck' collection from a tab-    *
 * separated text file supplied by the customer.                         *
 * 2014-03-23                                                            *
 *                                                                       *
 * To start the script, use this command line in a shell window:         *
 * node populate_all_image_credits_newdb_mongodb_pho_test.js startline end
 *                                                                       *
 * for example                                                           *
 *                                                                       *
 * node populate_all_image_credits_newdb_mongodb_pho_test.js 1 200       *
 *                                                                       *
 * Tells the script to start processing at line 1 and terminate          *
 * processing at line 200. Depending on your system and available memory,*
 * 200 open file descriptors at one time may be too many to have, so     *
 * process fewer lines per pass.                                         *
 *                                                                       *
 * The script processes in small passes to account for system overhead in*
 * using up too many file descriptors.                                   *
 * ----------------------------------------------------------------------*
 * 2014-03-28                                                            *
 * CUSTOMER-SUPPLIED FILE MAY NEED REFORMATTING PRIOR TO USE             *
 * ----------------------------------------------------------------------*
 * Read the converted_New_Names_2014-03-08_FileNamesandCaptionKeys.txt   *
 * file as a readable stream.                                            *
 * The input file has been reformatted from a Microsoft Windows formatted*
 * file containing carriage returns and line feed characters '\r\n' to a *
 * Unix style file with only '\n' terminating each line. Also, empty tab-*
 * separated lines in the format '\t\t\t\t\n' appended to the end of the *
 * original source input file were removed.                              *
 * The goal in this script is to extract the filename contained in each  *
 * row of the source file and append the extension .txt (period,         *
 * character t, character x, character t) to this name. Then read this   *
 * *.txt file with fs.read. Parse this file and extract the              *
 * "Photographer" field within the file. Next, update the matching       *
 * document in the 'fnck' collection of the 'sgtypdb2' database          *
 * to add this new field to the document: 'photographer'.                *
 *-----------------------------------------------------------------------*
 * FOR TESTING PURPOSES, the 'fnck' collection has been copied to the    *
 * 'test' database using mongodump and then mongorestore.                *
 *-----------------------------------------------------------------------*
 * The ultimate reason for updating the fnck collection in this way is to*
 * allow one document to be used as the source data to populate most of  *
 * the eventual application web page.                                    *
 *                                                                       *
 *------------------------- S T E P S -----------------------------------*
 *                                                                       *
 * 1. Extract filename from the current input line of the                *
 *    'converted_New_Names_2014-03-08_FileNamesandCaptionKeys.txt' file. *
 *    Example: _8758450914_o                                             *
 * 2. Save this filename prefix to a multidimensional array.             *
 * 3. Append a '.txt' extension to the extracted filename.               *
 *    _8758450914_o.txt                                                  *
 * 4. Save the [filename].txt element to the same multimensional array as*
 *    in step 2. The array element now looks like                        *
 *    [["_8758450914_o", "_8758450914_o.txt",...]]                       *
 * 5. Iterate to the next line of the FilenamesandCaptionKeys input file *
 *    listed in Step 1. Repeat steps 1-4, building up the multi-         *
 *    dimensional array with the elements for the next line of the input *
 *    file. So element #1 will look like this:                           *
 *    [["_8758450914_o", "_8758450914_o.txt",...],                       *
 *     ["_9758450914_o", "_9758450914_o.txt",...]...]                    *
 *    Do this in passes of 25 to 200 files.                              *
 *                                                                       *
 * 6. Now, working from the very beginning of the multidimensional array *
 *    that we have built, attempt to open a file matching the            *
 *    Filename.txt string that is at that index in our array. Example:   *
 *    open '_8758450914_o.txt'                                           *
 * 7. Attempt to read the file if the open succeeds.                     *
 *    read '_8758450914_o.txt'                                           *
 * 8. Find the line that begins with the word "Photographer : "          *
 * 9. Extract the name of the photographer.                              *
 *    peter.clark                                                        *
 *10. Add the photographer name to the multidimensional array as in step *
 *    4. The array now looks like:                                       *
 *    [["_8758450914_o", "_8758450914_o.txt", "peter.clark"],            *
 *    ["_9758450914_o", "_9758450914_o.txt",...]...]                     *
 *11. Iterate through all the array elements that need the photographer  *
 *    name added to the associated filename.txt string.                  *
 *12. With 25 to 200 filenames ready in the array, open a MongoDB        *
 *    connection to the 'fnck' collection of either the 'test' or        *
 *    the 'sgtypdb2' databases. At first use the 'test' database when    *
 *    testing application logic.                                         *
 *13. This script will attempt to update each matching document within   *
 *    the 'fnck' collection of the 'sgtypdb2' database with the          *
 *    photographer information just extracted from the text files.       *
 *    It expects that these fields will be added to each matching        *
 *    document and that these fields will be new fields for each matching*
 *    document. That is, the script does not try to try to update these  *
 *    fields in the matching document because they do not exist yet.     *
 *-----------------------------------------------------------------------*
 * Target database engine: MONGODB 2.4.9                                 *
 * Required node.js module: mongodb                                      *
 * It can take time for this script to complete all the inserts for the  *
 * fnck collection. If you abort the script by pressing CTRL-D or        *
 * CTRL-C the database inserts will most likely not complete.            *
 ************************************************************************/
var fs = require('fs');
var totalLines = 0
var j1 = 0              // first dimenion of im_array
var j2 = 0              // second dimension of im_array
var stream              // for use in parsing for photographer name
var startLn = 0         // the starting line for this processing "pass"
var endLn = 0           // the ending line for this processing "pass"
var actLines = 0        // the actual number of text lines that readLines has found
var webRows = 0         // count of web page row numbers, starting from 1
var array_lines = 0     // the number of array iterations we need

/* Were any arguments passed in? Exit if none found */

if (process.argv.length < 3) {
    console.log('You must pass in the starting and ending line numbers as arguments to this script')
    console.log('The number of arguments found were ' + process.argv.length)
    console.log('Terminating processing')
    process.exit(1)
}

/* Get the command line arguments passed to this script */

process.argv.forEach(function(val, index, array) {
    console.log(index + ': ' + val);
    if (index === 2) {
        startLn = val
        webRows = val
    }
    if (index == 3) {
        endLn = val
    }
});

array_lines = endLn - startLn      //compute number of iterations

console.log('startLn is ' + startLn)
console.log('endLn is ' + endLn)
console.log('Number of iterations in the array will be ' + array_lines + '\n')

/* Set up an [lines being processed] x 3 array */

var im_array = new Array(array_lines)       // multidimensional array of image names, file names, photographer names
for(i = 0; i < im_array.length; i++) {
    im_array[i] = new Array(3);
}

var input = fs.createReadStream('/Users/bobc/Documents/sgntyp_renamed_files_2014-03-08/converted_New_Names_2014-03-08_FileNamesandCaptionKeys.txt');

readLines(input, func);
get_credits()
/*
 * Wait 46 seconds to let other processes complete, then build
 * the summary web page. We want to pass it the starting line number value.
 */
setTimeout(function () {
    do_array_print()
},46000)

function readLines(input, func) {
      var remaining = '';

      input.on('data', function(data) {
      remaining += data;
      var index1 = remaining.indexOf('\n');
      while (index1 > -1) {
          var line = remaining.slice(0, index1);
          remaining = remaining.slice(index1 + 1);
          totalLines += 1
          // Skip the header line.
          if (totalLines === 1) {
             index1 = remaining.indexOf('\n')
             continue
          }
          actLines += 1                           // actual number of content lines minus header line

          //discover if the line we are on is the line to start processing
          if (actLines < startLn) {
              index1 = remaining.indexOf('\n')
              continue
          }

          //discover if the line we are on is past the ending line number
          //that we want to process for this pass
          if (actLines > endLn) {
              index1 = remaining.indexOf('\n')
              continue
          }

          index1 = remaining.indexOf('\n')        // recompute value of index1
          var tbbl = line.indexOf('\t')           // find the index of the tab character
          if (line[0] === '\"') {                 // check to see if the filename string is quoted
              var fn1 = line.slice(1,(tbbl-1))    //skip the quotes
          } else {
              var fn1 = line.slice(0, tbbl)        // save the file name string up to the tab character
          }
          im_array[j1][j2].push(fn1)              // save the filename string without an extension
          fn1 = fn1 + '.txt'                      // append the .txt extension
          j2++                                    // bump to next element in j1
          im_array[j1][j2].push(fn1)              // push this onto the array
          j2 = 0                                  // reset j2
          j1++                                    // set up the next array

  }
})

  input.on('end', function() {
    if (remaining.length > 0) {
      func(remaining);
    }
    console.log('\nTotal number of lines processed including input header row: ' + totalLines + '\n')

  })
    }
/*
 * At this point, we have extracted all the filenames from the source TSV document and these
 * are waiting for us in the array im_array. The array now looks like this:
 *
 * [["_8758450914_o", "_8758450914_o.txt", ...],["_9758450914_o", "_9758450914_o.txt",...]...]
 *
 * For each file name in the array[j1][j2], we want to call a function that will
 * create a readstream of that file's contents, and parse out the
 * photographer's name. The photographer name would be put into im_array[j1][2].
 *
 * After all the file names are processed, we can update the 'fnck' collection documents with
 * corresponding photographer information.
 *
 */
function get_credits() {

    setTimeout(function () {
        process.stdout.write('\nProcessing files...\n')
        for(var pj = 0; pj < im_array.length; pj++) {
            process.stdout.write(im_array[pj][0] + '... ')
            get_photo_info(im_array[pj][0],pj)
            process.stdout.write('done!\n')
        }
    }, 35000)

}
/*
 This function accepts an input file name in the format filename.txt from function
 get_credits() and attempts to create a readstream of the file. Then it attempts to
 parse out the photographer's name and save that to im_array[pj][2].
 */
function get_photo_info(fname,idx) {

    stream = fs.createReadStream('/Volumes/pictures/Signtyp/promptsnormalizedOnefolder/' + fname)
    stream.on("error", function(err) {

        return console.error("open file error " + err.message)

    })
    stream.on("open", function(fd) {
        fs.fstat(fd, function(err, stats) {
            var size
            if (err) {
                return console.error("fstat error: " + err.message)

            } else {
                size = stats.size

            }
        })
    })
    stream.on("data", function(data1) {
        var chunk
        var phline
        var photog
        var name_end
        var the_url
        var url_end

        chunk += data1
        phline = chunk.indexOf('Photographer : ')
        if (phline > -1) {
            name_end = chunk.indexOf('\n',phline)
            photog = chunk.slice(phline+15,name_end)
            im_array[idx][2].push(photog)

        } else {
            process.stdout.write('Photographer not found')
        }

    })
}

function func(data) {
  console.log('Line: ' + totalLines + ' ' + data);

}
function do_array_print() {
    console.log('Image name\tFilename\tPhotographer name\n')
    for (var i = 0; i < im_array.length; i++) {
        console.log(im_array[i][0] + '\t' + im_array[i][1] + '\t' + im_array[i][2])
    }
}<commit_msg>Fix multidimensional array errors<commit_after>/*************************************************************************
 * NODE.JS SCRIPT TO POPULATE A MONGODB 'fnck' collection from a tab-    *
 * separated text file supplied by the customer.                         *
 * 2014-03-23                                                            *
 *                                                                       *
 * To start the script, use this command line in a shell window:         *
 * node populate_all_image_credits_newdb_mongodb_pho_test.js startline end
 *                                                                       *
 * for example                                                           *
 *                                                                       *
 * node populate_all_image_credits_newdb_mongodb_pho_test.js 1 200       *
 *                                                                       *
 * Tells the script to start processing at line 1 and terminate          *
 * processing at line 200. Depending on your system and available memory,*
 * 200 open file descriptors at one time may be too many to have, so     *
 * process fewer lines per pass.                                         *
 *                                                                       *
 * The script processes in small passes to account for system overhead in*
 * using up too many file descriptors.                                   *
 * ----------------------------------------------------------------------*
 * 2014-03-28                                                            *
 * CUSTOMER-SUPPLIED FILE MAY NEED REFORMATTING PRIOR TO USE             *
 * ----------------------------------------------------------------------*
 * Read the converted_New_Names_2014-03-08_FileNamesandCaptionKeys.txt   *
 * file as a readable stream.                                            *
 * The input file has been reformatted from a Microsoft Windows formatted*
 * file containing carriage returns and line feed characters '\r\n' to a *
 * Unix style file with only '\n' terminating each line. Also, empty tab-*
 * separated lines in the format '\t\t\t\t\n' appended to the end of the *
 * original source input file were removed.                              *
 * The goal in this script is to extract the filename contained in each  *
 * row of the source file and append the extension .txt (period,         *
 * character t, character x, character t) to this name. Then read this   *
 * *.txt file with fs.read. Parse this file and extract the              *
 * "Photographer" field within the file. Next, update the matching       *
 * document in the 'fnck' collection of the 'sgtypdb2' database          *
 * to add this new field to the document: 'photographer'.                *
 *-----------------------------------------------------------------------*
 * FOR TESTING PURPOSES, the 'fnck' collection has been copied to the    *
 * 'test' database using mongodump and then mongorestore.                *
 *-----------------------------------------------------------------------*
 * The ultimate reason for updating the fnck collection in this way is to*
 * allow one document to be used as the source data to populate most of  *
 * the eventual application web page.                                    *
 *                                                                       *
 *------------------------- S T E P S -----------------------------------*
 *                                                                       *
 * 1. Extract filename from the current input line of the                *
 *    'converted_New_Names_2014-03-08_FileNamesandCaptionKeys.txt' file. *
 *    Example: _8758450914_o                                             *
 * 2. Save this filename prefix to a multidimensional array.             *
 * 3. Append a '.txt' extension to the extracted filename.               *
 *    _8758450914_o.txt                                                  *
 * 4. Save the [filename].txt element to the same multimensional array as*
 *    in step 2. The array element now looks like                        *
 *    [["_8758450914_o", "_8758450914_o.txt",...]]                       *
 * 5. Iterate to the next line of the FilenamesandCaptionKeys input file *
 *    listed in Step 1. Repeat steps 1-4, building up the multi-         *
 *    dimensional array with the elements for the next line of the input *
 *    file. So element #1 will look like this:                           *
 *    [["_8758450914_o", "_8758450914_o.txt",...],                       *
 *     ["_9758450914_o", "_9758450914_o.txt",...]...]                    *
 *    Do this in passes of 25 to 200 files.                              *
 *                                                                       *
 * 6. Now, working from the very beginning of the multidimensional array *
 *    that we have built, attempt to open a file matching the            *
 *    Filename.txt string that is at that index in our array. Example:   *
 *    open '_8758450914_o.txt'                                           *
 * 7. Attempt to read the file if the open succeeds.                     *
 *    read '_8758450914_o.txt'                                           *
 * 8. Find the line that begins with the word "Photographer : "          *
 * 9. Extract the name of the photographer.                              *
 *    peter.clark                                                        *
 *10. Add the photographer name to the multidimensional array as in step *
 *    4. The array now looks like:                                       *
 *    [["_8758450914_o", "_8758450914_o.txt", "peter.clark"],            *
 *    ["_9758450914_o", "_9758450914_o.txt",...]...]                     *
 *11. Iterate through all the array elements that need the photographer  *
 *    name added to the associated filename.txt string.                  *
 *12. With 25 to 200 filenames ready in the array, open a MongoDB        *
 *    connection to the 'fnck' collection of either the 'test' or        *
 *    the 'sgtypdb2' databases. At first use the 'test' database when    *
 *    testing application logic.                                         *
 *13. This script will attempt to update each matching document within   *
 *    the 'fnck' collection of the 'sgtypdb2' database with the          *
 *    photographer information just extracted from the text files.       *
 *    It expects that these fields will be added to each matching        *
 *    document and that these fields will be new fields for each matching*
 *    document. That is, the script does not try to try to update these  *
 *    fields in the matching document because they do not exist yet.     *
 *-----------------------------------------------------------------------*
 * Target database engine: MONGODB 2.4.9                                 *
 * Required node.js module: mongodb                                      *
 * It can take time for this script to complete all the inserts for the  *
 * fnck collection. If you abort the script by pressing CTRL-D or        *
 * CTRL-C the database inserts will most likely not complete.            *
 ************************************************************************/
var fs = require('fs');
var totalLines = 0
var j1 = 0              // first dimenion of im_array
var j2 = 0              // second dimension of im_array
var stream              // for use in parsing for photographer name
var startLn = 0         // the starting line for this processing "pass"
var endLn = 0           // the ending line for this processing "pass"
var actLines = 0        // the actual number of text lines that readLines has found
var webRows = 0         // count of web page row numbers, starting from 1
var array_lines = 0     // the number of array iterations we need

/* Were any arguments passed in? Exit if none found */

if (process.argv.length < 3) {
    console.log('You must pass in the starting and ending line numbers as arguments to this script')
    console.log('The number of arguments found were ' + process.argv.length)
    console.log('Terminating processing')
    process.exit(1)
}

/* Get the command line arguments passed to this script */

process.argv.forEach(function(val, index, array) {
    console.log(index + ': ' + val);
    if (index === 2) {
        startLn = val
        webRows = val
    }
    if (index == 3) {
        endLn = val
    }
});

array_lines = endLn - startLn      //compute number of iterations

console.log('startLn is ' + startLn)
console.log('endLn is ' + endLn)
console.log('Number of iterations in the array will be ' + array_lines + '\n')

/* Set up an [lines being processed] x 3 array */

var im_array = []             // multidimensional array of image names, file names, photographer names
for(i = 0; i < array_lines; i++) {
    im_array[i] = [];
}

var input = fs.createReadStream('/Users/bobc/Documents/sgntyp_renamed_files_2014-03-08/converted_New_Names_2014-03-08_FileNamesandCaptionKeys.txt');

readLines(input, func);
get_credits()
/*
 * Wait 46 seconds to let other processes complete, then build
 * the summary web page. We want to pass it the starting line number value.
 */
setTimeout(function () {
    do_array_print()
},46000)

function readLines(input, func) {
      var remaining = '';

      input.on('data', function(data) {
      remaining += data;
      var index1 = remaining.indexOf('\n');
      while (index1 > -1) {
          var line = remaining.slice(0, index1);
          remaining = remaining.slice(index1 + 1);
          totalLines += 1
          // Skip the header line.
          if (totalLines === 1) {
             index1 = remaining.indexOf('\n')
             continue
          }
          actLines += 1                           // actual number of content lines minus header line

          //discover if the line we are on is the line to start processing
          if (actLines < startLn) {
              index1 = remaining.indexOf('\n')
              continue
          }

          //discover if the line we are on is past the ending line number
          //that we want to process for this pass
          if (actLines > endLn) {
              index1 = remaining.indexOf('\n')
              continue
          }

          index1 = remaining.indexOf('\n')        // recompute value of index1
          var tbbl = line.indexOf('\t')           // find the index of the tab character
          if (line[0] === '\"') {                 // check to see if the filename string is quoted
              var fn1 = line.slice(1,(tbbl-1))    //skip the quotes
          } else {
              var fn1 = line.slice(0, tbbl)        // save the file name string up to the tab character
          }
          im_array[j1][j2].push(fn1)              // save the filename string without an extension
          fn1 = fn1 + '.txt'                      // append the .txt extension
          j2++                                    // bump to next element in j1
          im_array[j1][j2].push(fn1)              // push this onto the array
          j2 = 0                                  // reset j2
          j1++                                    // set up the next array

  }
})

  input.on('end', function() {
    if (remaining.length > 0) {
      func(remaining);
    }
    console.log('\nTotal number of lines processed including input header row: ' + totalLines + '\n')

  })
    }
/*
 * At this point, we have extracted all the filenames from the source TSV document and these
 * are waiting for us in the array im_array. The array now looks like this:
 *
 * [["_8758450914_o", "_8758450914_o.txt", ...],["_9758450914_o", "_9758450914_o.txt",...]...]
 *
 * For each file name in the array[j1][j2], we want to call a function that will
 * create a readstream of that file's contents, and parse out the
 * photographer's name. The photographer name would be put into im_array[j1][2].
 *
 * After all the file names are processed, we can update the 'fnck' collection documents with
 * corresponding photographer information.
 *
 */
function get_credits() {

    setTimeout(function () {
        process.stdout.write('\nProcessing files...\n')
        for(var pj = 0; pj < im_array.length; pj++) {
            process.stdout.write(im_array[pj][0] + '... ')
            get_photo_info(im_array[pj][0],pj)
            process.stdout.write('done!\n')
        }
    }, 35000)

}
/*
 This function accepts an input file name in the format filename.txt from function
 get_credits() and attempts to create a readstream of the file. Then it attempts to
 parse out the photographer's name and save that to im_array[pj][2].
 */
function get_photo_info(fname,idx) {

    stream = fs.createReadStream('/Volumes/pictures/Signtyp/promptsnormalizedOnefolder/' + fname)
    stream.on("error", function(err) {

        return console.error("open file error " + err.message)

    })
    stream.on("open", function(fd) {
        fs.fstat(fd, function(err, stats) {
            var size
            if (err) {
                return console.error("fstat error: " + err.message)

            } else {
                size = stats.size

            }
        })
    })
    stream.on("data", function(data1) {
        var chunk
        var phline
        var photog
        var name_end
        var the_url
        var url_end

        chunk += data1
        phline = chunk.indexOf('Photographer : ')
        if (phline > -1) {
            name_end = chunk.indexOf('\n',phline)
            photog = chunk.slice(phline+15,name_end)
            im_array[idx][2].push(photog)

        } else {
            process.stdout.write('Photographer not found')
        }

    })
}

function func(data) {
  console.log('Line: ' + totalLines + ' ' + data);

}
function do_array_print() {
    console.log('Image name\tFilename\tPhotographer name\n')
    for (var i = 0; i < im_array.length; i++) {
        console.log(im_array[i][0] + '\t' + im_array[i][1] + '\t' + im_array[i][2])
    }
}<|endoftext|>


<commit_before>import angular from 'angular';

/** Sentry.io exception reporting */
export let reportException = () => {};

if ($featureFlags.sentry) {
  // The require instead of import helps us trim this from the production bundle
  const Raven = require('raven-js');
  Raven
    .config('https://1367619d45da481b8148dd345c1a1330@sentry.io/279673', {
      release: $DIM_VERSION,
      environment: $DIM_FLAVOR
    })
    .addPlugin(require('raven-js/plugins/angular'), angular)
    .install();

  reportException = (name, e) => {
    // TODO: we can also do this in some situations to gather more feedback from users
    // Raven.showReportDialog();
    Raven.reportException(e);
  };

  window.addEventListener('unhandledrejection', (event) => Raven.captureException(event.reason));
}
<commit_msg>Use the right Sentry method<commit_after>import angular from 'angular';

/** Sentry.io exception reporting */
export let reportException = () => {};

if ($featureFlags.sentry) {
  // The require instead of import helps us trim this from the production bundle
  const Raven = require('raven-js');
  Raven
    .config('https://1367619d45da481b8148dd345c1a1330@sentry.io/279673', {
      release: $DIM_VERSION,
      environment: $DIM_FLAVOR
    })
    .addPlugin(require('raven-js/plugins/angular'), angular)
    .install();

  reportException = (name, e) => {
    // TODO: we can also do this in some situations to gather more feedback from users
    // Raven.showReportDialog();
    Raven.captureException(e);
  };

  window.addEventListener('unhandledrejection', (event) => Raven.captureException(event.reason));
}
<|endoftext|>


<commit_before>"use strict";

import { Timer } from "./../timer";
import { WorldTouch } from "./world_touch";
import { Animation } from "./../flythrough/animation";
import { SineEasing } from "./../flythrough/easing";
import { MapCameraTiltAnimation } from "./../flythrough/map_camera_tilt_animation";
import { MotionGenerator } from "./../flythrough/motion_generator";
import { VehicleController } from "./../flythrough/vehicle_controller";
import { VehicleView } from "./../flythrough/vehicle_view";

const HALF_PI = Math.PI * 0.5;

var TimerLoop = function(initialWorldData, sceneView, mapCamera, messageBroker) {
  var INTERACTIVE = 1;
  var FLYTHROUGH = 2;
  var FLYTHROUGH_STOP = 3;

  var END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT = 10;

  var worldData;
  var timer;
  var vehicleController;
  var vehicleView;
  var vehicleToInteractiveAnimation;
  var camera = sceneView.camera();
  var mode = INTERACTIVE;
  var zoomAmount = 0.0;

  var WINDOW_CENTER = new THREE.Vector3(0.0, 0.0, 0.0);

  var syncToCamera = function() {
    if (mode === FLYTHROUGH) {
      camera.position.x = vehicleView.positionX();
      camera.position.y = vehicleView.positionY();
      camera.position.z = vehicleView.positionZ();
      camera.rotation.x = vehicleView.rotationX();
      camera.rotation.y = vehicleView.rotationY();
    }
    else if (mode === FLYTHROUGH_STOP) {
      camera.position.x = vehicleToInteractiveAnimation.positionX();
      camera.position.y = vehicleToInteractiveAnimation.positionY();
      camera.position.z = vehicleToInteractiveAnimation.positionZ();
      camera.rotation.x = vehicleToInteractiveAnimation.rotationX();
      camera.rotation.y = vehicleToInteractiveAnimation.rotationY();
    }
  };

  var startFlythrough = function() {
    var initialCoordinates = {
      positionX: camera.position.x,
      positionY: camera.position.y,
      positionZ: camera.position.z,
      rotationX: camera.rotation.x,
      rotationY: camera.rotation.y,
    };

    zoomAmount = 0.0;
    mapCamera.setIsVelocityEnabled(false);

    vehicleController = new VehicleController(worldData.terrain, worldData.roadNetwork, worldData.neighborhoods, initialCoordinates);
    vehicleView = new VehicleView(vehicleController);
    mode = FLYTHROUGH;
    messageBroker.publish("flythrough.started", { vehicleView: vehicleView });
  };

  var requestStopFlythrough = function() {
    const centerOfTiltDistance = 3;
    var rotationY = camera.rotation.y + HALF_PI;

    if (camera.rotation.x > mapCamera.maxTiltAngle()) {
      mapCamera.setCenterOfTilt(new THREE.Vector3(camera.position.x + (centerOfTiltDistance * Math.cos(rotationY)),
                                                  camera.position.y,
                                                  camera.position.z + (centerOfTiltDistance * -Math.sin(rotationY))));
      vehicleToInteractiveAnimation = MapCameraTiltAnimation(mapCamera, mapCamera.maxTiltAngle(), (mapCamera.maxTiltAngle() - camera.rotation.x) / END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT);
    }
    else {
      vehicleToInteractiveAnimation = new Animation(
        new MotionGenerator(vehicleController.positionX(), camera.position.x, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI)),
        new MotionGenerator(vehicleController.positionY(), camera.position.y, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI)),
        new MotionGenerator(vehicleController.positionZ(), camera.position.z, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI)),
        new MotionGenerator(vehicleController.rotationX(), camera.rotation.x, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI)),
        new MotionGenerator(vehicleController.rotationY(), camera.rotation.y, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI))
      );
    }

    vehicleController = undefined;
    vehicleView = undefined;
    mode = FLYTHROUGH_STOP;
  };

  var stopFlythrough = function() {
    vehicleToInteractiveAnimation = undefined;
    mode = INTERACTIVE;

    messageBroker.publish("flythrough.stopped", {});
  };

  var toggleFlythrough = function() {
    if (mode === INTERACTIVE) {
      startFlythrough();
    }
    else if (mode === FLYTHROUGH) {
      requestStopFlythrough();
    }
  };

  var reset = function(newWorldData) {
    worldData = newWorldData;
    syncToCamera();
  };

  var restartTimer = function() {
    if (timer.isPaused()) {
      timer.start();
    }
  };

  var id1 = messageBroker.addSubscriber("touch.focus", function(data) { restartTimer(); });

  reset(initialWorldData);

  timer = new Timer();
  timer.onTick = function(frameCount) {
    var i;

    for (i = 0; i < frameCount; i++) {
      if (mode === INTERACTIVE) {
        if (zoomAmount !== 0.0) {
          mapCamera.zoomTowardCenterOfAction(zoomAmount);
        }
      }
      else if (mode === FLYTHROUGH) {
        vehicleController.tick();
        vehicleView.tick();
      }
      else if (mode === FLYTHROUGH_STOP) {
        vehicleToInteractiveAnimation.tick();
        if (vehicleToInteractiveAnimation.finished()) {
          stopFlythrough();
        }
      }
    }

    if (mapCamera.isVelocityEnabled()) {
      mapCamera.tickVelocity(frameCount);
    }

    syncToCamera();
    sceneView.render();
  };
  timer.start();

  window.addEventListener("blur", function(e) {
    timer.pause();
  }, false);

  window.addEventListener("focus", function(e) { restartTimer(); }, false);

  return {
    reset: reset,
    setZoomAmount: function(newZoomAmount) { zoomAmount = newZoomAmount; },
    toggleFlythrough: toggleFlythrough,
  };
};

export { TimerLoop };
<commit_msg>Removing no-op statement<commit_after>"use strict";

import { Timer } from "./../timer";
import { WorldTouch } from "./world_touch";
import { Animation } from "./../flythrough/animation";
import { SineEasing } from "./../flythrough/easing";
import { MapCameraTiltAnimation } from "./../flythrough/map_camera_tilt_animation";
import { MotionGenerator } from "./../flythrough/motion_generator";
import { VehicleController } from "./../flythrough/vehicle_controller";
import { VehicleView } from "./../flythrough/vehicle_view";

const HALF_PI = Math.PI * 0.5;

var TimerLoop = function(initialWorldData, sceneView, mapCamera, messageBroker) {
  var INTERACTIVE = 1;
  var FLYTHROUGH = 2;
  var FLYTHROUGH_STOP = 3;

  var END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT = 10;

  var worldData;
  var timer;
  var vehicleController;
  var vehicleView;
  var vehicleToInteractiveAnimation;
  var camera = sceneView.camera();
  var mode = INTERACTIVE;
  var zoomAmount = 0.0;

  var WINDOW_CENTER = new THREE.Vector3(0.0, 0.0, 0.0);

  var syncToCamera = function() {
    if (mode === FLYTHROUGH) {
      camera.position.x = vehicleView.positionX();
      camera.position.y = vehicleView.positionY();
      camera.position.z = vehicleView.positionZ();
      camera.rotation.x = vehicleView.rotationX();
      camera.rotation.y = vehicleView.rotationY();
    }
    else if (mode === FLYTHROUGH_STOP) {
      camera.position.x = vehicleToInteractiveAnimation.positionX();
      camera.position.y = vehicleToInteractiveAnimation.positionY();
      camera.position.z = vehicleToInteractiveAnimation.positionZ();
      camera.rotation.x = vehicleToInteractiveAnimation.rotationX();
      camera.rotation.y = vehicleToInteractiveAnimation.rotationY();
    }
  };

  var startFlythrough = function() {
    var initialCoordinates = {
      positionX: camera.position.x,
      positionY: camera.position.y,
      positionZ: camera.position.z,
      rotationX: camera.rotation.x,
      rotationY: camera.rotation.y,
    };

    zoomAmount = 0.0;
    mapCamera.setIsVelocityEnabled(false);

    vehicleController = new VehicleController(worldData.terrain, worldData.roadNetwork, worldData.neighborhoods, initialCoordinates);
    vehicleView = new VehicleView(vehicleController);
    mode = FLYTHROUGH;
    messageBroker.publish("flythrough.started", { vehicleView: vehicleView });
  };

  var requestStopFlythrough = function() {
    const centerOfTiltDistance = 3;
    var rotationY = camera.rotation.y + HALF_PI;

    if (camera.rotation.x > mapCamera.maxTiltAngle()) {
      mapCamera.setCenterOfTilt(new THREE.Vector3(camera.position.x + (centerOfTiltDistance * Math.cos(rotationY)),
                                                  camera.position.y,
                                                  camera.position.z + (centerOfTiltDistance * -Math.sin(rotationY))));
      vehicleToInteractiveAnimation = MapCameraTiltAnimation(mapCamera, mapCamera.maxTiltAngle(), (mapCamera.maxTiltAngle() - camera.rotation.x) / END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT);
    }
    else {
      vehicleToInteractiveAnimation = new Animation(
        new MotionGenerator(vehicleController.positionX(), camera.position.x, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI)),
        new MotionGenerator(vehicleController.positionY(), camera.position.y, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI)),
        new MotionGenerator(vehicleController.positionZ(), camera.position.z, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI)),
        new MotionGenerator(vehicleController.rotationX(), camera.rotation.x, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI)),
        new MotionGenerator(vehicleController.rotationY(), camera.rotation.y, new SineEasing(END_OF_FLYTHROUGH_ANIMATION_FRAME_COUNT, 0, HALF_PI))
      );
    }

    vehicleController = undefined;
    vehicleView = undefined;
    mode = FLYTHROUGH_STOP;
  };

  var stopFlythrough = function() {
    vehicleToInteractiveAnimation = undefined;
    mode = INTERACTIVE;

    messageBroker.publish("flythrough.stopped", {});
  };

  var toggleFlythrough = function() {
    if (mode === INTERACTIVE) {
      startFlythrough();
    }
    else if (mode === FLYTHROUGH) {
      requestStopFlythrough();
    }
  };

  var reset = function(newWorldData) {
    worldData = newWorldData;
  };

  var restartTimer = function() {
    if (timer.isPaused()) {
      timer.start();
    }
  };

  var id1 = messageBroker.addSubscriber("touch.focus", function(data) { restartTimer(); });

  reset(initialWorldData);

  timer = new Timer();
  timer.onTick = function(frameCount) {
    var i;

    for (i = 0; i < frameCount; i++) {
      if (mode === INTERACTIVE) {
        if (zoomAmount !== 0.0) {
          mapCamera.zoomTowardCenterOfAction(zoomAmount);
        }
      }
      else if (mode === FLYTHROUGH) {
        vehicleController.tick();
        vehicleView.tick();
      }
      else if (mode === FLYTHROUGH_STOP) {
        vehicleToInteractiveAnimation.tick();
        if (vehicleToInteractiveAnimation.finished()) {
          stopFlythrough();
        }
      }
    }

    if (mapCamera.isVelocityEnabled()) {
      mapCamera.tickVelocity(frameCount);
    }

    syncToCamera();
    sceneView.render();
  };
  timer.start();

  window.addEventListener("blur", function(e) {
    timer.pause();
  }, false);

  window.addEventListener("focus", function(e) { restartTimer(); }, false);

  return {
    reset: reset,
    setZoomAmount: function(newZoomAmount) { zoomAmount = newZoomAmount; },
    toggleFlythrough: toggleFlythrough,
  };
};

export { TimerLoop };
<|endoftext|>


<commit_before>const langs = ['en', 'it', 'de'];
let url = window.location.hash;
url = url.toString().replace('#', '');

$(window).on('load', function () {
	setTimeout(function () {
		$('.last').addClass('last-loaded');
	}, 2000);
	AOS.init();
});

const translate = function (jsdata) {
	$("[tkey]").each(function (index) {
		let strTr = jsdata [$(this).attr('tkey')];
		$(this).html(strTr);
	});
};

let langCode = navigator.language.substr(0, 2);

if (Cookies.get('lang') === undefined) {
	Cookies.set('lang', langCode, { expires: 365 }, { path: '' });
}

const cookieLang = Cookies.get('lang');

function changeLang(lang) {
	$.getJSON('lang/' + lang + '.json', translate);
	Cookies.set('lang', lang, { expires: 365 }, { path: '' });
}

if (url == 'de') changeLang('de');

else if (url == 'it') changeLang(it);

else if (url == 'en') changeLang('en');

else if (langs.indexOf(cookieLang) >= 0) changeLang(cookieLang);

else changeLang('en');

$('#changeEn').on('click', function () {
	changeLang('en');
});

$('#changeDe').on('click', function () {
	changeLang('de');
});

$('#changeIt').on('click', function () {
	changeLang('it');
});

$('#removeLang').on('click', function () {
	Cookies.remove('lang');
	window.location.reload();
});
<commit_msg>Support for Internet Explorer.<commit_after>const langs = ['en', 'it', 'de'];
let url = window.location.hash;
url = url.toString().replace('#', '');

$(window).on('load', function () {
	setTimeout(function () {
		$('.last').addClass('last-loaded');
	}, 2000);
	AOS.init();
});

const translate = function (jsdata) {
	$("[tkey]").each(function (index) {
		let strTr = jsdata [$(this).attr('tkey')];
		$(this).html(strTr);
	});
};

let langCode;

if (navigator.userLanguage) {
	langCode = navigator.userLanguage.substr(0, 2);
} else {
	langCode = navigator.language.substr(0, 2);
}

if (Cookies.get('lang') === undefined) {
	Cookies.set('lang', langCode, { expires: 365 }, { path: '' });
}

const cookieLang = Cookies.get('lang');

function changeLang(lang) {
	$.getJSON('lang/' + lang + '.json', translate);
	Cookies.set('lang', lang, { expires: 365 }, { path: '' });
}

if (url == 'de') changeLang('de');

else if (url == 'it') changeLang(it);

else if (url == 'en') changeLang('en');

else if (langs.indexOf(cookieLang) >= 0) changeLang(cookieLang);

else changeLang('en');

$('#changeEn').on('click', function () {
	changeLang('en');
});

$('#changeDe').on('click', function () {
	changeLang('de');
});

$('#changeIt').on('click', function () {
	changeLang('it');
});

$('#removeLang').on('click', function () {
	Cookies.remove('lang');
	window.location.reload();
});
<|endoftext|>


<commit_before>// sorted alphabetically
const locales = {
  cs: {
    name: 'Čeština',
    locale: 'cs',
    messages: () => import('@/locales/locale-cs.json'),
    intlLocale: () => import('intl/locale-data/jsonp/cs'),
    dateFnsLocale: () => import('date-fns/locale/cs'),
    quasar: () => import('quasar-framework/i18n/cs'),
  },

  de: {
    name: 'Deutsch',
    locale: 'de',
    messages: () => import('@/locales/locale-de.json'),
    intlLocale: () => import('intl/locale-data/jsonp/de'),
    dateFnsLocale: () => import('date-fns/locale/de'),
    quasar: () => import('quasar-framework/i18n/de'),
  },

  en: {
    name: 'English',
    locale: 'en',
    messages: () => import('@/locales/locale-en.json'),
    intlLocale: () => import('intl/locale-data/jsonp/en'),
    dateFnsLocale: () => import('date-fns/locale/en'),
    quasar: () => import('quasar-framework/i18n/en-us'),
  },

  eo: {
    name: 'Esperanto',
    locale: 'eo',
    messages: () => import('@/locales/locale-eo.json'),
    intlLocale: () => import('intl/locale-data/jsonp/eo'),
    dateFnsLocale: () => import('date-fns/locale/eo'),
    quasar: () => import('quasar-framework/i18n/en-us'), // TODO switch when translated
  },

  es: {
    name: 'Español',
    locale: 'es',
    messages: () => import('@/locales/locale-es.json'),
    intlLocale: () => import('intl/locale-data/jsonp/es'),
    dateFnsLocale: () => import('date-fns/locale/es'),
    quasar: () => import('quasar-framework/i18n/es'),
  },

  fr: {
    name: 'Français',
    locale: 'fr',
    messages: () => import('@/locales/locale-fr.json'),
    intlLocale: () => import('intl/locale-data/jsonp/fr'),
    dateFnsLocale: () => import('date-fns/locale/fr'),
    quasar: () => import('quasar-framework/i18n/fr'),
  },

  gu: {
    name: 'ગુજરાતી',
    locale: 'gu',
    messages: () => import('@/locales/locale-gu.json'),
    intlLocale: () => import('intl/locale-data/jsonp/gu'),
    dateFnsLocale: () => import('date-fns/locale/en'), // TODO switch to Gujarati when datefns supports it
    quasar: () => import('quasar-framework/i18n/en-us'), // TODO switch when translated
  },

  hi: {
    name: 'हिन्दी',
    locale: 'hi',
    messages: () => import('@/locales/locale-hi.json'),
    intlLocale: () => import('intl/locale-data/jsonp/hi'),
    dateFnsLocale: () => import('date-fns/locale/en'), // TODO switch to Hindi when datefns supports it
    quasar: () => import('quasar-framework/i18n/en-us'), // TODO switch when translated
  },

  it: {
    name: 'Italiano',
    locale: 'it',
    messages: () => import('@/locales/locale-it.json'),
    intlLocale: () => import('intl/locale-data/jsonp/it'),
    dateFnsLocale: () => import('date-fns/locale/it'),
    quasar: () => import('quasar-framework/i18n/it'),
  },

  pl: {
    name: 'Polski',
    locale: 'pl',
    messages: () => import('@/locales/locale-pl.json'),
    intlLocale: () => import('intl/locale-data/jsonp/pl'),
    dateFnsLocale: () => import('date-fns/locale/pl'),
    quasar: () => import('quasar-framework/i18n/pl'),
  },

  'pt': {
    name: 'Português',
    locale: 'pt',
    messages: () => import('@/locales/locale-pt.json'),
    intlLocale: () => import('intl/locale-data/jsonp/pt'),
    dateFnsLocale: () => import('date-fns/locale/pt'),
    quasar: () => import('quasar-framework/i18n/pt'),
  },

  'pt-br': {
    name: 'Português Brasileiro',
    locale: 'pt-br',
    messages: () => import('@/locales/locale-pt_BR.json'),
    intlLocale: () => import('intl/locale-data/jsonp/pt-BR'),
    dateFnsLocale: () => import('date-fns/locale/pt'), // TODO switch to pt-br when datefns supports it
    quasar: () => import('quasar-framework/i18n/pt-br'),
  },

  ru: {
    name: 'Русский',
    locale: 'ru',
    messages: () => import('@/locales/locale-ru.json'),
    intlLocale: () => import('intl/locale-data/jsonp/ru'),
    dateFnsLocale: () => import('date-fns/locale/ru'),
    quasar: () => import('quasar-framework/i18n/ru'),
  },

  sv: {
    name: 'Svenska',
    locale: 'sv',
    messages: () => import('@/locales/locale-sv.json'),
    intlLocale: () => import('intl/locale-data/jsonp/sv'),
    dateFnsLocale: () => import('date-fns/locale/sv'),
    quasar: () => import('quasar-framework/i18n/sv'),
  },

  /*
  // Currently not used, please open issue if this should be enabled
  'zh-hans': {
    name: '中文 (Simplified)',
    locale: 'zh-hans',
    messages: () => import('@/locales/locale-zh_Hans.json'),
    intlLocale: () => import('intl/locale-data/jsonp/zh-Hans'),
    dateFnsLocale: () => import('date-fns/locale/zh_cn'),
    quasar: () => import('quasar-framework/i18n/zh-hans'),
  },
  */

  'zh-hant': {
    name: '中文',
    locale: 'zh-hant',
    messages: () => import('@/locales/locale-zh_Hant.json'),
    intlLocale: () => import('intl/locale-data/jsonp/zh-Hant'),
    dateFnsLocale: () => import('date-fns/locale/zh_tw'),
    quasar: () => import('quasar-framework/i18n/zh-hant'),
  },
}

export default locales

/**
 * Loading helpers
 */

export function messages (locale) {
  return locales[locale].messages()
}

export function intlLocale (locale) {
  return locales[locale].IntlData()
}

export function dateFnsLocale (locale) {
  return locales[locale].dateFnsLocale()
}

export function quasarMessages (locale) {
  return locales[locale].quasar()
}
<commit_msg>fix intlLocale loading<commit_after>// sorted alphabetically
const locales = {
  cs: {
    name: 'Čeština',
    locale: 'cs',
    messages: () => import('@/locales/locale-cs.json'),
    intlLocale: () => import('intl/locale-data/jsonp/cs'),
    dateFnsLocale: () => import('date-fns/locale/cs'),
    quasar: () => import('quasar-framework/i18n/cs'),
  },

  de: {
    name: 'Deutsch',
    locale: 'de',
    messages: () => import('@/locales/locale-de.json'),
    intlLocale: () => import('intl/locale-data/jsonp/de'),
    dateFnsLocale: () => import('date-fns/locale/de'),
    quasar: () => import('quasar-framework/i18n/de'),
  },

  en: {
    name: 'English',
    locale: 'en',
    messages: () => import('@/locales/locale-en.json'),
    intlLocale: () => import('intl/locale-data/jsonp/en'),
    dateFnsLocale: () => import('date-fns/locale/en'),
    quasar: () => import('quasar-framework/i18n/en-us'),
  },

  eo: {
    name: 'Esperanto',
    locale: 'eo',
    messages: () => import('@/locales/locale-eo.json'),
    intlLocale: () => import('intl/locale-data/jsonp/eo'),
    dateFnsLocale: () => import('date-fns/locale/eo'),
    quasar: () => import('quasar-framework/i18n/en-us'), // TODO switch when translated
  },

  es: {
    name: 'Español',
    locale: 'es',
    messages: () => import('@/locales/locale-es.json'),
    intlLocale: () => import('intl/locale-data/jsonp/es'),
    dateFnsLocale: () => import('date-fns/locale/es'),
    quasar: () => import('quasar-framework/i18n/es'),
  },

  fr: {
    name: 'Français',
    locale: 'fr',
    messages: () => import('@/locales/locale-fr.json'),
    intlLocale: () => import('intl/locale-data/jsonp/fr'),
    dateFnsLocale: () => import('date-fns/locale/fr'),
    quasar: () => import('quasar-framework/i18n/fr'),
  },

  gu: {
    name: 'ગુજરાતી',
    locale: 'gu',
    messages: () => import('@/locales/locale-gu.json'),
    intlLocale: () => import('intl/locale-data/jsonp/gu'),
    dateFnsLocale: () => import('date-fns/locale/en'), // TODO switch to Gujarati when datefns supports it
    quasar: () => import('quasar-framework/i18n/en-us'), // TODO switch when translated
  },

  hi: {
    name: 'हिन्दी',
    locale: 'hi',
    messages: () => import('@/locales/locale-hi.json'),
    intlLocale: () => import('intl/locale-data/jsonp/hi'),
    dateFnsLocale: () => import('date-fns/locale/en'), // TODO switch to Hindi when datefns supports it
    quasar: () => import('quasar-framework/i18n/en-us'), // TODO switch when translated
  },

  it: {
    name: 'Italiano',
    locale: 'it',
    messages: () => import('@/locales/locale-it.json'),
    intlLocale: () => import('intl/locale-data/jsonp/it'),
    dateFnsLocale: () => import('date-fns/locale/it'),
    quasar: () => import('quasar-framework/i18n/it'),
  },

  pl: {
    name: 'Polski',
    locale: 'pl',
    messages: () => import('@/locales/locale-pl.json'),
    intlLocale: () => import('intl/locale-data/jsonp/pl'),
    dateFnsLocale: () => import('date-fns/locale/pl'),
    quasar: () => import('quasar-framework/i18n/pl'),
  },

  'pt': {
    name: 'Português',
    locale: 'pt',
    messages: () => import('@/locales/locale-pt.json'),
    intlLocale: () => import('intl/locale-data/jsonp/pt'),
    dateFnsLocale: () => import('date-fns/locale/pt'),
    quasar: () => import('quasar-framework/i18n/pt'),
  },

  'pt-br': {
    name: 'Português Brasileiro',
    locale: 'pt-br',
    messages: () => import('@/locales/locale-pt_BR.json'),
    intlLocale: () => import('intl/locale-data/jsonp/pt-BR'),
    dateFnsLocale: () => import('date-fns/locale/pt'), // TODO switch to pt-br when datefns supports it
    quasar: () => import('quasar-framework/i18n/pt-br'),
  },

  ru: {
    name: 'Русский',
    locale: 'ru',
    messages: () => import('@/locales/locale-ru.json'),
    intlLocale: () => import('intl/locale-data/jsonp/ru'),
    dateFnsLocale: () => import('date-fns/locale/ru'),
    quasar: () => import('quasar-framework/i18n/ru'),
  },

  sv: {
    name: 'Svenska',
    locale: 'sv',
    messages: () => import('@/locales/locale-sv.json'),
    intlLocale: () => import('intl/locale-data/jsonp/sv'),
    dateFnsLocale: () => import('date-fns/locale/sv'),
    quasar: () => import('quasar-framework/i18n/sv'),
  },

  /*
  // Currently not used, please open issue if this should be enabled
  'zh-hans': {
    name: '中文 (Simplified)',
    locale: 'zh-hans',
    messages: () => import('@/locales/locale-zh_Hans.json'),
    intlLocale: () => import('intl/locale-data/jsonp/zh-Hans'),
    dateFnsLocale: () => import('date-fns/locale/zh_cn'),
    quasar: () => import('quasar-framework/i18n/zh-hans'),
  },
  */

  'zh-hant': {
    name: '中文',
    locale: 'zh-hant',
    messages: () => import('@/locales/locale-zh_Hant.json'),
    intlLocale: () => import('intl/locale-data/jsonp/zh-Hant'),
    dateFnsLocale: () => import('date-fns/locale/zh_tw'),
    quasar: () => import('quasar-framework/i18n/zh-hant'),
  },
}

export default locales

/**
 * Loading helpers
 */

export function messages (locale) {
  return locales[locale].messages()
}

export function intlLocale (locale) {
  return locales[locale].intlLocale()
}

export function dateFnsLocale (locale) {
  return locales[locale].dateFnsLocale()
}

export function quasarMessages (locale) {
  return locales[locale].quasar()
}
<|endoftext|>


<commit_before>var LocationUtil = (function () {
    'use strict';

    function LocationUtil(url) {
        this.url = url;

        this._regexpProtocol = new RegExp('^([^:]+)://');
        this._regexpHost = new RegExp('^(?:([^:]+)://)?([^/]+)/?');
        this._regexpPort = new RegExp('^(?:([^:]+)://)?[^/]+?:([0-9]+)/?');
    }

    LocationUtil.prototype.absUrl = function () {
        return this.url;
    };

    LocationUtil.prototype.protocol = function () {
        var matches = this.url.match(this._regexpProtocol);

        if (matches === null) {
            return null;
        }

        var protocol = matches[1];
        if (typeof protocol === 'undefined') {
            return null;
        }
        return protocol;
    };

    LocationUtil.prototype.host = function () {
        var matches = this.url.match(this._regexpHost);

        if (matches === null) {
            return null;
        }

        var host = matches[2];
        if (typeof host === 'undefined') {
            return null;
        }
        return host;
    };

    LocationUtil.prototype.port = function () {
        var matches = this.url.match(this._regexpPort);

        if (matches === null) {
            return null;
        }

        var port = matches[2];
        if (typeof port === 'undefined') {
            return null;
        }
        return parseInt(port, 10);
    }

    return LocationUtil;
}());

this.LocationUtil = LocationUtil;
<commit_msg>Parse on initializing<commit_after>var LocationUtil = (function () {
    'use strict';

    function LocationUtil(url) {
        this._url = url;

        this._protocol = (function () {
            var matches = url.match('^([^:]+)://');

            if (matches === null) {
                return null;
            }

            var protocol = matches[1];
            if (typeof protocol === 'undefined') {
                return null;
            }
            return protocol;
        }());

        this._host = (function () {
            var matches = url.match('^(?:([^:]+)://)?([^/]+)/?');

            if (matches === null) {
                return null;
            }

            var host = matches[2];
            if (typeof host === 'undefined') {
                return null;
            }
            return host;
        }());

        this._port = (function () {
            var matches = url.match('^(?:([^:]+)://)?[^/]+?:([0-9]+)/?');

            if (matches === null) {
                return null;
            }

            var port = matches[2];
            if (typeof port === 'undefined') {
                return null;
            }
            return parseInt(port, 10);
        }());
    }

    LocationUtil.prototype.absUrl = function () {
        // TODO
        return this._url;
    };

    LocationUtil.prototype.protocol = function () {
        return this._protocol;
    };

    LocationUtil.prototype.host = function () {
        return this._host;
    };

    LocationUtil.prototype.port = function () {
        return this._port;
    }

    return LocationUtil;
}());

this.LocationUtil = LocationUtil;
<|endoftext|>