<commit_before>define(['jquery',
    'underscore',
    'backbone',
    'bootstrap',
    'arches',
    'views/map',
    'openlayers',
    'knockout',
    'map/resource-layer-model'],
    function($, _, Backbone, bootstrap, arches, MapView, ol, ko, ResourceLayerModel) {
        return Backbone.View.extend({

            events: {
                'click .layer-zoom': 'layerZoom'
            },

            initialize: function(options) {
                var self = this;

                //  Handle show/hide toggle ourselves
                $('#map-tools-btn').on('click', function(evt) {
                    if($(evt.currentTarget).hasClass('open')){
                        self.disableDrawingTools();
                    }
                    else {
                        self.enableDrawingTools();
                    }
                    $(evt.currentTarget).toggleClass('open');
                    return false;
                });
                $('#map-tools-dropdown').on('click', 'a', function(evt) {
                    if($(evt.target).attr('name') === 'map-tools'){
                        self.togglefilter(evt);
                    }
                    return false;
                });

                //  suppress default bahavior of the bootstrap menu to auto close
                $('#map-tools-btn').on('hide.bs.dropdown', false);
                $('#map-tools-btn').on('show.bs.dropdown', false);

                this.expanded = ko.observable(false);
                this.expanded.subscribe(function(status){
                    self.toggleFilterSection($('#map-filter'), status)
                });

                this.query = {
                    filter: {
                        geometry:{
                            type: ko.observable(''),
                            coordinates: ko.observable([])
                        },
                        buffer: {
                            width: ko.observable('0'),
                            unit: ko.observable('ft')
                        }
                    },
                    changed: ko.pureComputed(function(){
                        return (ko.toJSON(this.query.filter.geometry.coordinates()) +
                            ko.toJSON(this.query.filter.buffer.width()));
                    }, this).extend({ rateLimit: 200 })
                }

                ko.applyBindings(this.query.filter, $('#map-tools-dropdown')[0]);

                this.query.filter.buffer.width.subscribe(function(){
                    self.applyBuffer();
                });

                this.enabled = ko.computed(function(){
                    var enabled = (this.query.filter.geometry.type() !== '' && this.query.filter.geometry.coordinates().length !== 0);
                    this.trigger('enabled', enabled);
                    return enabled;
                }, this);

                this.vectorLayer = new ResourceLayerModel().layer;
                this.map = new MapView({
                    el: $('#map'),
                    overlays: [this.vectorLayer]
                });

                this.bufferFeatureOverlay = new ol.FeatureOverlay({
                    style: new ol.style.Style({
                        fill: new ol.style.Fill({
                            color: 'rgba(123, 123, 255, 0.5)'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#ff6633',
                            width: 2,
                            lineDash: [4,4]
                        })
                    })
                });
                this.bufferFeatureOverlay.setMap(this.map.map);

                this.drawingFeatureOverlay = new ol.FeatureOverlay({
                    style: new ol.style.Style({
                        fill: new ol.style.Fill({
                            color: 'rgba(255, 255, 255, 0.2)'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#ffcc33',
                            width: 2
                        })
                    })
                });
                this.drawingFeatureOverlay.setMap(this.map.map);

                this.zoomToExtent(this.vectorLayer.getLayers().item(0).getSource().getExtent())

                ko.applyBindings(this.map, $('#basemaps-panel')[0]);

                var hideAllPanels = function(){
                    $("#basemaps-panel").addClass("hidden");

                    //Update state of remaining buttons
                    $("#inventory-basemaps")
                        .removeClass("arches-map-tools-pressed")
                        .addClass("arches-map-tools")
                        .css("border-bottom-left-radius", "1px");
                };

                //Inventory-basemaps button opens basemap panel
                $("#inventory-basemaps").click(function (){
                    if ($(this).hasClass('arches-map-tools-pressed')) {
                        hideAllPanels();
                    } else {
                        $("#basemaps-panel").removeClass("hidden");

                        //Update state of current button and adjust position
                        $("#inventory-basemaps")
                            .addClass("arches-map-tools-pressed")
                            .removeClass("arches-map-tools")
                            .css("border-bottom-left-radius", "5px");
                    }
                });

                $(".basemap").click(function (){
                    var basemap = $(this).attr('id');
                    _.each(self.map.baseLayers, function(baseLayer){
                        baseLayer.layer.setVisible(baseLayer.id == basemap);
                    });
                    hideAllPanels();
                });

                //Close Button
                $(".close").click(function (){
                    hideAllPanels();
                });
            },

            zoomToExtent: function(extent){
                var size = this.map.map.getSize();
                var view = this.map.map.getView()
                view.fitExtent(
                    extent,
                    size
                );
            },

            highlightFeatures: function(resultsarray){
                if(!this.featureOverlay){
                    this.featureOverlay = new ol.FeatureOverlay({
                        map: this.map.map,
                        style: new ol.style.Style({
                            text: new ol.style.Text({
                                text: '\uf041',
                                font: 'normal 33px FontAwesome',
                                textBaseline: 'Bottom',
                                fill: new ol.style.Fill({
                                    color: '#C4171D'
                                })
                            })
                        })
                    });
                }
                this.featureOverlay.getFeatures().clear();

                _.each(resultsarray.results.hits.hits, function(result){
                    if(result._source.geometries.length > 0){
                        var feature = this.vectorLayer.getLayers().item(0).getSource().getFeatureById(result._id);
                        if(feature){
                            this.featureOverlay.addFeature(feature);
                        }
                    }
                }, this);
            },

            selectFeatureById: function(resourceid){
                if(!this.featureHightlightOverlay){
                    this.featureHightlightOverlay = new ol.FeatureOverlay({
                        map: this.map.map,
                        style: new ol.style.Style({
                            text: new ol.style.Text({
                                text: '\uf041',
                                font: 'normal 33px FontAwesome',
                                textBaseline: 'Bottom',
                                fill: new ol.style.Fill({
                                    color: '#4CAE4C'
                                })
                            })
                        })
                    });
                }

                this.unselectAllFeatures();
                var feature = this.vectorLayer.getLayers().item(0).getSource().getFeatureById(resourceid);
                if(feature){
                    this.featureHightlightOverlay.addFeature(feature);
                    return feature;
                }
            },

            unselectAllFeatures: function(){
                this.featureHightlightOverlay.getFeatures().clear();
            },

            getMapExtent: function(){
                var extent = ol.proj.transformExtent(this.map.map.getView().calculateExtent(this.map.map.getSize()), 'EPSG:3857', 'EPSG:4326');
                return extent;
            },

            onMoveEnd: function(evt) {
                this.query.filter.geometry.coordinates(this.getMapExtent());
            },

            togglefilter: function(evt){
                var link = $(evt.target).closest('a');
                var data = link.data();
                var item = link.find('i');

                if (!(item.hasClass("fa-check"))){
                    this.enableFilter(data.tooltype);
                }else{
                    this.clear();
                }
            },

            enableFilter: function(tooltype){
                if(tooltype){
                    if(tooltype === 'map-extent'){
                        this.removeDrawingTools();
                        this.clearDrawingFeatures();
                        this.query.filter.geometry.type('bbox');
                        this.query.filter.geometry.coordinates(this.getMapExtent());
                        this.map.map.on('moveend', this.onMoveEnd, this);
                    }else{
                        this.clearDrawingFeatures();
                        this.query.filter.geometry.type(tooltype);
                        this.changeDrawingTool(this.map.map, tooltype);
                        this.map.map.un('moveend', this.onMoveEnd, this);
                    }
                }
            },

            changeDrawingTool: function(map, tooltype){
                this.disableDrawingTools();

                this.modifyTool = new ol.interaction.Modify({
                    features: this.drawingFeatureOverlay.getFeatures(),
                    // the SHIFT key must be pressed to delete vertices, so
                    // that new vertices can be drawn at the same position
                    // of existing vertices
                    deleteCondition: function(event) {
                        return ol.events.condition.shiftKeyOnly(event) &&
                                ol.events.condition.singleClick(event);
                    }
                });
                map.addInteraction(this.modifyTool);

                this.drawingtool = new ol.interaction.Draw({
                    features: this.drawingFeatureOverlay.getFeatures(),
                    type: tooltype
                });
                this.drawingtool.set('type', tooltype);

                this.drawingtool.on('drawstart', function(){
                    if(this.drawingtool.get('type') !== 'Point'){
                        this.clearDrawingFeatures();
                    }
                }, this);

                this.drawingtool.on('drawend', function(evt){
                    var self = this;
                    var geometry = evt.feature.getGeometry().clone();
                    geometry.transform('EPSG:3857', 'EPSG:4326');
                    this.query.filter.geometry.coordinates(geometry.getCoordinates());

                    //this.applyBuffer();

                    evt.feature.on('change', function(evt) {
                        var geometry = evt.target.getGeometry().clone();
                        geometry.transform('EPSG:3857', 'EPSG:4326');
                        self.query.filter.geometry.coordinates(geometry.getCoordinates());
                        //self.applyBuffer();
                    });
                }, this);

                this.enableDrawingTools();
            },

            enableDrawingTools: function(){
                if(this.drawingtool){
                    this.map.map.addInteraction(this.drawingtool);
                }
            },

            disableDrawingTools: function(){
                if(this.drawingtool){
                    this.map.map.removeInteraction(this.drawingtool);
                }
            },

            removeDrawingTools: function(){
                this.disableDrawingTools();
                delete this.drawingtool;
            },

            clearDrawingFeatures: function(){
                if (this.bufferFeatureOverlay){
                    this.bufferFeatureOverlay.getFeatures().clear();
                }
                if (this.drawingFeatureOverlay){
                    this.drawingFeatureOverlay.getFeatures().clear();
                }
            },

            applyBuffer: function(){
                var self = this;
                var params = {
                    filter: ko.toJSON(this.query.filter)
                };
                if(this.query.filter.buffer.width() > 0 && this.drawingFeatureOverlay.getFeatures().getLength() > 0){
                    $.ajax({
                        type: "GET",
                        url: arches.urls.buffer,
                        data: {
                            filter: ko.toJSON(this.query.filter)
                        },
                        success: function(results){
                            var source = new ol.source.GeoJSON(({object:{type: 'FeatureCollection', features: [{type:'Feature', geometry: JSON.parse(results)}]}}));
                            var feature = source.getFeatures()[0];

                            feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
                            self.bufferFeatureOverlay.getFeatures().clear();
                            self.bufferFeatureOverlay.addFeature(feature);
                            self.zoomToExtent(feature.getGeometry().getExtent());
                        },
                        error: function(){}
                    });
                }else{
                    this.bufferFeatureOverlay.getFeatures().clear();
                }
            },

            toggleFilterSection: function(ele, expand){
                if(expand){
                    this.slideToggle(ele, 'show');
                }else{
                    this.slideToggle(ele, 'hide');
                }
            },

            slideToggle: function(ele, showOrHide){
                var self = this;
                if ($(ele).is(":visible") && showOrHide === 'hide'){
                    ele.slideToggle('slow');
                    return;
                }

                if (!($(ele).is(":visible")) && showOrHide === 'show'){
                    ele.slideToggle('slow', function(){
                        self.map.map.updateSize();
                    });
                    return;
                }

                if (!showOrHide){
                    ele.slideToggle('slow');
                }
            },

            restoreState: function(filter, expanded){
                this.map.map.once('change:size', function(){
                    if(typeof filter !== 'undefined' && 'geometry' in filter && filter.geometry.coordinates.length > 0){
                        this.query.filter.geometry.type(ko.utils.unwrapObservable(filter.geometry.type));
                        this.query.filter.geometry.coordinates(ko.utils.unwrapObservable(filter.geometry.coordinates));
                        this.query.filter.buffer.width(ko.utils.unwrapObservable(filter.buffer.width));
                        this.query.filter.buffer.unit(ko.utils.unwrapObservable(filter.buffer.unit));

                        var coordinates = this.query.filter.geometry.coordinates();
                        var type = this.query.filter.geometry.type();
                        if(type === 'bbox'){
                            this.map.map.on('moveend', this.onMoveEnd, this);

                            var extent = ol.proj.transformExtent(coordinates, 'EPSG:4326', 'EPSG:3857');
                            this.zoomToExtent(extent);

                        }else{
                            var feature = new ol.Feature({
                                geometry: new ol.geom[type](coordinates)
                            });

                            feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
                            this.zoomToExtent(feature.getGeometry().getExtent());
                            this.drawingFeatureOverlay.addFeature(feature);
                            this.changeDrawingTool(this.map.map, type);
                            this.disableDrawingTools();

                            feature.on('change', function(evt) {
                                var geometry = evt.target.getGeometry().clone();
                                geometry.transform('EPSG:3857', 'EPSG:4326');
                                this.query.filter.geometry.coordinates(geometry.getCoordinates());
                                //self.applyBuffer();
                            }, this);
                        }
                    }

                }, this);

                if(typeof expanded === 'undefined'){
                    expanded = false;
                }
                this.expanded(expanded);

            },

            clear: function(){
                this.removeDrawingTools();
                this.clearDrawingFeatures();
                this.query.filter.geometry.type('');
                this.query.filter.geometry.coordinates([]);
                this.map.map.un('moveend', this.onMoveEnd, this);
            }

        });
});<commit_msg>update point style on search map<commit_after>define(['jquery',
    'underscore',
    'backbone',
    'bootstrap',
    'arches',
    'views/map',
    'openlayers',
    'knockout',
    'map/resource-layer-model'],
    function($, _, Backbone, bootstrap, arches, MapView, ol, ko, ResourceLayerModel) {
        return Backbone.View.extend({

            events: {
                'click .layer-zoom': 'layerZoom'
            },

            initialize: function(options) {
                var self = this;

                //  Handle show/hide toggle ourselves
                $('#map-tools-btn').on('click', function(evt) {
                    if($(evt.currentTarget).hasClass('open')){
                        self.disableDrawingTools();
                    }
                    else {
                        self.enableDrawingTools();
                    }
                    $(evt.currentTarget).toggleClass('open');
                    return false;
                });
                $('#map-tools-dropdown').on('click', 'a', function(evt) {
                    if($(evt.target).attr('name') === 'map-tools'){
                        self.togglefilter(evt);
                    }
                    return false;
                });

                //  suppress default bahavior of the bootstrap menu to auto close
                $('#map-tools-btn').on('hide.bs.dropdown', false);
                $('#map-tools-btn').on('show.bs.dropdown', false);

                this.expanded = ko.observable(false);
                this.expanded.subscribe(function(status){
                    self.toggleFilterSection($('#map-filter'), status)
                });

                this.query = {
                    filter: {
                        geometry:{
                            type: ko.observable(''),
                            coordinates: ko.observable([])
                        },
                        buffer: {
                            width: ko.observable('0'),
                            unit: ko.observable('ft')
                        }
                    },
                    changed: ko.pureComputed(function(){
                        return (ko.toJSON(this.query.filter.geometry.coordinates()) +
                            ko.toJSON(this.query.filter.buffer.width()));
                    }, this).extend({ rateLimit: 200 })
                }

                ko.applyBindings(this.query.filter, $('#map-tools-dropdown')[0]);

                this.query.filter.buffer.width.subscribe(function(){
                    self.applyBuffer();
                });

                this.enabled = ko.computed(function(){
                    var enabled = (this.query.filter.geometry.type() !== '' && this.query.filter.geometry.coordinates().length !== 0);
                    this.trigger('enabled', enabled);
                    return enabled;
                }, this);

                this.vectorLayer = new ResourceLayerModel().layer;
                this.map = new MapView({
                    el: $('#map'),
                    overlays: [this.vectorLayer]
                });

                this.bufferFeatureOverlay = new ol.FeatureOverlay({
                    style: new ol.style.Style({
                        fill: new ol.style.Fill({
                            color: 'rgba(123, 123, 255, 0.5)'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#ff6633',
                            width: 2,
                            lineDash: [4,4]
                        })
                    })
                });
                this.bufferFeatureOverlay.setMap(this.map.map);

                this.drawingFeatureOverlay = new ol.FeatureOverlay({
                    style: new ol.style.Style({
                        fill: new ol.style.Fill({
                            color: 'rgba(255, 255, 255, 0.2)'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#ffcc33',
                            width: 2
                        })
                    })
                });
                this.drawingFeatureOverlay.setMap(this.map.map);

                this.zoomToExtent(this.vectorLayer.getLayers().item(0).getSource().getExtent())

                ko.applyBindings(this.map, $('#basemaps-panel')[0]);

                var hideAllPanels = function(){
                    $("#basemaps-panel").addClass("hidden");

                    //Update state of remaining buttons
                    $("#inventory-basemaps")
                        .removeClass("arches-map-tools-pressed")
                        .addClass("arches-map-tools")
                        .css("border-bottom-left-radius", "1px");
                };

                //Inventory-basemaps button opens basemap panel
                $("#inventory-basemaps").click(function (){
                    if ($(this).hasClass('arches-map-tools-pressed')) {
                        hideAllPanels();
                    } else {
                        $("#basemaps-panel").removeClass("hidden");

                        //Update state of current button and adjust position
                        $("#inventory-basemaps")
                            .addClass("arches-map-tools-pressed")
                            .removeClass("arches-map-tools")
                            .css("border-bottom-left-radius", "5px");
                    }
                });

                $(".basemap").click(function (){
                    var basemap = $(this).attr('id');
                    _.each(self.map.baseLayers, function(baseLayer){
                        baseLayer.layer.setVisible(baseLayer.id == basemap);
                    });
                    hideAllPanels();
                });

                //Close Button
                $(".close").click(function (){
                    hideAllPanels();
                });
            },

            zoomToExtent: function(extent){
                var size = this.map.map.getSize();
                var view = this.map.map.getView()
                view.fitExtent(
                    extent,
                    size
                );
            },

            hexToRgb: function (hex) {
                var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
                return result ? {
                    r: parseInt(result[1], 16),
                    g: parseInt(result[2], 16),
                    b: parseInt(result[3], 16)
                } : null;
            },

            highlightFeatures: function(resultsarray){
                var rgb = this.hexToRgb('#C4171D');
                var iconUnicode = '\uf060';

                var style = new ol.style.Style({
                    text: new ol.style.Text({
                        text: iconUnicode,
                        font: 'normal 33px octicons',
                        stroke: new ol.style.Stroke({
                            // color: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',1)',
                            color: 'white',
                            width: 3
                        }),
                        textBaseline: 'Bottom',
                        fill: new ol.style.Fill({
                            color: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',0.9)',
                        })
                    })
                });
                var shadowStyle = new ol.style.Style({
                    text: new ol.style.Text({
                        text: iconUnicode,
                        font: 'normal 38px octicons',
                        offsetX: 0,
                        rotation: 0.25,
                        textBaseline: 'Bottom',
                        fill: new ol.style.Fill({
                            color: 'rgba(126,126,126,0.3)',
                        })
                    })
                });
                if(!this.featureOverlay){
                    this.featureOverlay = new ol.FeatureOverlay({
                        map: this.map.map,
                        style: [shadowStyle,style]
                    });
                }
                this.featureOverlay.getFeatures().clear();

                _.each(resultsarray.results.hits.hits, function(result){
                    if(result._source.geometries.length > 0){
                        var feature = this.vectorLayer.getLayers().item(0).getSource().getFeatureById(result._id);
                        if(feature){
                            this.featureOverlay.addFeature(feature);
                        }
                    }
                }, this);
            },

            selectFeatureById: function(resourceid){
                var rgb = this.hexToRgb('#4CAE4C');
                var iconUnicode = '\uf060';

                if(!this.featureHightlightOverlay){
                    this.featureHightlightOverlay = new ol.FeatureOverlay({
                        map: this.map.map,
                        style: new ol.style.Style({
                            text: new ol.style.Text({
                                text: iconUnicode,
                                font: 'normal 33px octicons',
                                stroke: new ol.style.Stroke({
                                    // color: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',1)',
                                    color: 'white',
                                    width: 3
                                }),
                                textBaseline: 'Bottom',
                                fill: new ol.style.Fill({
                                    color: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',0.9)',
                                })
                            })
                        })
                    });
                }

                this.unselectAllFeatures();
                var feature = this.vectorLayer.getLayers().item(0).getSource().getFeatureById(resourceid);
                if(feature){
                    this.featureHightlightOverlay.addFeature(feature);
                    return feature;
                }
            },

            unselectAllFeatures: function(){
                this.featureHightlightOverlay.getFeatures().clear();
            },

            getMapExtent: function(){
                var extent = ol.proj.transformExtent(this.map.map.getView().calculateExtent(this.map.map.getSize()), 'EPSG:3857', 'EPSG:4326');
                return extent;
            },

            onMoveEnd: function(evt) {
                this.query.filter.geometry.coordinates(this.getMapExtent());
            },

            togglefilter: function(evt){
                var link = $(evt.target).closest('a');
                var data = link.data();
                var item = link.find('i');

                if (!(item.hasClass("fa-check"))){
                    this.enableFilter(data.tooltype);
                }else{
                    this.clear();
                }
            },

            enableFilter: function(tooltype){
                if(tooltype){
                    if(tooltype === 'map-extent'){
                        this.removeDrawingTools();
                        this.clearDrawingFeatures();
                        this.query.filter.geometry.type('bbox');
                        this.query.filter.geometry.coordinates(this.getMapExtent());
                        this.map.map.on('moveend', this.onMoveEnd, this);
                    }else{
                        this.clearDrawingFeatures();
                        this.query.filter.geometry.type(tooltype);
                        this.changeDrawingTool(this.map.map, tooltype);
                        this.map.map.un('moveend', this.onMoveEnd, this);
                    }
                }
            },

            changeDrawingTool: function(map, tooltype){
                this.disableDrawingTools();

                this.modifyTool = new ol.interaction.Modify({
                    features: this.drawingFeatureOverlay.getFeatures(),
                    // the SHIFT key must be pressed to delete vertices, so
                    // that new vertices can be drawn at the same position
                    // of existing vertices
                    deleteCondition: function(event) {
                        return ol.events.condition.shiftKeyOnly(event) &&
                                ol.events.condition.singleClick(event);
                    }
                });
                map.addInteraction(this.modifyTool);

                this.drawingtool = new ol.interaction.Draw({
                    features: this.drawingFeatureOverlay.getFeatures(),
                    type: tooltype
                });
                this.drawingtool.set('type', tooltype);

                this.drawingtool.on('drawstart', function(){
                    if(this.drawingtool.get('type') !== 'Point'){
                        this.clearDrawingFeatures();
                    }
                }, this);

                this.drawingtool.on('drawend', function(evt){
                    var self = this;
                    var geometry = evt.feature.getGeometry().clone();
                    geometry.transform('EPSG:3857', 'EPSG:4326');
                    this.query.filter.geometry.coordinates(geometry.getCoordinates());

                    //this.applyBuffer();

                    evt.feature.on('change', function(evt) {
                        var geometry = evt.target.getGeometry().clone();
                        geometry.transform('EPSG:3857', 'EPSG:4326');
                        self.query.filter.geometry.coordinates(geometry.getCoordinates());
                        //self.applyBuffer();
                    });
                }, this);

                this.enableDrawingTools();
            },

            enableDrawingTools: function(){
                if(this.drawingtool){
                    this.map.map.addInteraction(this.drawingtool);
                }
            },

            disableDrawingTools: function(){
                if(this.drawingtool){
                    this.map.map.removeInteraction(this.drawingtool);
                }
            },

            removeDrawingTools: function(){
                this.disableDrawingTools();
                delete this.drawingtool;
            },

            clearDrawingFeatures: function(){
                if (this.bufferFeatureOverlay){
                    this.bufferFeatureOverlay.getFeatures().clear();
                }
                if (this.drawingFeatureOverlay){
                    this.drawingFeatureOverlay.getFeatures().clear();
                }
            },

            applyBuffer: function(){
                var self = this;
                var params = {
                    filter: ko.toJSON(this.query.filter)
                };
                if(this.query.filter.buffer.width() > 0 && this.drawingFeatureOverlay.getFeatures().getLength() > 0){
                    $.ajax({
                        type: "GET",
                        url: arches.urls.buffer,
                        data: {
                            filter: ko.toJSON(this.query.filter)
                        },
                        success: function(results){
                            var source = new ol.source.GeoJSON(({object:{type: 'FeatureCollection', features: [{type:'Feature', geometry: JSON.parse(results)}]}}));
                            var feature = source.getFeatures()[0];

                            feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
                            self.bufferFeatureOverlay.getFeatures().clear();
                            self.bufferFeatureOverlay.addFeature(feature);
                            self.zoomToExtent(feature.getGeometry().getExtent());
                        },
                        error: function(){}
                    });
                }else{
                    this.bufferFeatureOverlay.getFeatures().clear();
                }
            },

            toggleFilterSection: function(ele, expand){
                if(expand){
                    this.slideToggle(ele, 'show');
                }else{
                    this.slideToggle(ele, 'hide');
                }
            },

            slideToggle: function(ele, showOrHide){
                var self = this;
                if ($(ele).is(":visible") && showOrHide === 'hide'){
                    ele.slideToggle('slow');
                    return;
                }

                if (!($(ele).is(":visible")) && showOrHide === 'show'){
                    ele.slideToggle('slow', function(){
                        self.map.map.updateSize();
                    });
                    return;
                }

                if (!showOrHide){
                    ele.slideToggle('slow');
                }
            },

            restoreState: function(filter, expanded){
                this.map.map.once('change:size', function(){
                    if(typeof filter !== 'undefined' && 'geometry' in filter && filter.geometry.coordinates.length > 0){
                        this.query.filter.geometry.type(ko.utils.unwrapObservable(filter.geometry.type));
                        this.query.filter.geometry.coordinates(ko.utils.unwrapObservable(filter.geometry.coordinates));
                        this.query.filter.buffer.width(ko.utils.unwrapObservable(filter.buffer.width));
                        this.query.filter.buffer.unit(ko.utils.unwrapObservable(filter.buffer.unit));

                        var coordinates = this.query.filter.geometry.coordinates();
                        var type = this.query.filter.geometry.type();
                        if(type === 'bbox'){
                            this.map.map.on('moveend', this.onMoveEnd, this);

                            var extent = ol.proj.transformExtent(coordinates, 'EPSG:4326', 'EPSG:3857');
                            this.zoomToExtent(extent);

                        }else{
                            var feature = new ol.Feature({
                                geometry: new ol.geom[type](coordinates)
                            });

                            feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
                            this.zoomToExtent(feature.getGeometry().getExtent());
                            this.drawingFeatureOverlay.addFeature(feature);
                            this.changeDrawingTool(this.map.map, type);
                            this.disableDrawingTools();

                            feature.on('change', function(evt) {
                                var geometry = evt.target.getGeometry().clone();
                                geometry.transform('EPSG:3857', 'EPSG:4326');
                                this.query.filter.geometry.coordinates(geometry.getCoordinates());
                                //self.applyBuffer();
                            }, this);
                        }
                    }

                }, this);

                if(typeof expanded === 'undefined'){
                    expanded = false;
                }
                this.expanded(expanded);

            },

            clear: function(){
                this.removeDrawingTools();
                this.clearDrawingFeatures();
                this.query.filter.geometry.type('');
                this.query.filter.geometry.coordinates([]);
                this.map.map.un('moveend', this.onMoveEnd, this);
            }

        });
});<|endoftext|>


<commit_before>'use strict'

const Controller = require('trails-controller')

/**
 * @module DefaultController
 *
 * @description Default Controller included with a new Trails app
 * @see {@link http://trailsjs.io/doc/api/controllers}
 * @this TrailsApp
 */
module.exports = class DefaultController extends Controller {

  /**
   * Return some info about this application
   */
  info (request, reply) {
    reply(this.app.api.services.DefaultService.getApplicationInfo())
  }
}
<commit_msg>[fix] fix service invocation<commit_after>'use strict'

const Controller = require('trails-controller')

/**
 * @module DefaultController
 *
 * @description Default Controller included with a new Trails app
 * @see {@link http://trailsjs.io/doc/api/controllers}
 * @this TrailsApp
 */
module.exports = class DefaultController extends Controller {

  /**
   * Return some info about this application
   */
  info (request, reply) {
    reply(this.app.services.DefaultService.getApplicationInfo())
  }
}
<|endoftext|>


<commit_before>'use strict';

function disconnect() {
	knex.destroy();
}

const knex = require('knex')({
  client: 'mysql',
  connection: {
    host: "localhost",
    user: "root",
    password: "",
    database: "ghost_copy"
  }
});

// Without using raw code it seems like the smallest integer
// I can store is INT which goes up to 10^9, I find this way overkill
// For so many of the ID fields especially.
// Do you think I should use raw code then? It just gets so ugly,
// and maybe those few extra bits of data don't matter? Or...
// I guess we could at least halve data usage on the id columns if we reduced it

const MAX_NAME_OR_SLUG_LENGTH = 70;
const MAX_DESCRIPTION_LENGTH = 170;
const MAX_BIOGRAPHY_LENGTH = 255;

// Start of script
knex.schema
// Reset database
.dropTableIfExists('issues_posts')
.dropTableIfExists('teams_authors')
.dropTableIfExists('authors_posts')
.dropTableIfExists('gazelle_posts')
.dropTableIfExists('issues_categories_order')
.dropTableIfExists('categories_posts_order')
.dropTableIfExists('authors')
.dropTableIfExists('categories')
.dropTableIfExists('teams')
.dropTableIfExists('issues')
// Create categories table
.createTable('categories', (table) => {
	table.increments('id').primary().unsigned();
	table.string('slug', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('name', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
})
// Create teams table
.createTable('teams', (table) => {
	table.increments('id').primary().unsigned();
	table.string('slug', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('name', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('description', MAX_DESCRIPTION_LENGTH);
	// Max 65,535 characters should be enough and is also what Ghost uses itself
	// And I left it nullable, then we can just input the default image
	// if an author is yet to give a picture of themselves
	table.text('image');
})
// Create issues table
.createTable('issues', (table) => {
	table.increments('id').primary().unsigned();
	table.string('slug', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('name', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.date('published_at');
})
// Create gazelle_posts table
.createTable('gazelle_posts', (table) => {
	table.integer('id').primary().unsigned().references('id').inTable('posts');
	table.integer('category_id').unsigned().references('id').inTable('categories');
	table.integer('views').unsigned().notNullable().defaultTo(0);
	table.date('gazelle_published_at');
})
// Create authors table
.createTable('authors', (table) => {
	table.increments('id').primary().unsigned();
	table.string('slug', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('name', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.integer('team_id').unsigned().references('id').inTable('teams');
	table.string('job_title', MAX_NAME_OR_SLUG_LENGTH);
	// This could also be made into a text, depends on whether we want to
	// constrain our authors to short biographies or not.
	// I left it nullable, we can handle default values while rendering
	table.string('biography', MAX_BIOGRAPHY_LENGTH)
	table.text('image')
})
// Create authors_posts table
.createTable('authors_posts', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('author_id').unsigned().notNullable().references('id').inTable('authors');
	table.integer('post_id').unsigned().notNullable().references('id').inTable('posts');
})
// Create teams_authors table
.createTable('teams_authors', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('team_id').unsigned().notNullable().references('id').inTable('teams');
	table.integer('author_id').unsigned().notNullable().references('id').inTable('authors');
})
// Create issues_posts table
.createTable('issues_posts', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('post_id').unsigned().notNullable().references('id').inTable('posts');
	table.integer('issue_id').unsigned().notNullable().references('id').inTable('issues');
})
// Create issues_categories_order table
.createTable('issues_categories_order', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('issue_id').unsigned().notNullable().references('id').inTable('issues');
	table.integer('category_id').unsigned().notNullable().references('id').inTable('categories');
	table.integer('sort_order').unsigned().notNullable().defaultTo(0);
	table.index(['issue_id', 'category_id', 'sort_order'], 'uniqueness_index');
})
// Create categories_posts_order table
.createTable('categories_posts_order', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('issue_id').unsigned().notNullable().references('id').inTable('issues');
	table.integer('category_id').unsigned().notNullable().references('id').inTable('categories');
	table.integer('post_id').unsigned().notNullable().references('id').inTable('posts');
	table.integer('sort_order').unsigned().notNullable().defaultTo(0);
	table.index(['issue_id', 'category_id', 'post_id', 'sort_order'], 'uniqueness_index');
})
.then((okPacketsArray) => {
	console.log("success");
})
.catch((err) => {
	throw err;
})
.then(disconnect());<commit_msg>added newline to end of file<commit_after>'use strict';

function disconnect() {
	knex.destroy();
}

const knex = require('knex')({
  client: 'mysql',
  connection: {
    host: "localhost",
    user: "root",
    password: "",
    database: "ghost_copy"
  }
});

// Without using raw code it seems like the smallest integer
// I can store is INT which goes up to 10^9, I find this way overkill
// For so many of the ID fields especially.
// Do you think I should use raw code then? It just gets so ugly,
// and maybe those few extra bits of data don't matter? Or...
// I guess we could at least halve data usage on the id columns if we reduced it

const MAX_NAME_OR_SLUG_LENGTH = 70;
const MAX_DESCRIPTION_LENGTH = 170;
const MAX_BIOGRAPHY_LENGTH = 255;

// Start of script
knex.schema
// Reset database
.dropTableIfExists('issues_posts')
.dropTableIfExists('teams_authors')
.dropTableIfExists('authors_posts')
.dropTableIfExists('gazelle_posts')
.dropTableIfExists('issues_categories_order')
.dropTableIfExists('categories_posts_order')
.dropTableIfExists('authors')
.dropTableIfExists('categories')
.dropTableIfExists('teams')
.dropTableIfExists('issues')
// Create categories table
.createTable('categories', (table) => {
	table.increments('id').primary().unsigned();
	table.string('slug', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('name', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
})
// Create teams table
.createTable('teams', (table) => {
	table.increments('id').primary().unsigned();
	table.string('slug', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('name', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('description', MAX_DESCRIPTION_LENGTH);
	// Max 65,535 characters should be enough and is also what Ghost uses itself
	// And I left it nullable, then we can just input the default image
	// if an author is yet to give a picture of themselves
	table.text('image');
})
// Create issues table
.createTable('issues', (table) => {
	table.increments('id').primary().unsigned();
	table.string('slug', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('name', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.date('published_at');
})
// Create gazelle_posts table
.createTable('gazelle_posts', (table) => {
	table.integer('id').primary().unsigned().references('id').inTable('posts');
	table.integer('category_id').unsigned().references('id').inTable('categories');
	table.integer('views').unsigned().notNullable().defaultTo(0);
	table.date('gazelle_published_at');
})
// Create authors table
.createTable('authors', (table) => {
	table.increments('id').primary().unsigned();
	table.string('slug', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.string('name', MAX_NAME_OR_SLUG_LENGTH).unique().notNullable();
	table.integer('team_id').unsigned().references('id').inTable('teams');
	table.string('job_title', MAX_NAME_OR_SLUG_LENGTH);
	// This could also be made into a text, depends on whether we want to
	// constrain our authors to short biographies or not.
	// I left it nullable, we can handle default values while rendering
	table.string('biography', MAX_BIOGRAPHY_LENGTH)
	table.text('image')
})
// Create authors_posts table
.createTable('authors_posts', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('author_id').unsigned().notNullable().references('id').inTable('authors');
	table.integer('post_id').unsigned().notNullable().references('id').inTable('posts');
})
// Create teams_authors table
.createTable('teams_authors', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('team_id').unsigned().notNullable().references('id').inTable('teams');
	table.integer('author_id').unsigned().notNullable().references('id').inTable('authors');
})
// Create issues_posts table
.createTable('issues_posts', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('post_id').unsigned().notNullable().references('id').inTable('posts');
	table.integer('issue_id').unsigned().notNullable().references('id').inTable('issues');
})
// Create issues_categories_order table
.createTable('issues_categories_order', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('issue_id').unsigned().notNullable().references('id').inTable('issues');
	table.integer('category_id').unsigned().notNullable().references('id').inTable('categories');
	table.integer('sort_order').unsigned().notNullable().defaultTo(0);
	table.index(['issue_id', 'category_id', 'sort_order'], 'uniqueness_index');
})
// Create categories_posts_order table
.createTable('categories_posts_order', (table) => {
	table.increments('id').primary().unsigned();
	table.integer('issue_id').unsigned().notNullable().references('id').inTable('issues');
	table.integer('category_id').unsigned().notNullable().references('id').inTable('categories');
	table.integer('post_id').unsigned().notNullable().references('id').inTable('posts');
	table.integer('sort_order').unsigned().notNullable().defaultTo(0);
	table.index(['issue_id', 'category_id', 'post_id', 'sort_order'], 'uniqueness_index');
})
.then((okPacketsArray) => {
	console.log("success");
})
.catch((err) => {
	throw err;
})
.then(disconnect());
<|endoftext|>


<commit_before>'use strict';

/**
 * Compute cost and estimate best configuration.
 */

module.exports.handler = (event, context, callback) => {

  const powerValues = process.env.powerValues.split(',');

  callback(null, "OK");

};
<commit_msg>Implemented finalizer<commit_after>'use strict';

const powerValues = process.env.powerValues.split(',');

/**
 * Receive avg prices and decides which config works better.
 */
module.exports.handler = (event, context, callback) => {

    const prices = event.prices;  // array?

    // TBD will prices be an object or a list?

    callback(null, "OK");

};
<|endoftext|>


<commit_before>define(function () {
    return ['$scope', '$http', function($scope, $http) {

function resetItem(){
   $scope.employee = {
      title : '',
      company : '',
      jobDesc : '',
      type : '',
      id : ''
   };
   $scope.displayForm = '';
   $scope.selectedType = '01';

}
resetItem();

 $scope.validate = function(item){
  return $scope.selectedType==''?item.type=='':item.type==$scope.selectedType;
}

 $scope.addItem = function () {
   resetItem();
   $scope.displayForm = true;
 }

$scope.saveItem = function () {
  var emp = $scope.employee;
      if (emp.id.length == 0){
            $http.post('/employee/create', emp).success(function(data) {
              $scope.items.push(data);
              $scope.displayForm = '';
              removeModal();
            }).
  error(function(data) {
    console.log(data);
  });
          }
          else{
            $http.post('/employee/update/'+ emp.id, emp).success(function(data) {
              $scope.displayForm = '';
              removeModal();
            }).
  error(function(data, status, headers, config) {
    alert(data.summary);
  });
          }
        };

$scope.editItem = function (data) {
        $scope.employee = data;
        $scope.displayForm = true;
}

        $scope.removeItem = function (data) {
          // if (confirm('Do you really want to delete?')){
            $http['delete']('/employee/' + data.id).success(function() {
              $scope.items.splice($scope.items.indexOf(data), 1);
            });
          // }
        };

        $http.get('/employee/find?sort=updatedAt DESC').success(function(data) {
          for (var i = 0; i < data.length; i++) {
            data[i].index = i;
          }
          $scope.items = data;
        });

        function removeModal(){
          $('.modal').modal('hide');
      }

    }];
});<commit_msg>add item as unshift<commit_after>define(function () {
    return ['$scope', '$http', function($scope, $http) {

function resetItem(){
   $scope.employee = {
      title : '',
      company : '',
      jobDesc : '',
      type : '',
      id : ''
   };
   $scope.displayForm = '';
   $scope.selectedType = '01';

}
resetItem();

 $scope.validate = function(item){
  return $scope.selectedType==''?item.type=='':item.type==$scope.selectedType;
}

 $scope.addItem = function () {
   resetItem();
   $scope.displayForm = true;
 }

$scope.saveItem = function () {
  var emp = $scope.employee;
      if (emp.id.length == 0){
            $http.post('/employee/create', emp).success(function(data) {
              $scope.items.unshift(data);
              $scope.displayForm = '';
              removeModal();
            }).
  error(function(data) {
    console.log(data);
  });
          }
          else{
            $http.post('/employee/update/'+ emp.id, emp).success(function(data) {
              $scope.displayForm = '';
              removeModal();
            }).
  error(function(data, status, headers, config) {
    alert(data.summary);
  });
          }
        };

$scope.editItem = function (data) {
        $scope.employee = data;
        $scope.displayForm = true;
}

        $scope.removeItem = function (data) {
          // if (confirm('Do you really want to delete?')){
            $http['delete']('/employee/' + data.id).success(function() {
              $scope.items.splice($scope.items.indexOf(data), 1);
            });
          // }
        };

        $http.get('/employee/find?sort=updatedAt DESC').success(function(data) {
          for (var i = 0; i < data.length; i++) {
            data[i].index = i;
          }
          $scope.items = data;
        });

        function removeModal(){
          $('.modal').modal('hide');
      }

    }];
});<|endoftext|>


<commit_before>assets/js/locales/bootstrap-wysihtml5.es-ES.js
<commit_msg>Update bootstrap-wysihtml5.it-IT.js<commit_after>/**
* Italian  translation for bootstrap-wysihtml5 by Mirko Tebaldi
*/
(function($){
    $.fn.wysihtml5.locale["it-IT"] = {
        font_styles: {
              normal: "Normale",
              h1: "Títolo 1",
              h2: "Títolo 2"
        },
        emphasis: {
              bold: "Grassetto",
              italic: "Corsivo",
              underline: "Sottolineato"
        },
        lists: {
              unordered: "Elenco puntato",
              ordered: "Elenco numerato",
              outdent: "Riduci rientro",
              indent: "Aumenta rientro"
        },
        link: {
              insert: "Inserisci Link",
              cancel: "Rimuovi"
        },
        image: {
              insert: "Inserisci immagine",
              cancel: "Rimuovi"
        },
        html: {
            edit: "Modifica HTML"
        }
    };
    $.fn.wysihtml5.locale["it"] = $.fn.wysihtml5.locale["it-IT"];
    $.fn.wysihtml5.locale["IT"] = $.fn.wysihtml5.locale["it-IT"];
}(jQuery));
<|endoftext|>


<commit_before>/*
 * Copyright 2020 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.
 */

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { format } from '@wordpress/date';

/**
 * External dependencies
 */
import moment from 'moment';

/**
 * Internal dependencies
 */
import {
  DEFAULT_DATE_FORMATTING,
  getTimeFromNow,
  isToday,
  isYesterday,
} from './';

// Returns hours since date if date passed in matches today
// Returns yesterday if date passed in is yesterday
// Returns formatted date + time by default
export function getTimeSensitiveDisplayDate(
  date,
  dateFormatting = DEFAULT_DATE_FORMATTING
) {
  if (!date) {
    return '';
  }
  const displayDate = moment.isMoment(date) ? date : moment(date);
  if (isToday(displayDate)) {
    return getTimeFromNow(displayDate, dateFormatting);
  } else if (isYesterday(displayDate)) {
    return __('yesterday', 'web-stories');
  }

  return format(dateFormatting?.dateFormat, displayDate);
}
<commit_msg>timezone wip<commit_after>/*
 * Copyright 2020 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.
 */

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { format } from '@wordpress/date';

/**
 * External dependencies
 */
import moment from 'moment';

/**
 * Internal dependencies
 */
import {
  DEFAULT_DATE_FORMATTING,
  getTimeFromNow,
  isToday,
  isYesterday,
} from './';

// Returns hours since date if date passed in matches today
// Returns yesterday if date passed in is yesterday
// Returns formatted date + time by default
export function getTimeSensitiveDisplayDate(
  date,
  dateFormatting = DEFAULT_DATE_FORMATTING
) {
  if (!date) {
    return '';
  }
  console.log('date formatting: ', dateFormatting);
  const displayDate = moment.isMoment(date) ? date : moment(date);

  if (isToday(displayDate)) {
    return getTimeFromNow(displayDate, dateFormatting);
  } else if (isYesterday(displayDate)) {
    return __('yesterday', 'web-stories');
  }

  return format(dateFormatting?.dateFormat, displayDate);
}
<|endoftext|>


<commit_before>/*
 * Inspired by Tom Mac Wright article :
 * http://mapbox.com/osmdev/2012/11/20/getting-serious-about-svg/
 */

(function () {

var __onAdd = L.Polyline.prototype.onAdd,
    __onRemove = L.Polyline.prototype.onRemove,
    __updatePath = L.Polyline.prototype._updatePath,
    __bringToFront = L.Polyline.prototype.bringToFront;

var PolylineTextPath = {

    onAdd: function (map) {
        __onAdd.call(this, map);
        this._textRedraw();
    },

    onRemove: function (map) {
        map = map || this._map;
        if (map && this._textNode)
            map._pathRoot.removeChild(this._textNode);
        __onRemove.call(this, map);
    },

    bringToFront: function () {
        __bringToFront.call(this);
        this._textRedraw();
    },

    _updatePath: function () {
        __updatePath.call(this);
        this._textRedraw();
    },

    _textRedraw: function () {
        var text = this._text,
            options = this._textOptions;
        if (text) {
            this.setText(null).setText(text, options);
        }
    },

    setText: function (text, options) {
        this._text = text;
        this._textOptions = options;

        /* If not in SVG mode or Polyline not added to map yet return */
        /* setText will be called by onAdd, using value stored in this._text */
        if (!L.Browser.svg || typeof this._map === 'undefined') {
          return this;
        }

        var defaults = {
            repeat: false,
            fillColor: 'black',
            attributes: {},
            below: false,
        };
        options = L.Util.extend(defaults, options);

        /* If empty text, hide */
        if (!text) {
            if (this._textNode && this._textNode.parentNode) {
                this._map._pathRoot.removeChild(this._textNode);

                /* delete the node, so it will not be removed a 2nd time if the layer is later removed from the map */
                delete this._textNode;
            }
            return this;
        }

        text = text.replace(/ /g, '\u00A0');  // Non breakable spaces
        var id = 'pathdef-' + L.Util.stamp(this);
        var svg = this._map._pathRoot;
        this._path.setAttribute('id', id);

        if (options.repeat) {
            /* Compute single pattern length */
            var pattern = L.Path.prototype._createElement('text');
            for (var attr in options.attributes)
                pattern.setAttribute(attr, options.attributes[attr]);
            pattern.appendChild(document.createTextNode(text));
            svg.appendChild(pattern);
            var alength = pattern.getComputedTextLength();
            svg.removeChild(pattern);

            /* Create string as long as path */
            text = new Array(Math.ceil(this._path.getTotalLength() / alength)).join(text);
        }

        /* Put it along the path using textPath */
        var textNode = L.Path.prototype._createElement('text'),
            textPath = L.Path.prototype._createElement('textPath');

        var dy = options.offset || this._path.getAttribute('stroke-width');

        textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", '#'+id);
        textNode.setAttribute('dy', dy);
        for (var attr in options.attributes)
            textNode.setAttribute(attr, options.attributes[attr]);
        textPath.appendChild(document.createTextNode(text));
        textNode.appendChild(textPath);
        this._textNode = textNode;

        if (options.below) {
            svg.insertBefore(textNode, svg.firstChild);
        }
        else {
            svg.appendChild(textNode);
        }

        /* Center text according to the path's bounding box */
        if (options.center) {
            var textWidth = textNode.getBBox().width;
            var pathWidth = this._path.getBoundingClientRect().width;
            /* Set the position for the left side of the textNode */
            textNode.setAttribute('dx', ((pathWidth / 2) - (textWidth / 2)));
        }

        /* Initialize mouse events for the additional nodes */
        if (this.options.clickable) {
            if (L.Browser.svg || !L.Browser.vml) {
                textPath.setAttribute('class', 'leaflet-clickable');
            }

            L.DomEvent.on(textNode, 'click', this._onMouseClick, this);

            var events = ['dblclick', 'mousedown', 'mouseover',
                          'mouseout', 'mousemove', 'contextmenu'];
            for (var i = 0; i < events.length; i++) {
                L.DomEvent.on(textNode, events[i], this._fireMouseEvent, this);
            }
        }

        return this;
    }
};

L.Polyline.include(PolylineTextPath);

L.LayerGroup.include({
    setText: function(text, options) {
        for (var layer in this._layers) {
            if (typeof this._layers[layer].setText === 'function') {
                this._layers[layer].setText(text, options);
            }
        }
        return this;
    }
});

})();
<commit_msg>Added option flipvertical<commit_after>/*
 * Inspired by Tom Mac Wright article :
 * http://mapbox.com/osmdev/2012/11/20/getting-serious-about-svg/
 */

(function () {

var __onAdd = L.Polyline.prototype.onAdd,
    __onRemove = L.Polyline.prototype.onRemove,
    __updatePath = L.Polyline.prototype._updatePath,
    __bringToFront = L.Polyline.prototype.bringToFront;

var PolylineTextPath = {

    onAdd: function (map) {
        __onAdd.call(this, map);
        this._textRedraw();
    },

    onRemove: function (map) {
        map = map || this._map;
        if (map && this._textNode)
            map._pathRoot.removeChild(this._textNode);
        __onRemove.call(this, map);
    },

    bringToFront: function () {
        __bringToFront.call(this);
        this._textRedraw();
    },

    _updatePath: function () {
        __updatePath.call(this);
        this._textRedraw();
    },

    _textRedraw: function () {
        var text = this._text,
            options = this._textOptions;
        if (text) {
            this.setText(null).setText(text, options);
        }
    },

    setText: function (text, options) {
        this._text = text;
        this._textOptions = options;

        /* If not in SVG mode or Polyline not added to map yet return */
        /* setText will be called by onAdd, using value stored in this._text */
        if (!L.Browser.svg || typeof this._map === 'undefined') {
          return this;
        }

        var defaults = {
            repeat: false,
            fillColor: 'black',
            attributes: {},
            below: false,
        };
        options = L.Util.extend(defaults, options);

        /* If empty text, hide */
        if (!text) {
            if (this._textNode && this._textNode.parentNode) {
                this._map._pathRoot.removeChild(this._textNode);

                /* delete the node, so it will not be removed a 2nd time if the layer is later removed from the map */
                delete this._textNode;
            }
            return this;
        }

        text = text.replace(/ /g, '\u00A0');  // Non breakable spaces
        var id = 'pathdef-' + L.Util.stamp(this);
        var svg = this._map._pathRoot;
        this._path.setAttribute('id', id);

        if (options.repeat) {
            /* Compute single pattern length */
            var pattern = L.Path.prototype._createElement('text');
            for (var attr in options.attributes)
                pattern.setAttribute(attr, options.attributes[attr]);
            pattern.appendChild(document.createTextNode(text));
            svg.appendChild(pattern);
            var alength = pattern.getComputedTextLength();
            svg.removeChild(pattern);

            /* Create string as long as path */
            text = new Array(Math.ceil(this._path.getTotalLength() / alength)).join(text);
        }

        /* Put it along the path using textPath */
        var textNode = L.Path.prototype._createElement('text'),
            textPath = L.Path.prototype._createElement('textPath');

        var dy = options.offset || this._path.getAttribute('stroke-width');

        textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", '#'+id);
        textNode.setAttribute('dy', dy);
        for (var attr in options.attributes)
            textNode.setAttribute(attr, options.attributes[attr]);
        textPath.appendChild(document.createTextNode(text));
        textNode.appendChild(textPath);
        this._textNode = textNode;

        if (options.below) {
            svg.insertBefore(textNode, svg.firstChild);
        }
        else {
            svg.appendChild(textNode);
        }

        /* Center text according to the path's bounding box */
        if (options.center) {
            var textWidth = textNode.getBBox().width;
            var pathWidth = this._path.getBoundingClientRect().width;
            /* Set the position for the left side of the textNode */
            textNode.setAttribute('dx', ((pathWidth / 2) - (textWidth / 2)));
        }

        if (options.flipvertical) {
			var rotatecenterX = (textNode.getBBox().x + textNode.getBBox().width / 2);
			var rotatecenterY = (textNode.getBBox().y + textNode.getBBox().height / 2);
			textNode.setAttribute('transform', 'rotate(90 ' + rotatecenterX + ' ' + rotatecenterY + ')');
		}

        /* Initialize mouse events for the additional nodes */
        if (this.options.clickable) {
            if (L.Browser.svg || !L.Browser.vml) {
                textPath.setAttribute('class', 'leaflet-clickable');
            }

            L.DomEvent.on(textNode, 'click', this._onMouseClick, this);

            var events = ['dblclick', 'mousedown', 'mouseover',
                          'mouseout', 'mousemove', 'contextmenu'];
            for (var i = 0; i < events.length; i++) {
                L.DomEvent.on(textNode, events[i], this._fireMouseEvent, this);
            }
        }

        return this;
    }
};

L.Polyline.include(PolylineTextPath);

L.LayerGroup.include({
    setText: function(text, options) {
        for (var layer in this._layers) {
            if (typeof this._layers[layer].setText === 'function') {
                this._layers[layer].setText(text, options);
            }
        }
        return this;
    }
});

})();
<|endoftext|>


<commit_before>/*eslint-env browser */
const ASCII_ENTER = 13;

var english = null;
var japanese = null;

var count = -1;
var remaining = -1;
var idx = -1;

var files = null;
var fileCounter = 0;
var wordCounter = 0;

var front = true;

function handleFileSelect(e) {
	wordCounter = 0;
	fileCounter = 0;
	english = [];
	japanese = [];
	files = e.target.files;
	var reader = new FileReader();

	reader.onload = function(e) {
		var text = reader.result;
		var strings = text.split("\r");
		for (var i = 0; i < strings.length / 2; i++) {
			english[wordCounter] = strings[i * 2].trim();
			japanese[wordCounter] = strings[(i * 2) + 1].trim();
			wordCounter++;
		}
		count = english.length;
		remaining = count;

		fileCounter++;

		if (fileCounter !== files.length) {
			reader.readAsText(files[fileCounter], "UTF-8");
		} else {
			document.getElementById("startBtn").disabled = false;
			document.getElementById("nextBtn").disabled = false;
			show();
		}
	};

	reader.readAsText(files[fileCounter], "UTF-8");
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);

function updateFlashCard() {
	if (front) {
		document.getElementById("frontContent").innerHTML = japanese[idx];
		document.getElementById("frontTable").style.visibility = "visible";
		document.getElementById("backTable").style.visibility = "hidden";
	} else {
		document.getElementById("frontTable").style.visibility = "hidden";
		document.getElementById("backTable").style.visibility = "visible";
		document.getElementById("backContent").innerHTML = japanese[idx];
	}
}

function show() {
	idx = Math.floor(Math.random() * remaining);
	updateFlashCard();
	document.getElementById("remaining").innerHTML = "残り： " + remaining + "/" + wordCounter;
	document.getElementById("input").value = "";
}

function onClick() {
	var input = document.getElementById("input");
	if (input.disabled) {
		return;
	}

	if (input.value === english[idx]) {
		remaining--;
		english[idx] = english[remaining];
		japanese[idx] = japanese[remaining];

		document.getElementById("mistake").innerHTML = "";

		if (remaining === 0) {
			showReport();
		} else {
			front = !front;
			show();

			var card = document.getElementById("card");
			if (card.className === "card") {
				card.className = "card flipped";
			} else {
				card.className = "card";
			}
		}
	} else {
		document.getElementById("mistake").innerHTML = "間違った！";
	}
}

var countdownTime = 5;
var remainingTime = -1;

/**
 * The desired time limit for a time trial. Will be -1 if the run is not a time trial.
 */
var timeLimit = -1;

/**
 * The time when the user started the run.
 */
var startTime = -1;

function startCountdown() {
	// hide the setup popup
	document.getElementById("openModal").style.display = "none";

	if (document.getElementById("timeCheckbox").checked) {
		// show the timer
		document.getElementById("countdown").style.display = "inline";
		drawCountdownCanvas();
	} else {
		// not a time trial, remove the field for showing the remaining time
		document.getElementById("remainingTime").style.display = "none";
		// show the content
		document.getElementById("body").style.background = "#eeeeee";
		document.getElementById("content").style.display = "inline";
		// enable the input field and grant it focus
		document.getElementById("input").disabled = false;
		document.getElementById("input").focus();
		startTime = new Date().getTime();
	}
}

function showReport() {
	var current = new Date().getTime();
	startTime = current - startTime;

	document.getElementById("backContent").innerHTML = "";
	document.getElementById("frontContent").innerHTML = "";
	document.getElementById("nextBtn").disabled = true;
	document.getElementById("input").disabled = true;

	if (remainingTime === -1) {
		// not a time trial, just tell the user how much time they used
		document.getElementById("reportTimeLimit").style.display = "none";
		document.getElementById("reportRemainingTime").innerHTML = "使った時間：" + (startTime / 1000) + "秒";
		document.getElementById("reportRemainingCards").innerHTML = "カード枚数：" + wordCounter;
	} else if (remainingTime > 0) {
		// completed before the time trial ended, show the time used
		document.getElementById("reportTimeLimit").innerHTML = "時間制限：" + timeLimit + "秒";
		document.getElementById("reportRemainingTime").innerHTML = "使った時間：" + (startTime / 1000) + "秒";
		document.getElementById("reportRemainingCards").innerHTML = "カード枚数：" + wordCounter;
	} else {
		// failed the time trial, show the remaining number of cards
		document.getElementById("reportTimeLimit").innerHTML = "時間制限：" + timeLimit + "秒";
		document.getElementById("reportRemainingCards").innerHTML = "残りカード：" + remaining;
	}
	document.getElementById("body").style.background = "#333333";
	document.getElementById("content").style.display = "none";
	document.getElementById("report").style.display = "inline";
}

function startTimeTrial() {
	timeLimit = parseInt(document.getElementById("time").value, 10);
	remainingTime = timeLimit;

	document.getElementById("remainingTime").innerHTML = remainingTime + "秒";
	setTimeout(timer, 1000);
}

function timer() {
	remainingTime--;
	document.getElementById("remainingTime").innerHTML = remainingTime + "秒";
	if (remainingTime === 0) {
		showReport();
	} else {
		setTimeout(timer, 1000);
	}
}

function keyDownHandler(e) {
	if (e.keyCode === ASCII_ENTER && remaining !== 0) {
		onClick();
	}
}

document.addEventListener("keydown", keyDownHandler, false);

var canvas = document.getElementById("countdownCanvas");
var ctx = canvas.getContext("2d");
var startPoint = 0 - (Math.PI / 2);

var start = -1;
var time = 5;

function drawCountdownCanvas() {
	if (start === -1) {
		start = new Date().getTime();
	}
	var now = new Date().getTime();
	if (now - start >= time * 1000) {
		ctx.fillStyle = "black";
		ctx.clearRect(0, 0, canvas.width, canvas.height);
		ctx.beginPath();
		ctx.moveTo(250, 250);
		ctx.arc(250, 250, 200, startPoint, Math.PI * 2);
			ctx.fill();
		ctx.closePath();

		ctx.fillStyle = "#eeeeee";
		ctx.beginPath();
		ctx.moveTo(250, 250);
		ctx.arc(250, 250, 190, startPoint, Math.PI * 2);
		ctx.fill();

		// show the content
		document.getElementById("body").style.background = "#ffffff";
		document.getElementById("content").style.display = "inline";
		// hide the countdown timer
		document.getElementById("countdown").style.display = "none";
		// enable the input field and grant it focus
		document.getElementById("input").disabled = false;
		document.getElementById("input").focus();
		startTime = new Date().getTime();

		startTimeTrial();
		return;
	}

	var pct = ((now - start) % 1000) / 1000;

	ctx.fillStyle = "black";
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.beginPath();
	ctx.moveTo(250, 250);
	ctx.arc(250, 250, 200, startPoint, startPoint + (Math.PI * 2 * (pct)));
		ctx.fill();
	ctx.closePath();

	ctx.fillStyle = "#eeeeee";
	ctx.beginPath();
	ctx.moveTo(250, 250);
	ctx.arc(250, 250, 190, startPoint, startPoint + (Math.PI * 2 * (pct)));
		ctx.fill();
	ctx.closePath();

	ctx.beginPath();
	ctx.font = "400px Calibri";
	ctx.fillStyle = "black";
	ctx.textAlign = "center";
	ctx.textBaseline = "middle";
	ctx.fillText(5 - Math.floor((now - start) / 1000), 250, 250);
	ctx.closePath();

	requestAnimationFrame(drawCountdownCanvas);
}
<commit_msg>Add dynamic colours to the pie timer<commit_after>/*eslint-env browser */
const ASCII_ENTER = 13;

var english = null;
var japanese = null;

var count = -1;
var remaining = -1;
var idx = -1;

var files = null;
var fileCounter = 0;
var wordCounter = 0;

var front = true;

function handleFileSelect(e) {
	wordCounter = 0;
	fileCounter = 0;
	english = [];
	japanese = [];
	files = e.target.files;
	var reader = new FileReader();

	reader.onload = function(e) {
		var text = reader.result;
		var strings = text.split("\r");
		for (var i = 0; i < strings.length / 2; i++) {
			english[wordCounter] = strings[i * 2].trim();
			japanese[wordCounter] = strings[(i * 2) + 1].trim();
			wordCounter++;
		}
		count = english.length;
		remaining = count;

		fileCounter++;

		if (fileCounter !== files.length) {
			reader.readAsText(files[fileCounter], "UTF-8");
		} else {
			document.getElementById("startBtn").disabled = false;
			document.getElementById("nextBtn").disabled = false;
			show();
		}
	};

	reader.readAsText(files[fileCounter], "UTF-8");
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);

function updateFlashCard() {
	if (front) {
		document.getElementById("frontContent").innerHTML = japanese[idx];
		document.getElementById("frontTable").style.visibility = "visible";
		document.getElementById("backTable").style.visibility = "hidden";
	} else {
		document.getElementById("frontTable").style.visibility = "hidden";
		document.getElementById("backTable").style.visibility = "visible";
		document.getElementById("backContent").innerHTML = japanese[idx];
	}
}

function show() {
	idx = Math.floor(Math.random() * remaining);
	updateFlashCard();
	document.getElementById("remaining").innerHTML = "残り： " + remaining + "/" + wordCounter;
	document.getElementById("input").value = "";
}

function onClick() {
	var input = document.getElementById("input");
	if (input.disabled) {
		return;
	}

	if (input.value === english[idx]) {
		remaining--;
		english[idx] = english[remaining];
		japanese[idx] = japanese[remaining];

		document.getElementById("mistake").innerHTML = "";

		if (remaining === 0) {
			showReport();
		} else {
			front = !front;
			show();

			var card = document.getElementById("card");
			if (card.className === "card") {
				card.className = "card flipped";
			} else {
				card.className = "card";
			}
		}
	} else {
		document.getElementById("mistake").innerHTML = "間違った！";
	}
}

var countdownTime = 5;
var remainingTime = -1;

/**
 * The desired time limit for a time trial. Will be -1 if the run is not a time trial.
 */
var timeLimit = -1;

/**
 * The time when the user started the run.
 */
var startTime = -1;

function startCountdown() {
	// hide the setup popup
	document.getElementById("openModal").style.display = "none";

	if (document.getElementById("timeCheckbox").checked) {
		// show the timer
		document.getElementById("countdown").style.display = "inline";
		drawCountdownCanvas();
	} else {
		// not a time trial, remove the field for showing the remaining time
		document.getElementById("remainingTime").style.display = "none";
		// show the content
		document.getElementById("body").style.background = "#eeeeee";
		document.getElementById("content").style.display = "inline";
		// enable the input field and grant it focus
		document.getElementById("input").disabled = false;
		document.getElementById("input").focus();
		startTime = new Date().getTime();
	}
}

function showReport() {
	var current = new Date().getTime();
	startTime = current - startTime;

	document.getElementById("backContent").innerHTML = "";
	document.getElementById("frontContent").innerHTML = "";
	document.getElementById("nextBtn").disabled = true;
	document.getElementById("input").disabled = true;

	if (remainingTime === -1) {
		// not a time trial, just tell the user how much time they used
		document.getElementById("reportTimeLimit").style.display = "none";
		document.getElementById("reportRemainingTime").innerHTML = "使った時間：" + (startTime / 1000) + "秒";
		document.getElementById("reportRemainingCards").innerHTML = "カード枚数：" + wordCounter;
	} else if (remainingTime > 0) {
		// completed before the time trial ended, show the time used
		document.getElementById("reportTimeLimit").innerHTML = "時間制限：" + timeLimit + "秒";
		document.getElementById("reportRemainingTime").innerHTML = "使った時間：" + (startTime / 1000) + "秒";
		document.getElementById("reportRemainingCards").innerHTML = "カード枚数：" + wordCounter;
	} else {
		// failed the time trial, show the remaining number of cards
		document.getElementById("reportTimeLimit").innerHTML = "時間制限：" + timeLimit + "秒";
		document.getElementById("reportRemainingCards").innerHTML = "残りカード：" + remaining;
	}
	document.getElementById("body").style.background = "#333333";
	document.getElementById("content").style.display = "none";
	document.getElementById("report").style.display = "inline";
}

function startTimeTrial() {
	timeLimit = parseInt(document.getElementById("time").value, 10);
	remainingTime = timeLimit;

	document.getElementById("remainingTime").innerHTML = remainingTime + "秒";
	setTimeout(timer, 1000);
}

function timer() {
	remainingTime--;
	document.getElementById("remainingTime").innerHTML = remainingTime + "秒";
	if (remainingTime === 0) {
		showReport();
	} else {
		setTimeout(timer, 1000);
	}
}

function keyDownHandler(e) {
	if (e.keyCode === ASCII_ENTER && remaining !== 0) {
		onClick();
	}
}

document.addEventListener("keydown", keyDownHandler, false);

var canvas = document.getElementById("countdownCanvas");
var ctx = canvas.getContext("2d");
var startPoint = 0 - (Math.PI / 2);

var start = -1;
var time = 5;

function drawCountdownCanvas() {
	if (start === -1) {
		start = new Date().getTime();
	}
	var now = new Date().getTime();
	if (now - start >= time * 1000) {
		ctx.clearRect(0, 0, canvas.width, canvas.height);
		ctx.shadowOffsetX = 0;
		ctx.shadowOffsetY = 0;

		ctx.fillStyle = "black";
		ctx.beginPath();
		ctx.moveTo(250, 250);
		ctx.arc(250, 250, 200, startPoint, Math.PI * 2);
			ctx.fill();
		ctx.closePath();

		ctx.fillStyle = "#eeeeee";
		ctx.beginPath();
		ctx.moveTo(250, 250);
		ctx.arc(250, 250, 190, startPoint, Math.PI * 2);
		ctx.fill();

		// show the content
		document.getElementById("body").style.background = "#ffffff";
		document.getElementById("content").style.display = "inline";
		// hide the countdown timer
		document.getElementById("countdown").style.display = "none";
		// enable the input field and grant it focus
		document.getElementById("input").disabled = false;
		document.getElementById("input").focus();
		startTime = new Date().getTime();

		startTimeTrial();
		return;
	}

	var pct = ((now - start) % 1000) / 1000;
	var timeLeft = 5 - Math.floor((now - start) / 1000);

	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.shadowOffsetX = 0;
	ctx.shadowOffsetY = 0;

	switch (timeLeft) {
		case 5:
		case 4:
			ctx.fillStyle = "#33cc33";
			break;
		case 3:
		case 2:
			ctx.fillStyle = "#cccc00";
			break;
		case 1:
			ctx.fillStyle = "#cc0000";
			break;
	}
	ctx.beginPath();
	ctx.moveTo(250, 250);
	ctx.arc(250, 250, 230, startPoint, startPoint + (Math.PI * 2 * (.2 * (6 - timeLeft))));
	ctx.fill();
	ctx.closePath();

	ctx.beginPath();
	ctx.fillStyle = "#333333";
	ctx.moveTo(250, 250);
	ctx.arc(250, 250, 215, startPoint, Math.PI * 2);
	ctx.fill();
	ctx.closePath();

	ctx.beginPath();
	ctx.fillStyle = "white";
	ctx.moveTo(250, 250);
	ctx.arc(250, 250, 200, startPoint, startPoint + (Math.PI * 2 * (pct)));
	ctx.fill();
	ctx.closePath();

	switch (timeLeft) {
		case 5:
		case 4:
			ctx.fillStyle = "#33cc33";
			break;
		case 3:
		case 2:
			ctx.fillStyle = "#cccc00";
			break;
		case 1:
			ctx.fillStyle = "#cc0000";
			break;
	}

	ctx.beginPath();
	ctx.moveTo(250, 250);
	ctx.arc(250, 250, 190, startPoint, startPoint + (Math.PI * 2 * (pct)));
	ctx.fill();
	ctx.closePath();

	ctx.beginPath();
	ctx.font = "400px Calibri";
	ctx.fillStyle = "white";
	ctx.shadowColor = "black";
	ctx.shadowOffsetX = 5;
	ctx.shadowOffsetY = 5;
	ctx.textAlign = "center";
	ctx.textBaseline = "middle";
	ctx.fillText(timeLeft, 250, 250);
	ctx.closePath();

	requestAnimationFrame(drawCountdownCanvas);
}
<|endoftext|>


<commit_before>Error.captureStackTrace = Error.captureStackTrace || function (obj) {
  obj.stack = [{ toString: null }];
};

exports.generate  = require("./generator");
exports.transform = require("./transform");
<commit_msg>add Error.captureStackTrace polyfill so browser build will work in non-v8 environments - fixes #107<commit_after>Error.captureStackTrace = Error.captureStackTrace || function (obj) {
  if (Error.prepareStackTrace) {
    var frame = {
      isEval: function () { return false; },
      getFileName: function () { return "filename"; },
      getLineNumber: function () { return 1; },
      getColumnNumber: function () { return 1; },
      getFunctionName: function () { return "functionName" }
    };

    obj.stack = Error.prepareStackTrace(obj, [frame, frame, frame]);
  } else {
    obj.stack = obj.stack || obj.name || "Error";
  }
};

console.log("omg hi");

exports.generate  = require("./generator");
exports.transform = require("./transform");
<|endoftext|>


<commit_before>var sentimentQueue = [];

function processSentimentQueue() {
    var averageSentiment = 0;
    var newSound = false;

    if (sentimentQueue.length != 0) {
        newSound = true;
        var sum = 0;

        for (var i = 0; i < sentimentQueue.length; i++) {
            sum += sentimentQueue[i];
        }

        averageSentiment = Math.round(sum / sentimentQueue.length);

        sentimentQueue = [];
    }

    if (newSound) {
        var note = Math.round(((averageSentiment + 100) / 200) * 86) + 1;
        playNote(note);
    }

    setTimeout(function() {
        processSentimentQueue();
    }, 150);
}

function processTweet(tweet) {
    // Add tweet sentiment to the sentiment queue
    sentimentQueue.push(tweet['sentiment']);

    // Add tweet to the tweets table
    $('
' + tweet['tweet'] + '	' + tweet['sentiment'] + '
').prependTo('#tweets-table tbody');
    $('#tweets-table').find('tbody').find('tr').slice(20, 21).remove();
}

function startNoisyClient(keyword) {
    NoisyClient.setup(keyword);

    NoisyClient.addOnTweetFunction(function(tweet) {
        processTweet(tweet);
    });

    processSentimentQueue();
}
<commit_msg>Pass websocketUrl to NoisyClient.setup.<commit_after>var sentimentQueue = [];

function processSentimentQueue() {
    var averageSentiment = 0;
    var newSound = false;

    if (sentimentQueue.length != 0) {
        newSound = true;
        var sum = 0;

        for (var i = 0; i < sentimentQueue.length; i++) {
            sum += sentimentQueue[i];
        }

        averageSentiment = Math.round(sum / sentimentQueue.length);

        sentimentQueue = [];
    }

    if (newSound) {
        var note = Math.round(((averageSentiment + 100) / 200) * 86) + 1;
        playNote(note);
    }

    setTimeout(function() {
        processSentimentQueue();
    }, 150);
}

function processTweet(tweet) {
    // Add tweet sentiment to the sentiment queue
    sentimentQueue.push(tweet['sentiment']);

    // Add tweet to the tweets table
    $('
' + tweet['tweet'] + '	' + tweet['sentiment'] + '
').prependTo('#tweets-table tbody');
    $('#tweets-table').find('tbody').find('tr').slice(20, 21).remove();
}

function startNoisyClient(keyword, websocketUrl) {
    NoisyClient.setup(keyword, websocketUrl);

    NoisyClient.addOnTweetFunction(function(tweet) {
        processTweet(tweet);
    });

    processSentimentQueue();
}
<|endoftext|>


<commit_before>var ColumnLine = require('./ColumnLine');

function ColumnBuffer(column) {

    this.column = column;
    this.max_size = column.columns.opts.maximum_buffer;

    this.new_lines = 0;
    this.modified = false;

    this.data = column.opts.raw === true ? [new ColumnLine('', {tab_size: column.columns.opts.tab_size})] : [];

    this.offset = 0;
}

// column buffer prototype getter/setter properties

Object.defineProperty(ColumnBuffer.prototype, 'size', {
    get: function() {
        return this.data.length + this.offset;
    }
});

// column buffer prototype methods

ColumnBuffer.prototype.line = function(num) {

    if (num - this.offset < 0) {
        return new ColumnLine(new Array(400).join('-'));
    } else {
        return this.data[num - this.offset];
    }
};

ColumnBuffer.prototype.add = function(line) {

    this.data.push(new ColumnLine(line, {
        legacy: this.data[this.data.length - 1],
        tab_size: this.column.columns.opts.tab_size
    }));

    this.new_lines++;

    if (this.data.length > this.max_size) {
        this.data.shift();
        this.offset++;
    }
};

ColumnBuffer.prototype.newLine = function(data) {
    this.add(data || '');
};

ColumnBuffer.prototype.backspace = function(data) {
    this.data[this.data.length - 1].backspace();
};

ColumnBuffer.prototype.addGeneric = function(data) {

    var dataSplit = data.split(/\n/);

    this.data[this.data.length - 1].write(dataSplit.shift());

    for (var i = 0; i < dataSplit.length; i++) {
        this.add(dataSplit[i]);
    }

    return dataSplit.length;
};

ColumnBuffer.prototype.writeToCurrentLine = function(data) {
    this.data[this.data.length - 1].write(data);
    this.modified = true;
};

ColumnBuffer.prototype.reset = function() {
    this.new_lines = 0;
    this.modified = false;
};

module.exports = exports = ColumnBuffer;
<commit_msg>Adding buffer tracking of new lines and whether current line has changed.<commit_after>var ColumnLine = require('./ColumnLine');

function ColumnBuffer(column) {

    this.column = column;
    this.max_size = column.columns.opts.maximum_buffer;

    this.new_lines = 0;
    this.current_modified = false;

    this.data = column.opts.raw === true ? [new ColumnLine('', {tab_size: column.columns.opts.tab_size})] : [];

    this.offset = 0;
}

// column buffer prototype getter/setter properties

Object.defineProperty(ColumnBuffer.prototype, 'size', {
    get: function() {
        return this.data.length + this.offset;
    }
});

// column buffer prototype methods

ColumnBuffer.prototype.line = function(num) {

    if (num - this.offset < 0) {
        return new ColumnLine(new Array(400).join('-'));
    } else {
        return this.data[num - this.offset];
    }
};

ColumnBuffer.prototype.add = function(line) {

    this.data.push(new ColumnLine(line, {
        legacy: this.data[this.data.length - 1],
        tab_size: this.column.columns.opts.tab_size
    }));

    this.new_lines++;

    if (this.data.length > this.max_size) {
        this.data.shift();
        this.offset++;
    }
};

ColumnBuffer.prototype.newLine = function(data) {
    this.add(data || '');
};

ColumnBuffer.prototype.backspace = function() {
    this.data[this.data.length - 1].backspace();
};

ColumnBuffer.prototype.addGeneric = function(data) {

    var dataSplit = data.split(/\n/);

    this.data[this.data.length - 1].write(dataSplit.shift());

    for (var i = 0; i < dataSplit.length; i++) {
        this.add(dataSplit[i]);
    }

    return dataSplit.length;
};

ColumnBuffer.prototype.writeToCurrentLine = function(data) {
    this.data[this.data.length - 1].write(data);
    this.current_modified = true;
};

ColumnBuffer.prototype.reset = function() {
    this.new_lines = 0;
    this.current_modified = false;
};

module.exports = exports = ColumnBuffer;
<|endoftext|>