<commit_before>/**
 * Copyright (c) 2009-2011 The Open Planning Project
 */

Ext.USE_NATIVE_JSON = true;

(function() {
    // backwards compatibility for reading saved maps
    // these source plugins were renamed after 2.3.2
    Ext.preg("gx_wmssource", gxp.plugins.WMSSource);
    Ext.preg("gx_olsource", gxp.plugins.OLSource);
    Ext.preg("gx_googlesource", gxp.plugins.GoogleSource);
    Ext.preg("gx_bingsource", gxp.plugins.BingSource);
    Ext.preg("gx_osmsource", gxp.plugins.OSMSource);
})();

/**
 * api: (define)
 * module = GeoExplorer
 * extends = gxp.Viewer
 */

/** api: constructor
 *  .. class:: GeoExplorer(config)
 *     Create a new GeoExplorer application.
 *
 *     Parameters:
 *     config - {Object} Optional application configuration properties.
 *
 *     Valid config properties:
 *     map - {Object} Map configuration object.
 *     sources - {Object} An object with properties whose values are WMS endpoint URLs
 *
 *     Valid map config properties:
 *         projection - {String} EPSG:xxxx
 *         units - {String} map units according to the projection
 *         maxResolution - {Number}
 *         layers - {Array} A list of layer configuration objects.
 *         center - {Array} A two item array with center coordinates.
 *         zoom - {Number} An initial zoom level.
 *
 *     Valid layer config properties (WMS):
 *     name - {String} Required WMS layer name.
 *     title - {String} Optional title to display for layer.
 */
var GeoExplorer = Ext.extend(gxp.Viewer, {

    // Begin i18n.
    zoomSliderText: "
Zoom Level: {zoom}

Scale: 1:{scale}
",
    loadConfigErrorText: "Trouble reading saved configuration:
",
    loadConfigErrorDefaultText: "Server Error.",
    xhrTroubleText: "Communication Trouble: Status ",
    layersText: "Layers",
    titleText: "Title",
    switch3dText: "Switch to 3D Viewer",
    saveErrorText: "Trouble saving: ",
    bookmarkText: "Bookmark URL",
    permakinkText: 'Permalink',
    appInfoText: "GeoExplorer",
    aboutText: "About GeoExplorer",
    mapInfoText: "Map Info",
    descriptionText: "Description",
    contactText: "Contact",
    aboutThisMapText: "About this Map",
    // End i18n.

    /**
     * private: property[mapPanel]
     * the :class:`GeoExt.MapPanel` instance for the main viewport
     */
    mapPanel: null,

    toggleGroup: "toolGroup",

    constructor: function(config) {
        this.mapItems = [
            {
                xtype: "gxp_scaleoverlay"
            }, {
                xtype: "gx_zoomslider",
                vertical: true,
                height: 100,
                plugins: new GeoExt.ZoomSliderTip({
                    template: this.zoomSliderText
                })
            }
        ];

        // both the Composer and the Viewer need to know about the viewerTools
        // First row in each object is needed to correctly render a tool in the treeview
        // of the embed map dialog. TODO: make this more flexible so this is not needed.
        config.viewerTools = [
            {
                leaf: true,
                text: gxp.plugins.Navigation.prototype.tooltip,
                checked: true,
                iconCls: "gxp-icon-pan",
                ptype: "gxp_navigation",
                toggleGroup: this.toggleGroup,
                actionTarget: {target: "paneltbar", index: 2}
            }, {
                leaf: true,
                text: gxp.plugins.WMSGetFeatureInfo.prototype.infoActionTip,
                checked: true,
                iconCls: "gxp-icon-getfeatureinfo",
                ptype: "gxp_wmsgetfeatureinfo",
                toggleGroup: this.toggleGroup,
                actionTarget: {target: "paneltbar", index: 3}
            }, {
                leaf: true,
                text: gxp.plugins.Measure.prototype.measureTooltip,
                checked: true,
                iconCls: "gxp-icon-measure-length",
                ptype: "gxp_measure",
                toggleGroup: this.toggleGroup,
                actionTarget: {target: "paneltbar", index: 4}
            }, {
                leaf: true,
                text: gxp.plugins.Zoom.prototype.zoomInTooltip + " / " + gxp.plugins.Zoom.prototype.zoomOutTooltip,
                checked: true,
                iconCls: "gxp-icon-zoom-in",
                ptype: "gxp_zoom",
                actionTarget: {target: "paneltbar", index: 5}
            }, {
                leaf: true,
                text: gxp.plugins.NavigationHistory.prototype.previousTooltip + " / " + gxp.plugins.NavigationHistory.prototype.nextTooltip,
                checked: true,
                iconCls: "gxp-icon-zoom-previous",
                ptype: "gxp_navigationhistory",
                actionTarget: {target: "paneltbar", index: 7}
            }, {
                leaf: true,
                text: gxp.plugins.ZoomToExtent.prototype.tooltip,
                checked: true,
                iconCls: gxp.plugins.ZoomToExtent.prototype.iconCls,
                ptype: "gxp_zoomtoextent",
                actionTarget: {target: "paneltbar", index: 9}
            }, {
                leaf: true,
                text: gxp.plugins.Legend.prototype.tooltip,
                checked: true,
                iconCls: "gxp-icon-legend",
                ptype: "gxp_legend",
                actionTarget: {target: "paneltbar", index: 10}
            }
        ];

        GeoExplorer.superclass.constructor.apply(this, arguments);
    },

    loadConfig: function(config) {

        var mapUrl = window.location.hash.substr(1);
        var match = mapUrl.match(/^maps\/(\d+)$/);
        if (match) {
            this.id = Number(match[1]);
            OpenLayers.Request.GET({
                url: mapUrl,
                success: function(request) {
                    var addConfig = Ext.util.JSON.decode(request.responseText);
                    this.applyConfig(Ext.applyIf(addConfig, config));
                },
                failure: function(request) {
                    var obj;
                    try {
                        obj = Ext.util.JSON.decode(request.responseText);
                    } catch (err) {
                        // pass
                    }
                    var msg = this.loadConfigErrorText;
                    if (obj && obj.error) {
                        msg += obj.error;
                    } else {
                        msg += this.loadConfigErrorDefaultText;
                    }
                    this.on({
                        ready: function() {
                            this.displayXHRTrouble(msg, request.status);
                        },
                        scope: this
                    });
                    delete this.id;
                    window.location.hash = "";
                    this.applyConfig(config);
                },
                scope: this
            });
        } else {
            var query = Ext.urlDecode(document.location.search.substr(1));
            if (query && query.q) {
                var queryConfig = Ext.util.JSON.decode(query.q);
                Ext.apply(config, queryConfig);
            }
            this.applyConfig(config);
        }

    },

    displayXHRTrouble: function(msg, status) {

        Ext.Msg.show({
            title: this.xhrTroubleText + status,
            msg: msg,
            icon: Ext.MessageBox.WARNING
        });

    },

    /** private: method[initPortal]
     * Create the various parts that compose the layout.
     */
    initPortal: function() {

        var westPanel = new Ext.Panel({
            border: false,
            layout: "border",
            region: "west",
            width: 250,
            split: true,
            collapsible: true,
            collapseMode: "mini",
            header: false,
            items: [
                {region: 'center', autoScroll: true, tbar: [], border: false, id: 'tree', title: this.layersText},
                {region: 'south', xtype: "container", layout: "fit", border: false, height: 200, id: 'legend'}
            ]
        });

        this.toolbar = new Ext.Toolbar({
            disabled: true,
            id: 'paneltbar',
            items: this.createTools()
        });
        this.on("ready", function() {
            // enable only those items that were not specifically disabled
            var disabled = this.toolbar.items.filterBy(function(item) {
                return item.initialConfig && item.initialConfig.disabled;
            });
            this.toolbar.enable();
            disabled.each(function(item) {
                item.disable();
            });
        });

        var googleEarthPanel = new gxp.GoogleEarthPanel({
            mapPanel: this.mapPanel,
            listeners: {
                beforeadd: function(record) {
                    return record.get("group") !== "background";
                }
            }
        });

        googleEarthPanel.on("show", function() {
            // loop over all the tools and remove their output
            for (var key in this.tools) {
                var tool = this.tools[key];
                if (tool.outputTarget === "map") {
                    tool.removeOutput();
                }
            }
            var layersContainer = Ext.getCmp('layertree');
            if (layersContainer && layersContainer.getTopToolbar()) {
                layersContainer.getTopToolbar().setDisabled(true);
            }
        }, this);

        googleEarthPanel.on("hide", function() {
            var layersContainer = Ext.getCmp('layertree');
            if (layersContainer && layersContainer.getTopToolbar()) {
                layersContainer.getTopToolbar().setDisabled(false);
            }
        }, this);

        this.mapPanelContainer = new Ext.Panel({
            layout: "card",
            region: "center",
            defaults: {
                border: false
            },
            items: [
                this.mapPanel,
                googleEarthPanel
            ],
            activeItem: 0
        });

        this.portalItems = [{
            region: "center",
            layout: "border",
            tbar: this.toolbar,
            items: [
                this.mapPanelContainer,
                westPanel
            ]
        }];

        GeoExplorer.superclass.initPortal.apply(this, arguments);
    },

    /** private: method[createTools]
     * Create the toolbar configuration for the main panel.  This method can be
     * overridden in derived explorer classes such as :class:`GeoExplorer.Composer`
     * or :class:`GeoExplorer.Viewer` to provide specialized controls.
     */
    createTools: function() {

        var toolGroup = this.toggleGroup;

        var enable3DButton = new Ext.Button({
            iconCls: "icon-3D",
            tooltip: this.switch3dText,
            enableToggle: true,
            toggleHandler: function(button, state) {
                if (state === true) {
                    this.mapPanelContainer.getLayout().setActiveItem(1);
                    this.toolbar.disable();
                    button.enable();
                } else {
                    this.mapPanelContainer.getLayout().setActiveItem(0);
                    this.toolbar.enable();
                }
            },
            scope: this
        });

        var tools = [
            "-",
            enable3DButton
        ];

        return tools;
    },

    /** private: method[save]
     *
     * Saves the map config and displays the URL in a window.
     */
    save: function(callback, scope) {
        var configStr = Ext.util.JSON.encode(this.getState());
        var method, url;
        if (this.id) {
            method = "PUT";
            url = "maps/" + this.id;
        } else {
            method = "POST";
            url = "maps";
        }
        OpenLayers.Request.issue({
            method: method,
            url: url,
            data: configStr,
            callback: function(request) {
                this.handleSave(request);
                if (callback) {
                    callback.call(scope || this);
                }
            },
            scope: this
        });
    },

    /** private: method[handleSave]
     *  :arg: ``XMLHttpRequest``
     */
    handleSave: function(request) {
        if (request.status == 200) {
            var config = Ext.util.JSON.decode(request.responseText);
            var mapId = config.id;
            if (mapId) {
                this.id = mapId;
                window.location.hash = "#maps/" + mapId;
            }
        } else {
            throw this.saveErrorText + request.responseText;
        }
    },

    /** private: method[showUrl]
     */
    showUrl: function() {
        var win = new Ext.Window({
            title: this.bookmarkText,
            layout: 'form',
            labelAlign: 'top',
            modal: true,
            bodyStyle: "padding: 5px",
            width: 300,
            items: [{
                xtype: 'textfield',
                fieldLabel: this.permakinkText,
                readOnly: true,
                anchor: "100%",
                selectOnFocus: true,
                value: window.location.href
            }]
        });
        win.show();
        win.items.first().selectText();
    },

    /** api: method[getBookmark]
     *  :return: ``String``
     *
     *  Generate a bookmark for an unsaved map.
     */
    getBookmark: function() {
        var params = Ext.apply(
            OpenLayers.Util.getParameters(),
            {q: Ext.util.JSON.encode(this.getState())}
        );

        // disregard any hash in the url, but maintain all other components
        var url =
            document.location.href.split("?").shift() +
            "?" + Ext.urlEncode(params);

        return url;
    },

    /** private: method[displayAppInfo]
     * Display an informational dialog about the application.
     */
    displayAppInfo: function() {
        var appInfo = new Ext.Panel({
            title: this.appInfoText,
            html: ""+this.aboutText+" "
        });

        var about = Ext.applyIf(this.about, {
            title: '',
            "abstract": '',
            contact: ''
        });

        var mapInfo = new Ext.Panel({
            title: this.mapInfoText,
            html: '
' +
                  '
'+this.titleText+'

' + about.title +
                  '

'+this.descriptionText+'

' + about['abstract'] +
                  '

'+this.contactText+'

' + about.contact +'

',
            height: 'auto',
            width: 'auto'
        });

        var tabs = new Ext.TabPanel({
            activeTab: 0,
            items: [mapInfo, appInfo]
        });

        var win = new Ext.Window({
            title: this.aboutThisMapText,
            modal: true,
            layout: "fit",
            width: 300,
            height: 300,
            items: [tabs]
        });
        win.show();
    }
});

<commit_msg>make the disabling and enabling of the tree toptoolbar buttons work again when toggling to 3D Google Earth view<commit_after>/**
 * Copyright (c) 2009-2011 The Open Planning Project
 */

Ext.USE_NATIVE_JSON = true;

(function() {
    // backwards compatibility for reading saved maps
    // these source plugins were renamed after 2.3.2
    Ext.preg("gx_wmssource", gxp.plugins.WMSSource);
    Ext.preg("gx_olsource", gxp.plugins.OLSource);
    Ext.preg("gx_googlesource", gxp.plugins.GoogleSource);
    Ext.preg("gx_bingsource", gxp.plugins.BingSource);
    Ext.preg("gx_osmsource", gxp.plugins.OSMSource);
})();

/**
 * api: (define)
 * module = GeoExplorer
 * extends = gxp.Viewer
 */

/** api: constructor
 *  .. class:: GeoExplorer(config)
 *     Create a new GeoExplorer application.
 *
 *     Parameters:
 *     config - {Object} Optional application configuration properties.
 *
 *     Valid config properties:
 *     map - {Object} Map configuration object.
 *     sources - {Object} An object with properties whose values are WMS endpoint URLs
 *
 *     Valid map config properties:
 *         projection - {String} EPSG:xxxx
 *         units - {String} map units according to the projection
 *         maxResolution - {Number}
 *         layers - {Array} A list of layer configuration objects.
 *         center - {Array} A two item array with center coordinates.
 *         zoom - {Number} An initial zoom level.
 *
 *     Valid layer config properties (WMS):
 *     name - {String} Required WMS layer name.
 *     title - {String} Optional title to display for layer.
 */
var GeoExplorer = Ext.extend(gxp.Viewer, {

    // Begin i18n.
    zoomSliderText: "
Zoom Level: {zoom}

Scale: 1:{scale}
",
    loadConfigErrorText: "Trouble reading saved configuration:
",
    loadConfigErrorDefaultText: "Server Error.",
    xhrTroubleText: "Communication Trouble: Status ",
    layersText: "Layers",
    titleText: "Title",
    switch3dText: "Switch to 3D Viewer",
    saveErrorText: "Trouble saving: ",
    bookmarkText: "Bookmark URL",
    permakinkText: 'Permalink',
    appInfoText: "GeoExplorer",
    aboutText: "About GeoExplorer",
    mapInfoText: "Map Info",
    descriptionText: "Description",
    contactText: "Contact",
    aboutThisMapText: "About this Map",
    // End i18n.

    /**
     * private: property[mapPanel]
     * the :class:`GeoExt.MapPanel` instance for the main viewport
     */
    mapPanel: null,

    toggleGroup: "toolGroup",

    constructor: function(config) {
        this.mapItems = [
            {
                xtype: "gxp_scaleoverlay"
            }, {
                xtype: "gx_zoomslider",
                vertical: true,
                height: 100,
                plugins: new GeoExt.ZoomSliderTip({
                    template: this.zoomSliderText
                })
            }
        ];

        // both the Composer and the Viewer need to know about the viewerTools
        // First row in each object is needed to correctly render a tool in the treeview
        // of the embed map dialog. TODO: make this more flexible so this is not needed.
        config.viewerTools = [
            {
                leaf: true,
                text: gxp.plugins.Navigation.prototype.tooltip,
                checked: true,
                iconCls: "gxp-icon-pan",
                ptype: "gxp_navigation",
                toggleGroup: this.toggleGroup,
                actionTarget: {target: "paneltbar", index: 2}
            }, {
                leaf: true,
                text: gxp.plugins.WMSGetFeatureInfo.prototype.infoActionTip,
                checked: true,
                iconCls: "gxp-icon-getfeatureinfo",
                ptype: "gxp_wmsgetfeatureinfo",
                toggleGroup: this.toggleGroup,
                actionTarget: {target: "paneltbar", index: 3}
            }, {
                leaf: true,
                text: gxp.plugins.Measure.prototype.measureTooltip,
                checked: true,
                iconCls: "gxp-icon-measure-length",
                ptype: "gxp_measure",
                toggleGroup: this.toggleGroup,
                actionTarget: {target: "paneltbar", index: 4}
            }, {
                leaf: true,
                text: gxp.plugins.Zoom.prototype.zoomInTooltip + " / " + gxp.plugins.Zoom.prototype.zoomOutTooltip,
                checked: true,
                iconCls: "gxp-icon-zoom-in",
                ptype: "gxp_zoom",
                actionTarget: {target: "paneltbar", index: 5}
            }, {
                leaf: true,
                text: gxp.plugins.NavigationHistory.prototype.previousTooltip + " / " + gxp.plugins.NavigationHistory.prototype.nextTooltip,
                checked: true,
                iconCls: "gxp-icon-zoom-previous",
                ptype: "gxp_navigationhistory",
                actionTarget: {target: "paneltbar", index: 7}
            }, {
                leaf: true,
                text: gxp.plugins.ZoomToExtent.prototype.tooltip,
                checked: true,
                iconCls: gxp.plugins.ZoomToExtent.prototype.iconCls,
                ptype: "gxp_zoomtoextent",
                actionTarget: {target: "paneltbar", index: 9}
            }, {
                leaf: true,
                text: gxp.plugins.Legend.prototype.tooltip,
                checked: true,
                iconCls: "gxp-icon-legend",
                ptype: "gxp_legend",
                actionTarget: {target: "paneltbar", index: 10}
            }
        ];

        GeoExplorer.superclass.constructor.apply(this, arguments);
    },

    loadConfig: function(config) {

        var mapUrl = window.location.hash.substr(1);
        var match = mapUrl.match(/^maps\/(\d+)$/);
        if (match) {
            this.id = Number(match[1]);
            OpenLayers.Request.GET({
                url: mapUrl,
                success: function(request) {
                    var addConfig = Ext.util.JSON.decode(request.responseText);
                    this.applyConfig(Ext.applyIf(addConfig, config));
                },
                failure: function(request) {
                    var obj;
                    try {
                        obj = Ext.util.JSON.decode(request.responseText);
                    } catch (err) {
                        // pass
                    }
                    var msg = this.loadConfigErrorText;
                    if (obj && obj.error) {
                        msg += obj.error;
                    } else {
                        msg += this.loadConfigErrorDefaultText;
                    }
                    this.on({
                        ready: function() {
                            this.displayXHRTrouble(msg, request.status);
                        },
                        scope: this
                    });
                    delete this.id;
                    window.location.hash = "";
                    this.applyConfig(config);
                },
                scope: this
            });
        } else {
            var query = Ext.urlDecode(document.location.search.substr(1));
            if (query && query.q) {
                var queryConfig = Ext.util.JSON.decode(query.q);
                Ext.apply(config, queryConfig);
            }
            this.applyConfig(config);
        }

    },

    displayXHRTrouble: function(msg, status) {

        Ext.Msg.show({
            title: this.xhrTroubleText + status,
            msg: msg,
            icon: Ext.MessageBox.WARNING
        });

    },

    /** private: method[initPortal]
     * Create the various parts that compose the layout.
     */
    initPortal: function() {

        var westPanel = new Ext.Panel({
            border: false,
            layout: "border",
            region: "west",
            width: 250,
            split: true,
            collapsible: true,
            collapseMode: "mini",
            header: false,
            items: [
                {region: 'center', autoScroll: true, tbar: [], border: false, id: 'tree', title: this.layersText},
                {region: 'south', xtype: "container", layout: "fit", border: false, height: 200, id: 'legend'}
            ]
        });

        this.toolbar = new Ext.Toolbar({
            disabled: true,
            id: 'paneltbar',
            items: this.createTools()
        });
        this.on("ready", function() {
            // enable only those items that were not specifically disabled
            var disabled = this.toolbar.items.filterBy(function(item) {
                return item.initialConfig && item.initialConfig.disabled;
            });
            this.toolbar.enable();
            disabled.each(function(item) {
                item.disable();
            });
        });

        var googleEarthPanel = new gxp.GoogleEarthPanel({
            mapPanel: this.mapPanel,
            listeners: {
                beforeadd: function(record) {
                    return record.get("group") !== "background";
                }
            }
        });

        googleEarthPanel.on("show", function() {
            // loop over all the tools and remove their output
            for (var key in this.tools) {
                var tool = this.tools[key];
                if (tool.outputTarget === "map") {
                    tool.removeOutput();
                }
            }
            var layersContainer = Ext.getCmp('tree');
            if (layersContainer && layersContainer.getTopToolbar()) {
                layersContainer.getTopToolbar().setDisabled(true);
            }
        }, this);

        googleEarthPanel.on("hide", function() {
            var layersContainer = Ext.getCmp('tree');
            if (layersContainer && layersContainer.getTopToolbar()) {
                layersContainer.getTopToolbar().setDisabled(false);
            }
        }, this);

        this.mapPanelContainer = new Ext.Panel({
            layout: "card",
            region: "center",
            defaults: {
                border: false
            },
            items: [
                this.mapPanel,
                googleEarthPanel
            ],
            activeItem: 0
        });

        this.portalItems = [{
            region: "center",
            layout: "border",
            tbar: this.toolbar,
            items: [
                this.mapPanelContainer,
                westPanel
            ]
        }];

        GeoExplorer.superclass.initPortal.apply(this, arguments);
    },

    /** private: method[createTools]
     * Create the toolbar configuration for the main panel.  This method can be
     * overridden in derived explorer classes such as :class:`GeoExplorer.Composer`
     * or :class:`GeoExplorer.Viewer` to provide specialized controls.
     */
    createTools: function() {

        var toolGroup = this.toggleGroup;

        var enable3DButton = new Ext.Button({
            iconCls: "icon-3D",
            tooltip: this.switch3dText,
            enableToggle: true,
            toggleHandler: function(button, state) {
                if (state === true) {
                    this.mapPanelContainer.getLayout().setActiveItem(1);
                    this.toolbar.disable();
                    button.enable();
                } else {
                    this.mapPanelContainer.getLayout().setActiveItem(0);
                    this.toolbar.enable();
                }
            },
            scope: this
        });

        var tools = [
            "-",
            enable3DButton
        ];

        return tools;
    },

    /** private: method[save]
     *
     * Saves the map config and displays the URL in a window.
     */
    save: function(callback, scope) {
        var configStr = Ext.util.JSON.encode(this.getState());
        var method, url;
        if (this.id) {
            method = "PUT";
            url = "maps/" + this.id;
        } else {
            method = "POST";
            url = "maps";
        }
        OpenLayers.Request.issue({
            method: method,
            url: url,
            data: configStr,
            callback: function(request) {
                this.handleSave(request);
                if (callback) {
                    callback.call(scope || this);
                }
            },
            scope: this
        });
    },

    /** private: method[handleSave]
     *  :arg: ``XMLHttpRequest``
     */
    handleSave: function(request) {
        if (request.status == 200) {
            var config = Ext.util.JSON.decode(request.responseText);
            var mapId = config.id;
            if (mapId) {
                this.id = mapId;
                window.location.hash = "#maps/" + mapId;
            }
        } else {
            throw this.saveErrorText + request.responseText;
        }
    },

    /** private: method[showUrl]
     */
    showUrl: function() {
        var win = new Ext.Window({
            title: this.bookmarkText,
            layout: 'form',
            labelAlign: 'top',
            modal: true,
            bodyStyle: "padding: 5px",
            width: 300,
            items: [{
                xtype: 'textfield',
                fieldLabel: this.permakinkText,
                readOnly: true,
                anchor: "100%",
                selectOnFocus: true,
                value: window.location.href
            }]
        });
        win.show();
        win.items.first().selectText();
    },

    /** api: method[getBookmark]
     *  :return: ``String``
     *
     *  Generate a bookmark for an unsaved map.
     */
    getBookmark: function() {
        var params = Ext.apply(
            OpenLayers.Util.getParameters(),
            {q: Ext.util.JSON.encode(this.getState())}
        );

        // disregard any hash in the url, but maintain all other components
        var url =
            document.location.href.split("?").shift() +
            "?" + Ext.urlEncode(params);

        return url;
    },

    /** private: method[displayAppInfo]
     * Display an informational dialog about the application.
     */
    displayAppInfo: function() {
        var appInfo = new Ext.Panel({
            title: this.appInfoText,
            html: ""+this.aboutText+" "
        });

        var about = Ext.applyIf(this.about, {
            title: '',
            "abstract": '',
            contact: ''
        });

        var mapInfo = new Ext.Panel({
            title: this.mapInfoText,
            html: '
' +
                  '
'+this.titleText+'

' + about.title +
                  '

'+this.descriptionText+'

' + about['abstract'] +
                  '

'+this.contactText+'

' + about.contact +'

',
            height: 'auto',
            width: 'auto'
        });

        var tabs = new Ext.TabPanel({
            activeTab: 0,
            items: [mapInfo, appInfo]
        });

        var win = new Ext.Window({
            title: this.aboutThisMapText,
            modal: true,
            layout: "fit",
            width: 300,
            height: 300,
            items: [tabs]
        });
        win.show();
    }
});

<|endoftext|>


<commit_before>const helpers = require('./helpers');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');const {CheckerPlugin} = require('awesome-typescript-loader');

const getConfig = (hasCoverage, isTddMode) => {

    let extraRules = [];
    if (hasCoverage) {
        extraRules.push(
            {
                enforce: 'post',
                test: /\.(js|ts)$/,
                loader: 'istanbul-instrumenter-loader',
                include: helpers.root('src'),
                exclude: [
                    /\.(e2e|spec)\.ts$/,
                    /node_modules/
                ]
            }
        );
    }

    let extraPlugins = [];
    if (isTddMode) {
        extraPlugins.push(new CheckerPlugin());// to speed up compilation during TDD
    }

    return {

        devtool: 'inline-source-map',

        resolve: {
            extensions: ['.ts', '.js'],
            modules: [helpers.root('src'), 'node_modules']

        },

        module: {

            rules: [

                {
                    enforce: 'pre',
                    test: /\.js$/,
                    loader: 'source-map-loader',
                    exclude: [
                        // these packages have problems with their sourcemaps
                        helpers.root('node_modules/rxjs'),
                        helpers.root('node_modules/@angular')
                    ]
                },

                {
                    test: /\.ts$/,
                    use: [
                        {
                            loader: 'awesome-typescript-loader',
                            query: {
                                // use inline sourcemaps for "karma-remap-coverage" reporter (if coverage is activated)
                                sourceMap: !hasCoverage,
                                inlineSourceMap: hasCoverage,
                                compilerOptions: {

                                    // Remove TypeScript helpers to be injected
                                    // below by DefinePlugin
                                    removeComments: true

                                }
                            },
                        },
                        'angular2-template-loader'
                    ],
                    exclude: [/\.e2e\.ts$/]
                },

                {
                    test: /\.css$/,
                    loader: ['to-string-loader', 'css-loader']
                },
                {
                  test: /\.(scss|sass)$/,
                  use: ['to-string-loader', 'css-loader', 'sass-loader'],
                  exclude: [helpers.root('src', 'scss')]
                },
                {
                    test: /\.html$/,
                    loader: 'raw-loader'
                }
            ].concat(extraRules)
        },

        plugins: [

            new LoaderOptionsPlugin({
                debug: false,
                options: {
                    // legacy options go here
                }
            }),
            // Fixes linker warnings (see https://github.com/angular/angular/issues/11580)
            new ContextReplacementPlugin(
              // The (\\|\/) piece accounts for path separators in *nix and Windows
              /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
              helpers.root('src'), // location of your src
              {} // a map of your routes
            ),
        ].concat(extraPlugins),

        performance: {
            hints: false
        },

        node: {
            global: true,
            process: false,
            crypto: 'empty',
            module: false,
            clearImmediate: false,
            setImmediate: false
        }
    };
}

module.exports.getConfig = getConfig;
<commit_msg>chore(test): fix alignement in webpack conf file<commit_after>const helpers = require('./helpers');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const {CheckerPlugin} = require('awesome-typescript-loader');

const getConfig = (hasCoverage, isTddMode) => {

    let extraRules = [];
    if (hasCoverage) {
        extraRules.push(
            {
                enforce: 'post',
                test: /\.(js|ts)$/,
                loader: 'istanbul-instrumenter-loader',
                include: helpers.root('src'),
                exclude: [
                    /\.(e2e|spec)\.ts$/,
                    /node_modules/
                ]
            }
        );
    }

    let extraPlugins = [];
    if (isTddMode) {
        extraPlugins.push(new CheckerPlugin());// to speed up compilation during TDD
    }

    return {

        devtool: 'inline-source-map',

        resolve: {
            extensions: ['.ts', '.js'],
            modules: [helpers.root('src'), 'node_modules']

        },

        module: {

            rules: [

                {
                    enforce: 'pre',
                    test: /\.js$/,
                    loader: 'source-map-loader',
                    exclude: [
                        // these packages have problems with their sourcemaps
                        helpers.root('node_modules/rxjs'),
                        helpers.root('node_modules/@angular')
                    ]
                },

                {
                    test: /\.ts$/,
                    use: [
                        {
                            loader: 'awesome-typescript-loader',
                            query: {
                                // use inline sourcemaps for "karma-remap-coverage" reporter (if coverage is activated)
                                sourceMap: !hasCoverage,
                                inlineSourceMap: hasCoverage,
                                compilerOptions: {

                                    // Remove TypeScript helpers to be injected
                                    // below by DefinePlugin
                                    removeComments: true

                                }
                            },
                        },
                        'angular2-template-loader'
                    ],
                    exclude: [/\.e2e\.ts$/]
                },

                {
                    test: /\.css$/,
                    loader: ['to-string-loader', 'css-loader']
                },
                {
                  test: /\.(scss|sass)$/,
                  use: ['to-string-loader', 'css-loader', 'sass-loader'],
                  exclude: [helpers.root('src', 'scss')]
                },
                {
                    test: /\.html$/,
                    loader: 'raw-loader'
                }
            ].concat(extraRules)
        },

        plugins: [

            new LoaderOptionsPlugin({
                debug: false,
                options: {
                    // legacy options go here
                }
            }),
            // Fixes linker warnings (see https://github.com/angular/angular/issues/11580)
            new ContextReplacementPlugin(
              // The (\\|\/) piece accounts for path separators in *nix and Windows
              /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
              helpers.root('src'), // location of your src
              {} // a map of your routes
            ),
        ].concat(extraPlugins),

        performance: {
            hints: false
        },

        node: {
            global: true,
            process: false,
            crypto: 'empty',
            module: false,
            clearImmediate: false,
            setImmediate: false
        }
    };
}

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


<commit_before><commit_msg>Update NeuralNetwork.js<commit_after><|endoftext|>


<commit_before><commit_msg>Add some needed externs. (Important for release builds.)<commit_after><|endoftext|>


<commit_before>// Exercise 3
//
// 1. Building on Exercise 2, implement the following methods:
//
// age() - returns the age of the car.
// setYear()
// getYear()
// setMake()
// getMake()
// setModel()
// getModel()
// setColor()
// getColor()
// Include validity checking for setYear().

// 2. Modify the constructor you have written so that the mileage is
//    passed in as a parameter and recorded as an attribute.

// 3.  Add accessors for the new mileage.  For validity, ensure that the
//     mileage for a car can never be decreased.
<commit_msg>Add one more exercise, clean up the format<commit_after>
// Exercise 3
//
// 1. Building on Exercise 2, implement the
// following methods:
//
// setYear()
// getYear()
// setMake()
// getMake()
// setModel()
// getModel()
// setColor()
// getColor()
// Include validity checking for setYear().

// 2. Modify the constructor you have written so
// that the mileage is passed in as a parameter
// and recorded as an attribute.

// 3.  Add accessors for the new mileage.  For
// validity, ensure that the mileage for a car
// can never be decreased.

// 4. The database backing our list of cars only
// recognizes seven colors, plus none.
//
// Make sure that when a car color is set, it is
// in the list: red, orange, black, green, blue,
// purple, and white.  "None" is also allowed and
// should be the default.
//
// Modify the constructor so that if you pass it
// an unrecognized color, it stores the string
// "none" instead. If a programmer passes an
// unrecognized color to the accessor function,
// you should write a message to the console and
// make no change to the object.
<|endoftext|>


<commit_before>import Shevy from '../src'

describe('Shevy', () => {
  it('is defined', () => {
    const shevy = new Shevy()
    expect(shevy).toBeDefined()
  })

  describe('Defined Properties', () => {
    const shevy = new Shevy()
    const {
      baseFontSize,
      baseFontUnit,
      baseLineHeight,
      baseFontScale,
      addMarginBottom,
      proximity,
      proximityFactor,
      lineHeightSpacing,
      baseSpacing,
      body,
      content
    } = shevy

    it('baseFontSize', () => { expect(baseFontSize).toBeDefined() })
    it('baseFontUnit', () => { expect(baseFontUnit).toBeDefined() })
    it('baseLineHeight', () => { expect(baseLineHeight).toBeDefined() })
    it('baseFontScale', () => { expect(baseFontScale).toBeDefined() })
    it('addMarginBottom', () => { expect(addMarginBottom).toBeDefined() })
    it('addMarginBottom', () => { expect(addMarginBottom).toBeDefined() })
    it('proximity', () => { expect(proximity).toBeDefined() })
    it('proximityFactor', () => { expect(proximityFactor).toBeDefined() })
    it('body', () => { expect(body).toBeDefined() })
    it('content', () => { expect(content).toBeDefined() })
    it('lineHeightSpacing', () => { expect(lineHeightSpacing).toBeDefined() })
    it('baseSpacing', () => { expect(baseSpacing).toBeDefined() })
  })

  describe('Default settings', () => {
    const shevy = new Shevy()

    describe('Property Values', () => {
      it('baseFontSize is 16px', () => {
        expect(shevy.baseFontSize).toEqual('16px')
      })

      it('baseFontUnit is px', () => {
        expect(shevy.baseFontUnit).toEqual('px')
      })

      it('baseLineHeight is 1.5', () => {
        expect(shevy.baseLineHeight).toEqual(1.5)
      })

      it('baseFontScale is an array of default values', () => {
        const expectedScale = [3, 2.5, 2, 1.5, 1.25, 1]
        expect(shevy.baseFontScale).toEqual(expectedScale)
      })

      it('addMarginBottom is true', () => {
        expect(shevy.addMarginBottom).toEqual(true)
      })

      it('proximity is false', () => {
        expect(shevy.proximity).toEqual(false)
      })

      it('proximityFactor is .85', () => {
        expect(shevy.proximityFactor).toEqual(.85)
      })
    })

    describe('Headings', () => {
      const { h1, h2, h3, h4, h5, h6 } = shevy

      it('h1', () => { expect(h1.fontSize).toEqual('48px') })
      it('h2', () => { expect(h2.fontSize).toEqual('40px') })
      it('h3', () => { expect(h3.fontSize).toEqual('32px') })
      it('h4', () => { expect(h4.fontSize).toEqual('24px') })
      it('h5', () => { expect(h5.fontSize).toEqual('20px') })
      it('h6', () => { expect(h6.fontSize).toEqual('16px') })
    })

    describe('Body', () => {
      const { body } = shevy

      it('fontSize is 16px', () => {
        expect(body.fontSize).toEqual('16px')
      })

      it('lineHeight of 1.5', () => {
        expect(body.lineHeight).toEqual(1.5)
      })
    })

    describe('Content', () => {
      const { content } = shevy

      it('fontSize is 16px', () => {
        expect(content.fontSize).toEqual('16px')
      })

      it('lineHeight is 1.5', () => {
        expect(content.lineHeight).toEqual(1.5)
      })

      it('marginBottom is 24px', () => {
        expect(content.marginBottom).toEqual('24px')
      })
    })

    describe('Methods', () => {
      it('lineHeightSpacing returns 24px', () => {
        expect(shevy.lineHeightSpacing()).toEqual('24px')
      })

      it('baseSpacing returns 24px', () => {
        expect(shevy.baseSpacing()).toEqual('24px')
      })
    })
  })

  describe('Custom settings', () => {
    describe('unit: em', () => {
      const customOptions = {
        baseFontSize: '1em',
        baseLineHeight: 2
      }
      const shevy = new Shevy(customOptions)

      describe('Headings', () => {
        const { h1, h2, h3, h4, h5, h6 } = shevy

        it('h1', () => { expect(h1.fontSize).toEqual('3em') })
        it('h2', () => { expect(h2.fontSize).toEqual('2.5em') })
        it('h3', () => { expect(h3.fontSize).toEqual('2em') })
        it('h4', () => { expect(h4.fontSize).toEqual('1.5em') })
        it('h5', () => { expect(h5.fontSize).toEqual('1.25em') })
        it('h6', () => { expect(h6.fontSize).toEqual('1em') })
      })

      describe('Body', () => {
        const { body } = shevy

        it('fontSize is 1em', () => {
          expect(body.fontSize).toEqual('1em')
        })

        it('lineHeight of 2', () => {
          expect(body.lineHeight).toEqual(2)
        })
      })

      describe('Content', () => {
        const { content } = shevy

        it('fontSize is 1rem', () => {
          expect(content.fontSize).toEqual('1em')
        })

        it('lineHeight is 2', () => {
          expect(content.lineHeight).toEqual(2)
        })

        it('marginBottom is 2em', () => {
          expect(content.marginBottom).toEqual('2em')
        })
      })

      describe('Base Font Unit', () => {
        it('should equal em', () => {
          const { baseFontUnit } = shevy
          expect(baseFontUnit).toEqual('em')
        })
      })

      describe('Base Spacing', () => {
        const { baseSpacing } = shevy

        it('baseSpacing equals 2em', () => {
          expect(baseSpacing()).toEqual('2em')
        })
      })
    })

    describe('unit: rem', () => {
      const customOptions = {
        baseFontSize: '1rem',
        baseLineHeight: 2
      }
      const shevy = new Shevy(customOptions)

      describe('Headings', () => {
        const { h1, h2, h3, h4, h5, h6 } = shevy

        it('h1', () => { expect(h1.fontSize).toEqual('3rem') })
        it('h2', () => { expect(h2.fontSize).toEqual('2.5rem') })
        it('h3', () => { expect(h3.fontSize).toEqual('2rem') })
        it('h4', () => { expect(h4.fontSize).toEqual('1.5rem') })
        it('h5', () => { expect(h5.fontSize).toEqual('1.25rem') })
        it('h6', () => { expect(h6.fontSize).toEqual('1rem') })
      })

      describe('Body', () => {
        const { body } = shevy

        it('fontSize is 1rem', () => {
          expect(body.fontSize).toEqual('1rem')
        })

        it('lineHeight of 2', () => {
          expect(body.lineHeight).toEqual(2)
        })
      })

      describe('Content', () => {
        const { content } = shevy

        it('fontSize is 1rem', () => {
          expect(content.fontSize).toEqual('1rem')
        })

        it('lineHeight is 2', () => {
          expect(content.lineHeight).toEqual(2)
        })

        it('marginBottom is 2rem', () => {
          expect(content.marginBottom).toEqual('2rem')
        })
      })

      describe('Base Font Unit', () => {
        it('should equal rem', () => {
          const { baseFontUnit } = shevy
          expect(baseFontUnit).toEqual('rem')
        })
      })

      describe('Base Spacing', () => {
        const { baseSpacing } = shevy

        it('baseSpacing equals 2rem', () => {
          expect(baseSpacing()).toEqual('2rem')
        })
      })
    })
  })
})
<commit_msg>finish test organization, all tests pass<commit_after>import Shevy from '../src'

describe('Shevy', () => {
  it('is defined', () => {
    const shevy = new Shevy()
    expect(shevy).toBeDefined()
  })

  describe('Defined Properties', () => {
    const shevy = new Shevy()
    const {
      baseFontSize,
      baseFontUnit,
      baseLineHeight,
      baseFontScale,
      addMarginBottom,
      proximity,
      proximityFactor,
      lineHeightSpacing,
      baseSpacing,
      body,
      content
    } = shevy

    it('baseFontSize', () => { expect(baseFontSize).toBeDefined() })
    it('baseFontUnit', () => { expect(baseFontUnit).toBeDefined() })
    it('baseLineHeight', () => { expect(baseLineHeight).toBeDefined() })
    it('baseFontScale', () => { expect(baseFontScale).toBeDefined() })
    it('addMarginBottom', () => { expect(addMarginBottom).toBeDefined() })
    it('addMarginBottom', () => { expect(addMarginBottom).toBeDefined() })
    it('proximity', () => { expect(proximity).toBeDefined() })
    it('proximityFactor', () => { expect(proximityFactor).toBeDefined() })
    it('body', () => { expect(body).toBeDefined() })
    it('content', () => { expect(content).toBeDefined() })
    it('lineHeightSpacing', () => { expect(lineHeightSpacing).toBeDefined() })
    it('baseSpacing', () => { expect(baseSpacing).toBeDefined() })
  })

  describe('Default settings', () => {
    const shevy = new Shevy()

    describe('Property Values', () => {
      it('baseFontSize is 16px', () => {
        expect(shevy.baseFontSize).toEqual('16px')
      })

      it('baseFontUnit is px', () => {
        expect(shevy.baseFontUnit).toEqual('px')
      })

      it('baseLineHeight is 1.5', () => {
        expect(shevy.baseLineHeight).toEqual(1.5)
      })

      it('baseFontScale is an array of default values', () => {
        const expectedScale = [3, 2.5, 2, 1.5, 1.25, 1]
        expect(shevy.baseFontScale).toEqual(expectedScale)
      })

      it('addMarginBottom is true', () => {
        expect(shevy.addMarginBottom).toEqual(true)
      })

      it('proximity is false', () => {
        expect(shevy.proximity).toEqual(false)
      })

      it('proximityFactor is .85', () => {
        expect(shevy.proximityFactor).toEqual(.85)
      })
    })

    describe('Headings', () => {
      const { h1, h2, h3, h4, h5, h6 } = shevy

      it('h1', () => { expect(h1.fontSize).toEqual('48px') })
      it('h2', () => { expect(h2.fontSize).toEqual('40px') })
      it('h3', () => { expect(h3.fontSize).toEqual('32px') })
      it('h4', () => { expect(h4.fontSize).toEqual('24px') })
      it('h5', () => { expect(h5.fontSize).toEqual('20px') })
      it('h6', () => { expect(h6.fontSize).toEqual('16px') })
    })

    describe('Body', () => {
      const { body } = shevy

      it('fontSize is 16px', () => {
        expect(body.fontSize).toEqual('16px')
      })

      it('lineHeight of 1.5', () => {
        expect(body.lineHeight).toEqual(1.5)
      })
    })

    describe('Content', () => {
      const { content } = shevy

      it('fontSize is 16px', () => {
        expect(content.fontSize).toEqual('16px')
      })

      it('lineHeight is 1.5', () => {
        expect(content.lineHeight).toEqual(1.5)
      })

      it('marginBottom is 24px', () => {
        expect(content.marginBottom).toEqual('24px')
      })
    })

    describe('Methods', () => {
      it('lineHeightSpacing returns 24px', () => {
        expect(shevy.lineHeightSpacing()).toEqual('24px')
      })

      it('baseSpacing returns 24px', () => {
        expect(shevy.baseSpacing()).toEqual('24px')
      })
    })
  })

  describe('Custom settings', () => {
    describe('unit: em', () => {
      const customOptions = {
        baseFontSize: '1em',
        baseLineHeight: 2,
        baseFontScale: [6, 5, 4, 3, 2, 1],
        addMarginBottom: false,
        proximity: true,
        proximityFactor: .5
      }
      const shevy = new Shevy(customOptions)

      describe('Property Values', () => {
        it('baseFontSize is 1em', () => {
          expect(shevy.baseFontSize).toEqual('1em')
        })

        it('baseFontUnit is em', () => {
          expect(shevy.baseFontUnit).toEqual('em')
        })

        it('baseLineHeight is 2', () => {
          expect(shevy.baseLineHeight).toEqual(2)
        })

        it('baseFontScale is an array matching the custom values', () => {
          const expectedScale = [6, 5, 4, 3, 2, 1]
          expect(shevy.baseFontScale).toEqual(expectedScale)
        })

        it('addMarginBottom is false', () => {
          expect(shevy.addMarginBottom).toEqual(false)
        })

        it('proximity is true', () => {
          expect(shevy.proximity).toEqual(true)
        })

        it('proximityFactor is .5', () => {
          expect(shevy.proximityFactor).toEqual(.5)
        })
      })

      describe('Headings', () => {
        const { h1, h2, h3, h4, h5, h6 } = shevy

        it('h1', () => { expect(h1.fontSize).toEqual('6em') })
        it('h2', () => { expect(h2.fontSize).toEqual('5em') })
        it('h3', () => { expect(h3.fontSize).toEqual('4em') })
        it('h4', () => { expect(h4.fontSize).toEqual('3em') })
        it('h5', () => { expect(h5.fontSize).toEqual('2em') })
        it('h6', () => { expect(h6.fontSize).toEqual('1em') })
      })

      describe('Body', () => {
        const { body } = shevy

        it('fontSize is 1em', () => {
          expect(body.fontSize).toEqual('1em')
        })

        it('lineHeight of 2', () => {
          expect(body.lineHeight).toEqual(2)
        })
      })

      describe('Content', () => {
        const { content } = shevy

        it('fontSize is 1rem', () => {
          expect(content.fontSize).toEqual('1em')
        })

        it('lineHeight is 2', () => {
          expect(content.lineHeight).toEqual(2)
        })

        it('marginBottom is undefined', () => {
          expect(content.marginBottom).toEqual(undefined)
        })
      })

      describe('Methods', () => {
        it('lineHeightSpacing returns 2em', () => {
          expect(shevy.lineHeightSpacing()).toEqual('2em')
        })

        it('baseSpacing returns 1em due to proximityFactor', () => {
          expect(shevy.baseSpacing()).toEqual('1em')
        })
      })
    })

    describe('unit: rem', () => {
      const customOptions = {
        baseFontSize: '1rem',
        baseLineHeight: 2,
        baseFontScale: [6, 5, 4, 3, 2, 1],
        addMarginBottom: true,
        proximity: true,
        proximityFactor: 1.5
      }
      const shevy = new Shevy(customOptions)

      describe('Property Values', () => {
        it('baseFontSize is 1rem', () => {
          expect(shevy.baseFontSize).toEqual('1rem')
        })

        it('baseFontUnit is rem', () => {
          expect(shevy.baseFontUnit).toEqual('rem')
        })

        it('baseLineHeight is 2', () => {
          expect(shevy.baseLineHeight).toEqual(2)
        })

        it('baseFontScale is an array matching the custom values', () => {
          const expectedScale = [6, 5, 4, 3, 2, 1]
          expect(shevy.baseFontScale).toEqual(expectedScale)
        })

        it('addMarginBottom is true', () => {
          expect(shevy.addMarginBottom).toEqual(true)
        })

        it('proximity is true', () => {
          expect(shevy.proximity).toEqual(true)
        })

        it('proximityFactor is 1.5', () => {
          expect(shevy.proximityFactor).toEqual(1.5)
        })
      })

      describe('Headings', () => {
        const { h1, h2, h3, h4, h5, h6 } = shevy

        it('h1', () => { expect(h1.fontSize).toEqual('6rem') })
        it('h2', () => { expect(h2.fontSize).toEqual('5rem') })
        it('h3', () => { expect(h3.fontSize).toEqual('4rem') })
        it('h4', () => { expect(h4.fontSize).toEqual('3rem') })
        it('h5', () => { expect(h5.fontSize).toEqual('2rem') })
        it('h6', () => { expect(h6.fontSize).toEqual('1rem') })
      })

      describe('Body', () => {
        const { body } = shevy

        it('fontSize is 1rem', () => {
          expect(body.fontSize).toEqual('1rem')
        })

        it('lineHeight of 2', () => {
          expect(body.lineHeight).toEqual(2)
        })
      })

      describe('Content', () => {
        const { content } = shevy

        it('fontSize is 1rem', () => {
          expect(content.fontSize).toEqual('1rem')
        })

        it('lineHeight is 2', () => {
          expect(content.lineHeight).toEqual(2)
        })

        it('marginBottom is 3rem', () => {
          expect(content.marginBottom).toEqual('3rem')
        })
      })

      describe('Methods', () => {
        it('lineHeightSpacing returns 2rem', () => {
          expect(shevy.lineHeightSpacing()).toEqual('2rem')
        })

        it('baseSpacing returns 3rem due to proximityFactor', () => {
          expect(shevy.baseSpacing()).toEqual('3rem')
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>ace.define("ace/mode/tlstatusnss_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports, module) {
  "use strict";

  var oop = require("../lib/oop");
  var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

  var NssHighlightRules = function() {
    this.$rules = {
      start: [{
          include: 'comment'
        },
        {
          include: 'block'
        },
        {
          include: 'tag'
        },
        {
          include: 'important_function_call'
        },
        {
          defaultToken: 'tlstatus.code'
        },
        {
          caseInsensitive: true
        }
      ],
      important_function_call: [{
          token: 'tlstatus.no-comment-code',
          regex: '(CreateText|SetBacklog)(\\s*)\\(',
          push: [{
              token: 'tlstatus.no-comment-code',
              regex: '\\)',
              next: 'pop'
            }, {
              include: 'no_comment_lparen'
            },
            {
              defaultToken: 'tlstatus.no-comment-code'
            }
          ]
        },
        {
          caseInsensitive: true
        }
      ],
      no_comment_lparen: [{
          token: 'tlstatus.no-comment-code',
          regex: '\\(',
          push: [{
              token: 'tlstatus.no-comment-code',
              regex: '\\)',
              next: 'pop'
            },
            {
              include: 'no_comment_lparen'
            },
            {
              defaultToken: 'tlstatus.no-comment-code'
            }
          ]
        },
        {
          caseInsensitive: true
        }
      ],
      comment: [{
          token: 'tlstatus.note',
          regex: '^\\/\\/note(.*)'
        },
        {
          token: 'comment.single-line',
          regex: '(^|\\s+)\\/\\/(.*)'
        },
        {
          token: 'comment.multiline',
          regex: '\\/\\*',
          push: [{
            token: 'comment.multiline',
            regex: '\\*\\/',
            next: 'pop'
          }, {
            defaultToken: 'comment.multiline'
          }]
        },
        {
          caseInsensitive: true
        }
      ],
      block: [{
          token: 'tlstatus.code',
          regex: '{',
          push: [{
            token: 'tlstatus.code',
            regex: '}',
            next: 'pop'
          }, {
            include: 'start'
          }]
        },
        {
          caseInsensitive: true
        }
      ],
      tag: [{
          token: 'tlstatus.code',
          regex: '<PRE(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/PRE>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<FONT(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/FONT>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<RUBY(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/RUBY>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<SPAN(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/SPAN>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<U(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/U>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<(voice|k|br)(.*)>'
        },
        {
          caseInsensitive: true
        }
      ],
      text: [{
          token: 'tlstatus.code',
          regex: '\\[text(\\d+)\\]'
        },
        {
          include: 'comment'
        },
        {
          include: 'tag'
        },
        {
          include: 'block'
        },
        {
          defaultToken: 'tlstatus.text'
        },
        {
          caseInsensitive: true
        }
      ]
    };

    this.normalizeRules();
  };

  oop.inherits(NssHighlightRules, TextHighlightRules);

  exports.NssHighlightRules = NssHighlightRules;
});

ace.define("ace/mode/tlstatusnss", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text"], function(require, exports, module) {
  "use strict";

  var oop = require("../lib/oop");
  var TextMode = require("./text").Mode;
  var NssHighlightRules = require("./tlstatusnss_highlight_rules").NssHighlightRules;

  var Mode = function() {
    this.HighlightRules = NssHighlightRules;
    this.foldingRules = null;
    this.$behaviour = this.$defaultBehaviour;
  };
  oop.inherits(Mode, TextMode);

  (function() {
    this.$id = "ace/mode/tlstatusnss";
  }).call(Mode.prototype);

  exports.Mode = Mode;
});<commit_msg>make multiline comments nestable because that's what the original parser does ¯\_(ツ)_/¯<commit_after>ace.define("ace/mode/tlstatusnss_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports, module) {
  "use strict";

  var oop = require("../lib/oop");
  var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

  var NssHighlightRules = function() {
    this.$rules = {
      start: [{
          include: 'comment'
        },
        {
          include: 'block'
        },
        {
          include: 'tag'
        },
        {
          include: 'important_function_call'
        },
        {
          defaultToken: 'tlstatus.code'
        },
        {
          caseInsensitive: true
        }
      ],
      important_function_call: [{
          token: 'tlstatus.no-comment-code',
          regex: '(CreateText|SetBacklog)(\\s*)\\(',
          push: [{
              token: 'tlstatus.no-comment-code',
              regex: '\\)',
              next: 'pop'
            }, {
              include: 'no_comment_lparen'
            },
            {
              defaultToken: 'tlstatus.no-comment-code'
            }
          ]
        },
        {
          caseInsensitive: true
        }
      ],
      no_comment_lparen: [{
          token: 'tlstatus.no-comment-code',
          regex: '\\(',
          push: [{
              token: 'tlstatus.no-comment-code',
              regex: '\\)',
              next: 'pop'
            },
            {
              include: 'no_comment_lparen'
            },
            {
              defaultToken: 'tlstatus.no-comment-code'
            }
          ]
        },
        {
          caseInsensitive: true
        }
      ],
      comment: [{
          token: 'tlstatus.note',
          regex: '^\\/\\/note(.*)'
        },
        {
          token: 'comment.single-line',
          regex: '(^|\\s+)\\/\\/(.*)'
        },
        {
          include: 'multiline_comment'
        },
        {
          caseInsensitive: true
        }
      ],
      multiline_comment: [{ // yes, these are nestable in NSS
          token: 'comment.multiline',
          regex: '\\/\\*',
          push: [{
            token: 'comment.multiline',
            regex: '\\*\\/',
            next: 'pop'
          }, {
            defaultToken: 'comment.multiline'
          }, {
            include: 'multiline_comment'
          }]
      }],
      block: [{
          token: 'tlstatus.code',
          regex: '{',
          push: [{
            token: 'tlstatus.code',
            regex: '}',
            next: 'pop'
          }, {
            include: 'start'
          }]
        },
        {
          caseInsensitive: true
        }
      ],
      tag: [{
          token: 'tlstatus.code',
          regex: '<PRE(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/PRE>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<FONT(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/FONT>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<RUBY(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/RUBY>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<SPAN(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/SPAN>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<U(.*?)>',
          push: [{
            token: 'tlstatus.code',
            regex: '<\\/U>',
            next: 'pop'
          }, {
            include: 'text'
          }]
        },
        {
          token: 'tlstatus.code',
          regex: '<(voice|k|br)(.*)>'
        },
        {
          caseInsensitive: true
        }
      ],
      text: [{
          token: 'tlstatus.code',
          regex: '\\[text(\\d+)\\]'
        },
        {
          include: 'comment'
        },
        {
          include: 'tag'
        },
        {
          include: 'block'
        },
        {
          defaultToken: 'tlstatus.text'
        },
        {
          caseInsensitive: true
        }
      ]
    };

    this.normalizeRules();
  };

  oop.inherits(NssHighlightRules, TextHighlightRules);

  exports.NssHighlightRules = NssHighlightRules;
});

ace.define("ace/mode/tlstatusnss", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text"], function(require, exports, module) {
  "use strict";

  var oop = require("../lib/oop");
  var TextMode = require("./text").Mode;
  var NssHighlightRules = require("./tlstatusnss_highlight_rules").NssHighlightRules;

  var Mode = function() {
    this.HighlightRules = NssHighlightRules;
    this.foldingRules = null;
    this.$behaviour = this.$defaultBehaviour;
  };
  oop.inherits(Mode, TextMode);

  (function() {
    this.$id = "ace/mode/tlstatusnss";
  }).call(Mode.prototype);

  exports.Mode = Mode;
});<|endoftext|>


<commit_before>var auctionModule = angular.module('auction');

auctionModule.factory('Items', ['$resource', function($resource) {
  return $resource('/auction.json',{}, {
    query: {method: 'GET', isArray: true}
  });
}]);

auctionModule.controller('AuctionCtrl', ['$scope', '$timeout', '$http', 'Items', function($scope, $timeout, $http, Items) {

  $scope.init = function() {
    $scope.itemsPerPage = 10;
    $scope.pageNumber = 0;
    $scope.totalItems = 0;
    $scope.timeLeft = 3600;

    $scope.allItems = [];
    $scope.pageItems = [];

    (function refreshItems() {
      Items.query({}, function(items) {
          $scope.totalItems = items.length;
          $scope.allItems = items;
          $scope.pageItems = [];

          var firstItemIndex = $scope.pageNumber * $scope.itemsPerPage;
          var lastItemIndex = firstItemIndex + $scope.itemsPerPage;
          angular.forEach($scope.allItems, function(item, index) {
            if(index >= firstItemIndex && index < lastItemIndex) {
              $scope.pageItems.push(item);
            }
          });

         // $timeout(refreshItems, 1000);
      });
    })();

    (function refreshAmountRaised() {
      $http({method: 'GET', url: '/amount_raised'}).
      success(function(data, status, headers, config) {
        $scope.amountRaised = data.amount_raised;
      });

      $timeout(refreshAmountRaised, 1000);
    })();

    (function refreshTimer() {
      $http({method: 'GET', url: '/time_left'}).
      success(function(data, status, headers, config) {
        $scope.timeLeft = data.time_left;
      });

      $timeout(refreshTimer, 60000);
    })();

    (function tickTimeLeft() {
      if($scope.timeLeft > 0) {
        $scope.timeLeft = $scope.timeLeft - 1;
        duration = moment.duration($scope.timeLeft, 'seconds');
        $scope.timer = moment(duration.asMilliseconds()).utc().format('H:mm:ss');

        $timeout(tickTimeLeft, 1000);
      } else {
        $scope.timer = 'Auction is now closed';
      }
    })();

    (function nextPage() {
      $scope.loadNextPage();
      // $timeout(nextPage, 10000);
    })();

  };

  $scope.loadNextPage = function() {
    $scope.pageNumber = $scope.pageNumber + 1;
    if($scope.pageNumber > ($scope.totalItems / $scope.itemsPerPage)) {
      $scope.pageNumber = 0;
    }
  };

}]);
<commit_msg>Rvert polling<commit_after>var auctionModule = angular.module('auction');

auctionModule.factory('Items', ['$resource', function($resource) {
  return $resource('/auction.json',{}, {
    query: {method: 'GET', isArray: true}
  });
}]);

auctionModule.controller('AuctionCtrl', ['$scope', '$timeout', '$http', 'Items', function($scope, $timeout, $http, Items) {

  $scope.init = function() {
    $scope.itemsPerPage = 10;
    $scope.pageNumber = 0;
    $scope.totalItems = 0;
    $scope.timeLeft = 3600;

    $scope.allItems = [];
    $scope.pageItems = [];

    (function refreshItems() {
      Items.query({}, function(items) {
          $scope.totalItems = items.length;
          $scope.allItems = items;
          $scope.pageItems = [];

          var firstItemIndex = $scope.pageNumber * $scope.itemsPerPage;
          var lastItemIndex = firstItemIndex + $scope.itemsPerPage;
          angular.forEach($scope.allItems, function(item, index) {
            if(index >= firstItemIndex && index < lastItemIndex) {
              $scope.pageItems.push(item);
            }
          });

         $timeout(refreshItems, 1000);
      });
    })();

    (function refreshAmountRaised() {
      $http({method: 'GET', url: '/amount_raised'}).
      success(function(data, status, headers, config) {
        $scope.amountRaised = data.amount_raised;
      });

      $timeout(refreshAmountRaised, 1000);
    })();

    (function refreshTimer() {
      $http({method: 'GET', url: '/time_left'}).
      success(function(data, status, headers, config) {
        $scope.timeLeft = data.time_left;
      });

      $timeout(refreshTimer, 60000);
    })();

    (function tickTimeLeft() {
      if($scope.timeLeft > 0) {
        $scope.timeLeft = $scope.timeLeft - 1;
        duration = moment.duration($scope.timeLeft, 'seconds');
        $scope.timer = moment(duration.asMilliseconds()).utc().format('H:mm:ss');

        $timeout(tickTimeLeft, 1000);
      } else {
        $scope.timer = 'Auction is now closed';
      }
    })();

    (function nextPage() {
      $scope.loadNextPage();
      $timeout(nextPage, 10000);
    })();

  };

  $scope.loadNextPage = function() {
    $scope.pageNumber = $scope.pageNumber + 1;
    if($scope.pageNumber > ($scope.totalItems / $scope.itemsPerPage)) {
      $scope.pageNumber = 0;
    }
  };

}]);
<|endoftext|>


<commit_before>'use strict';

function getTaskConfig(projectConfig) {
	var taskConfig = {
		files: {
			bundle: [
				projectConfig.paths.src.scripts + '**/*.js',
				projectConfig.paths.src.components + '**/*.js',
				'!' + projectConfig.paths.src.scripts + 'vendor/*.js'
			],
			vendor: [
				projectConfig.paths.src.scripts + 'vendor/*.js'
			]
		},
		docs: {
		  "opts": {
				"destination": "./docs/gen"
		  }
		},
		useBabel: false,
		jshint: {
			"bitwise"       : true,
			"camelcase"     : true,
			"curly"         : true,
			"eqeqeq"        : true,
			"indent"        : 4,
			"newcap"        : true,
			"noarg"         : true,
			"noempty"       : true,
			"plusplus"      : false,
			"quotmark"      : "single",
			"regexp"        : true,
			"undef"         : true,
			"unused"        : true,
			"strict"        : true,
			"trailing"      : true,
			"maxparams"     : 20,
			"maxdepth"      : 3,
			"maxstatements" : 50,
			"maxcomplexity" : 10,
			"asi"           : false,
			"boss"          : false,
			"debug"         : false,
			"eqnull"        : false,
			"es5"           : false,
			"esnext"        : false,
			"evil"          : false,
			"expr"          : false,
			"funcscope"     : false,
			"globalstrict"  : false,
			"iterator"      : false,
			"lastsemic"     : false,
			"laxbreak"      : false,
			"laxcomma"      : false,
			"loopfunc"      : false,
			"multistr"      : false,
			"onecase"       : false,
			"proto"         : false,
			"regexdash"     : false,
			"scripturl"     : false,
			"smarttabs"     : true,
			"shadow"        : false,
			"sub"           : false,
			"supernew"      : false,
			"validthis"     : false,
			"nomen"         : false,
			"onevar"        : false,
			"passfail"      : false,
			"white"         : false,
			"globals": {
				"$": true,
				"clearInterval": true,
				"clearTimeout": true,
				"console": true,
				"document": true,
				"jQuery": true,
				"ga": true,
				"Modernizr": true,
				"module": true,
				"node": true,
				"process": true,
				"require": true,
				"setInterval": true,
				"setTimeout": true,
				"window": true,
				"XMLHttpRequest": true
			}
		},
		watch: [
			projectConfig.paths.src.scripts + '**/*.js'
		]
	};

	return taskConfig;
}

module.exports = getTaskConfig;
<commit_msg>refactor: Move useBabel config to the top of the file<commit_after>'use strict';

function getTaskConfig(projectConfig) {
	var taskConfig = {
		useBabel: false,
		files: {
			bundle: [
				projectConfig.paths.src.scripts + '**/*.js',
				projectConfig.paths.src.components + '**/*.js',
				'!' + projectConfig.paths.src.scripts + 'vendor/*.js'
			],
			vendor: [
				projectConfig.paths.src.scripts + 'vendor/*.js'
			]
		},
		docs: {
		  "opts": {
				"destination": "./docs/gen"
		  }
		},
		jshint: {
			"bitwise"       : true,
			"camelcase"     : true,
			"curly"         : true,
			"eqeqeq"        : true,
			"indent"        : 4,
			"newcap"        : true,
			"noarg"         : true,
			"noempty"       : true,
			"plusplus"      : false,
			"quotmark"      : "single",
			"regexp"        : true,
			"undef"         : true,
			"unused"        : true,
			"strict"        : true,
			"trailing"      : true,
			"maxparams"     : 20,
			"maxdepth"      : 3,
			"maxstatements" : 50,
			"maxcomplexity" : 10,
			"asi"           : false,
			"boss"          : false,
			"debug"         : false,
			"eqnull"        : false,
			"es5"           : false,
			"esnext"        : false,
			"evil"          : false,
			"expr"          : false,
			"funcscope"     : false,
			"globalstrict"  : false,
			"iterator"      : false,
			"lastsemic"     : false,
			"laxbreak"      : false,
			"laxcomma"      : false,
			"loopfunc"      : false,
			"multistr"      : false,
			"onecase"       : false,
			"proto"         : false,
			"regexdash"     : false,
			"scripturl"     : false,
			"smarttabs"     : true,
			"shadow"        : false,
			"sub"           : false,
			"supernew"      : false,
			"validthis"     : false,
			"nomen"         : false,
			"onevar"        : false,
			"passfail"      : false,
			"white"         : false,
			"globals": {
				"$": true,
				"clearInterval": true,
				"clearTimeout": true,
				"console": true,
				"document": true,
				"jQuery": true,
				"ga": true,
				"Modernizr": true,
				"module": true,
				"node": true,
				"process": true,
				"require": true,
				"setInterval": true,
				"setTimeout": true,
				"window": true,
				"XMLHttpRequest": true
			}
		},
		watch: [
			projectConfig.paths.src.scripts + '**/*.js'
		]
	};

	return taskConfig;
}

module.exports = getTaskConfig;
<|endoftext|>


<commit_before>var PrettyError = require('pretty-error');
var pe = new PrettyError();

function errorHandler(error) {

	var prettyError = pe.render(new Error(error));

	console.error('');
	console.error(prettyError);

	process.exit(1);
}

function setPrettyErrrorTheme() {
	pe.appendStyle({
		'pretty-error > header > title > kind': {
			display: 'none'
		},

		// the 'colon' after 'Error':
		'pretty-error > header > colon': {
			display: 'none'
		},

		// our error message
		'pretty-error > header > message': {
			color: 'bright-white',
			//colour range red, green, yellow, blue, magenta, cyan, white,
			background: 'red',
			padding: '0 1' // top/bottom left/right
		},

		// each trace item ...
		'pretty-error > trace > item': {
			marginLeft: 2,
			marginBottom: 0,
			bullet: '"<grey>-</grey>"'
		},

		'pretty-error > trace > item > header > pointer > file': {
			color: 'yellow'
		},

		'pretty-error > trace > item > header > pointer > colon': {
			color: 'yellow'
		},

		'pretty-error > trace > item > header > pointer > line': {
			color: 'bright-cyan'
		},

		'pretty-error > trace > item > header > what': {
			color: 'bright-white'
		},

		'pretty-error > trace > item > footer > addr': {
			// display: 'none'
			marginLeft: 4
		}
	});
}

setPrettyErrrorTheme();

module.exports = errorHandler<commit_msg>feat: Change error bullet type<commit_after>var PrettyError = require('pretty-error');
var pe = new PrettyError();

function errorHandler(error) {

	var prettyError = pe.render(new Error(error));

	console.error('');
	console.error(prettyError);

	process.exit(1);
}

function setPrettyErrrorTheme() {
	pe.appendStyle({
		'pretty-error > header > title > kind': {
			display: 'none'
		},

		// the 'colon' after 'Error':
		'pretty-error > header > colon': {
			display: 'none'
		},

		// our error message
		'pretty-error > header > message': {
			color: 'bright-white',
			//colour range red, green, yellow, blue, magenta, cyan, white,
			background: 'red',
			padding: '0 1' // top/bottom left/right
		},

		// each trace item ...
		'pretty-error > trace > item': {
			marginLeft: 2,
			marginBottom: 0,
			bullet: '"<grey>· </grey>"'
		},

		'pretty-error > trace > item > header > pointer > file': {
			color: 'yellow'
		},

		'pretty-error > trace > item > header > pointer > colon': {
			color: 'yellow'
		},

		'pretty-error > trace > item > header > pointer > line': {
			color: 'bright-cyan'
		},

		'pretty-error > trace > item > header > what': {
			color: 'bright-white'
		},

		'pretty-error > trace > item > footer > addr': {
			// display: 'none'
			marginLeft: 4
		}
	});
}

setPrettyErrrorTheme();

module.exports = errorHandler<|endoftext|>


<commit_before>'use strict';

let mlbRequest = require('./request'),
    find = require('../find'),
    prune = require('../prune'),
    validate = require('../validate');

/**
 * Constructs and makes call to MLB for stats.
 *
 * @private
 * @param {Object|string} options - The options to make the request with.
 * @param {string} options.player_id - ID of player to get stats for.
 * @param {string} [options.pitching=false] - The type of stats to get.
 * @param {string} [options.year] - The season to get stats for.
 * @returns {Promise} - Promise to be fulfilled with player stats object, or error.
 */
function getStats(options) {
    return new Promise (function (resolve, reject) {
        validate.statsOptions(options, (err) => {
            if (err) {
                reject(err);
            }
        });

        let url = mlbRequest.build('stats', options);

        if (!url) {
            reject(new Error('Error building sport_[stat_type]_tm request URL.'));
        }

        mlbRequest.make(url)
            .then(data => {
                if (!options.year) {
                    data = find.latestStats(data);
                }
                if (options.prune) {
                    data = pruneData(data);
                }
                resolve(data);
            })
            .catch(error => {
                reject(error);
            });
    });
}

module.exports = getStats;
<commit_msg>corrently set the data variable to pruned data<commit_after>'use strict';

let mlbRequest = require('./request'),
    find = require('../find'),
    prune = require('../prune'),
    validate = require('../validate');

/**
 * Constructs and makes call to MLB for stats.
 *
 * @private
 * @param {Object|string} options - The options to make the request with.
 * @param {string} options.player_id - ID of player to get stats for.
 * @param {string} [options.pitching=false] - The type of stats to get.
 * @param {string} [options.year] - The season to get stats for.
 * @returns {Promise} - Promise to be fulfilled with player stats object, or error.
 */
function getStats(options) {
    return new Promise (function (resolve, reject) {
        validate.statsOptions(options, (err) => {
            if (err) {
                reject(err);
            }
        });

        let url = mlbRequest.build('stats', options);

        if (!url) {
            reject(new Error('Error building sport_[stat_type]_tm request URL.'));
        }

        mlbRequest.make(url)
            .then(data => {
                if (!options.year) {
                    data = find.latestStats(data);
                }
                if (options.prune) {
                    data = prune(data);
                }
                resolve(data);
            })
            .catch(error => {
                reject(error);
            });
    });
}

module.exports = getStats;
<|endoftext|>


<commit_before>function heredoc(fn) {
    return fn.toString()
        .replace(/^[^\/]+\/\*!?/, '')
        .replace(/\*\/[^\/]+$/, '')
        .replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '')
}

var KISSY_FN_TEMPLATE = heredoc(function() {
    /*
    KISSY.add(function(S, require) {

        return {{code}};

    });
    */
});

var CMD_TEMPLATE = heredoc(function() {
    /*
    define(function(require) {

        return {{code}};

    });
    */
});

var COMMONJS_TEMPLATE = heredoc(function() {
    /*
        module.exports = {{code}};
    */
});

var AMD_TEMPLATE = heredoc(function() {
    /*
    define(function(require) {

        return {{code}};

    });
    */
});

var KISSY_TEMPLATE = heredoc(function() {
    /*
    KISSY.add(function(S, require) {
        var Crox = require('crox');

        var tmpl = '{{tmpl}}';
        {{replaces}}

        var fn = Crox.compile(tmpl);
        fn.tmpl = tmpl;

        return fn;
    });
    */
});

exports.KISSY_FN_TEMPLATE = KISSY_FN_TEMPLATE;
exports.CMD_TEMPLATE = CMD_TEMPLATE;
exports.COMMONJS_TEMPLATE = COMMONJS_TEMPLATE;
exports.AMD_TEMPLATE = AMD_TEMPLATE;
exports.KISSY_TEMPLATE = KISSY_TEMPLATE;<commit_msg>indent<commit_after>function heredoc(fn) {
    return fn.toString()
        .replace(/^[^\/]+\/\*!?/, '')
        .replace(/\*\/[^\/]+$/, '')
        .replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '')
}

var KISSY_FN_TEMPLATE = heredoc(function() {
    /*
    KISSY.add(function(S, require) {

        return {{code}};

    });
    */
});

var CMD_TEMPLATE = heredoc(function() {
    /*
    define(function(require) {

        return {{code}};

    });
    */
});

var COMMONJS_TEMPLATE = heredoc(function() {
    /*
    module.exports = {{code}};
    */
});

var AMD_TEMPLATE = heredoc(function() {
    /*
    define(function(require) {

        return {{code}};

    });
    */
});

var KISSY_TEMPLATE = heredoc(function() {
    /*
    KISSY.add(function(S, require) {
        var Crox = require('crox');

        var tmpl = '{{tmpl}}';
        {{replaces}}

        var fn = Crox.compile(tmpl);
        fn.tmpl = tmpl;

        return fn;
    });
    */
});

exports.KISSY_FN_TEMPLATE = KISSY_FN_TEMPLATE;
exports.CMD_TEMPLATE = CMD_TEMPLATE;
exports.COMMONJS_TEMPLATE = COMMONJS_TEMPLATE;
exports.AMD_TEMPLATE = AMD_TEMPLATE;
exports.KISSY_TEMPLATE = KISSY_TEMPLATE;<|endoftext|>


<commit_before>var commonChartOptions = {
  title: { text: null },
  xAxis: { showEmpty: false },
  yAxis: { showEmpty: false },
  legend: {
    align: 'center',
    x: -30,
    margin: 20,
    verticalAlign: 'bottom',
    floating: false,
    backgroundColor: 'white',
    shadow: false
  },
  plotOptions: {
    bar: {
      stacking: 'normal',
    },
    column: {
      dataLabels: {
        color: '#232b49'
      },
    },
    pie: {
      allowPointSelect: true,
      colors: ["#9c3367", "#67347f", "#501e74", "#935fb8", "#e676a3", "#e4558b", "#7a9fb1", "#5297c6", "#97c086", "#3f7d69", "#6dc691", "#8e8d6b", "#e5c07c", "#e9d889", "#e59757", "#f4966c", "#e5644e", "#cd4851", "#bd4d65", "#515749"],
      cursor: 'pointer',
      dataLabels: { enabled: false },
      showInLegend: true,
      point: {
        events: {
          legendItemClick: function () {
            return false;
          }
        }
      }
    },
    line: {
      tooltip: {
        headerFormat: '{point.key}
',
        pointFormat: '{point.y:.2f} kW'
      }
    },
    scatter: {
      marker: {
        radius: 5,
        states: {
          hover: {
            enabled: true,
            lineColor: 'rgb(100,100,100)'
          }
        }
      },
      states: {
        hover: {
          marker: {
            enabled: false
          }
        }
      },
      tooltip: {
        headerFormat: '{series.name}
',
        pointFormat: '{point.x:.2f} °C, {point.y:.2f} kWh'
      }
    }
  }
}

function barColumnLine(d, c, chartIndex, seriesData, yAxisLabel, chartType) {
  var subChartType = d.chart1_subtype;
  console.log('bar or column or line ' + subChartType);

  var xAxisCategories = d.x_axis_categories;
  var y2AxisLabel = d.y2_axis_label;

  c.xAxis[0].setCategories(xAxisCategories);

  // BAR Charts
  if (chartType == 'bar') {
    console.log('bar');
    c.update({ chart: { inverted: true }, yAxis: [{ stackLabels: { style: { fontWeight: 'bold',  color: '#232b49' } } }], plotOptions: { bar: { tooltip: { headerFormat: '{series.name}
', pointFormat: yAxisLabel + '{point.y:.2f}' }}}});
  }

  // LINE charts
  if (chartType == 'line') {
    if (y2AxisLabel !== undefined && y2AxisLabel == 'Temperature') {
      console.log('Yaxis - Temperature');
      c.addAxis({ title: { text: '°C' }, stackLabels: { style: { fontWeight: 'bold',  color: '#232b49' }}, opposite: true });
      c.update({ plotOptions: { line: { tooltip: { headerFormat: '{point.key}
',  pointFormat: '{point.y:.2f} °C' }}}});
    } else {
      c.update({ plotOptions: { line: { tooltip: { headerFormat: '{point.key}
',  pointFormat: '{point.y:.2f}' + yAxisLabel }}}});
    }
  }

  // Column charts
  if (chartType == 'column') {
    console.log('column: ' + subChartType);

    if (subChartType == 'stacked') {
      c.update({ plotOptions: { column: { tooltip: { headerFormat: '{series.name}
', pointFormat: '{point.y:.2f}' + yAxisLabel }, stacking: 'normal'}}, yAxis: [{title: { text: yAxisLabel }, stackLabels: { style: { fontWeight: 'bold',  color: '#232b49' } } }]});
    } else {
      c.update({ plotOptions: { column: { tooltip: { headerFormat: '{series.name}
', pointFormat: '{point.y:.2f}' + yAxisLabel }}}});
    }

    if (y2AxisLabel !== undefined && (y2AxisLabel == 'Degree Days' || y2AxisLabel == 'Temperature')) {
      console.log('Yaxis - Degree days');
      c.addAxis({ title: { text: '°C' }, stackLabels: { style: { fontWeight: 'bold',  color: '#232b49' }}, opposite: true });
      c.update({ plotOptions: { line: { tooltip: { headerFormat: '{point.key}
',  pointFormat: '{point.y:.2f} °C' }}}});
    }
  }

  Object.keys(seriesData).forEach(function (key) {
    console.log('Series data name: ' + seriesData[key].name);

    if (seriesData[key].name == 'CUSUM') {
      c.update({ plotOptions: { line: { tooltip: { pointFormat: '{point.y:.2f}', valueSuffix: yAxisLabel }}}});
    }

    if (seriesData[key].name.startsWith('Energy')) {
      seriesData[key].tooltip = { pointFormat: '{point.y:.2f} ' + yAxisLabel  }
    }
    // The false parameter stops it being redrawed after every addition of series data
    c.addSeries(seriesData[key], false);
  });

  if (yAxisLabel.length) {
    console.log('we have a yAxisLabel ' + yAxisLabel);
    c.update({ yAxis: [{ title: { text: yAxisLabel }}]});
  }
  c.redraw();
}

function scatter(d, c, chartIndex, seriesData, yAxisLabel) {
  console.log('scatter');
  c.update({chart: { type: 'scatter' }});

  if (yAxisLabel.length) {
    console.log('we have a yAxisLabel ' + yAxisLabel);
    c.update({ xAxis: [{ title: { text: 'Degree Days' }}], yAxis: [{ title: { text: yAxisLabel }}]});
  }

  Object.keys(seriesData).forEach(function (key) {
    console.log(seriesData[key].name);
    c.addSeries(seriesData[key], false);
  });
  c.redraw();
}

function pie(d, c, chartIndex, seriesData, $chartDiv, yAxisLabel) {
  $chartDiv.addClass('pie-chart');

  c.addSeries(seriesData, false);
  c.update({chart: {
    height: 450,
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  plotOptions: {
   pie: {
    tooltip: {
        headerFormat: '{point.key}
',
        pointFormat: '{point.y:.2f} ' + yAxisLabel
      }
    }
  }
  });
  c.redraw();
}<commit_msg>Dash for energy on optimum start chart<commit_after>var commonChartOptions = {
  title: { text: null },
  xAxis: { showEmpty: false },
  yAxis: { showEmpty: false },
  legend: {
    align: 'center',
    x: -30,
    margin: 20,
    verticalAlign: 'bottom',
    floating: false,
    backgroundColor: 'white',
    shadow: false
  },
  plotOptions: {
    bar: {
      stacking: 'normal',
    },
    column: {
      dataLabels: {
        color: '#232b49'
      },
    },
    pie: {
      allowPointSelect: true,
      colors: ["#9c3367", "#67347f", "#501e74", "#935fb8", "#e676a3", "#e4558b", "#7a9fb1", "#5297c6", "#97c086", "#3f7d69", "#6dc691", "#8e8d6b", "#e5c07c", "#e9d889", "#e59757", "#f4966c", "#e5644e", "#cd4851", "#bd4d65", "#515749"],
      cursor: 'pointer',
      dataLabels: { enabled: false },
      showInLegend: true,
      point: {
        events: {
          legendItemClick: function () {
            return false;
          }
        }
      }
    },
    line: {
      tooltip: {
        headerFormat: '{point.key}
',
        pointFormat: '{point.y:.2f} kW'
      }
    },
    scatter: {
      marker: {
        radius: 5,
        states: {
          hover: {
            enabled: true,
            lineColor: 'rgb(100,100,100)'
          }
        }
      },
      states: {
        hover: {
          marker: {
            enabled: false
          }
        }
      },
      tooltip: {
        headerFormat: '{series.name}
',
        pointFormat: '{point.x:.2f} °C, {point.y:.2f} kWh'
      }
    }
  }
}

function barColumnLine(d, c, chartIndex, seriesData, yAxisLabel, chartType) {
  var subChartType = d.chart1_subtype;
  console.log('bar or column or line ' + subChartType);

  var xAxisCategories = d.x_axis_categories;
  var y2AxisLabel = d.y2_axis_label;

  c.xAxis[0].setCategories(xAxisCategories);

  // BAR Charts
  if (chartType == 'bar') {
    console.log('bar');
    c.update({ chart: { inverted: true }, yAxis: [{ stackLabels: { style: { fontWeight: 'bold',  color: '#232b49' } } }], plotOptions: { bar: { tooltip: { headerFormat: '{series.name}
', pointFormat: yAxisLabel + '{point.y:.2f}' }}}});
  }

  // LINE charts
  if (chartType == 'line') {
    if (y2AxisLabel !== undefined && y2AxisLabel == 'Temperature') {
      console.log('Yaxis - Temperature');
      c.addAxis({ title: { text: '°C' }, stackLabels: { style: { fontWeight: 'bold',  color: '#232b49' }}, opposite: true });
      c.update({ plotOptions: { line: { tooltip: { headerFormat: '{point.key}
',  pointFormat: '{point.y:.2f} °C' }}}});
    } else {
      c.update({ plotOptions: { line: { tooltip: { headerFormat: '{point.key}
',  pointFormat: '{point.y:.2f}' + yAxisLabel }}}});
    }
  }

  // Column charts
  if (chartType == 'column') {
    console.log('column: ' + subChartType);

    if (subChartType == 'stacked') {
      c.update({ plotOptions: { column: { tooltip: { headerFormat: '{series.name}
', pointFormat: '{point.y:.2f}' + yAxisLabel }, stacking: 'normal'}}, yAxis: [{title: { text: yAxisLabel }, stackLabels: { style: { fontWeight: 'bold',  color: '#232b49' } } }]});
    } else {
      c.update({ plotOptions: { column: { tooltip: { headerFormat: '{series.name}
', pointFormat: '{point.y:.2f}' + yAxisLabel }}}});
    }

    if (y2AxisLabel !== undefined && (y2AxisLabel == 'Degree Days' || y2AxisLabel == 'Temperature')) {
      console.log('Yaxis - Degree days');
      c.addAxis({ title: { text: '°C' }, stackLabels: { style: { fontWeight: 'bold',  color: '#232b49' }}, opposite: true });
      c.update({ plotOptions: { line: { tooltip: { headerFormat: '{point.key}
',  pointFormat: '{point.y:.2f} °C' }}}});
    }
  }

  Object.keys(seriesData).forEach(function (key) {
    console.log('Series data name: ' + seriesData[key].name);

    if (seriesData[key].name == 'CUSUM') {
      c.update({ plotOptions: { line: { tooltip: { pointFormat: '{point.y:.2f}', valueSuffix: yAxisLabel }}}});
    }

    if (seriesData[key].name.startsWith('Energy') && seriesData[key].type == 'line') {
      console.log(seriesData[key]);
      seriesData[key].tooltip = { pointFormat: '{point.y:.2f} ' + yAxisLabel  }
      seriesData[key].dashStyle =  'Dash';
    }
    // The false parameter stops it being redrawed after every addition of series data
    c.addSeries(seriesData[key], false);
  });

  if (yAxisLabel.length) {
    console.log('we have a yAxisLabel ' + yAxisLabel);
    c.update({ yAxis: [{ title: { text: yAxisLabel }}]});
  }
  c.redraw();
}

function scatter(d, c, chartIndex, seriesData, yAxisLabel) {
  console.log('scatter');
  c.update({chart: { type: 'scatter' }});

  if (yAxisLabel.length) {
    console.log('we have a yAxisLabel ' + yAxisLabel);
    c.update({ xAxis: [{ title: { text: 'Degree Days' }}], yAxis: [{ title: { text: yAxisLabel }}]});
  }

  Object.keys(seriesData).forEach(function (key) {
    console.log(seriesData[key].name);
    c.addSeries(seriesData[key], false);
  });
  c.redraw();
}

function pie(d, c, chartIndex, seriesData, $chartDiv, yAxisLabel) {
  $chartDiv.addClass('pie-chart');

  c.addSeries(seriesData, false);
  c.update({chart: {
    height: 450,
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  plotOptions: {
   pie: {
    tooltip: {
        headerFormat: '{point.key}
',
        pointFormat: '{point.y:.2f} ' + yAxisLabel
      }
    }
  }
  });
  c.redraw();
}<|endoftext|>


<commit_before>#!/usr/bin/env node

/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-mqtt
 *
 * iotagent-mqtt is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-mqtt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-mqtt.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

var iotAgent = require('../lib/iotagent-mqtt'),
    context = {
        op: 'IOTAMQTT.Executable'
    },
    logger = require('logops');

function start() {
    var config;

    if (process.argv.length === 3) {
        config = require('../' + process.argv[2]);
    } else {
        config = require('../config');
    }

    iotAgent.start(config, function (error) {
        if (error) {
            logger.error(context, 'Error starting MQTT IoT Agent: [%s] Exiting process', error);
        } else {
            logger.info(context, 'MQTT IoT Agent started');
        }
    });
}

start();<commit_msg>ADD Final blank line<commit_after>#!/usr/bin/env node

/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-mqtt
 *
 * iotagent-mqtt is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-mqtt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-mqtt.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

var iotAgent = require('../lib/iotagent-mqtt'),
    context = {
        op: 'IOTAMQTT.Executable'
    },
    logger = require('logops');

function start() {
    var config;

    if (process.argv.length === 3) {
        config = require('../' + process.argv[2]);
    } else {
        config = require('../config');
    }

    iotAgent.start(config, function (error) {
        if (error) {
            logger.error(context, 'Error starting MQTT IoT Agent: [%s] Exiting process', error);
        } else {
            logger.info(context, 'MQTT IoT Agent started');
        }
    });
}

start();
<|endoftext|>