<commit_before>if (typeof require != "undefined") {
    var buster = require("buster-core");
}

buster.stackFilter = function (stack, cwd) {
    var lines = (stack || "").split("\n");
    var stackLines = [], line, replacer = "./";

    if (typeof cwd == "string") {
        cwd = cwd.replace(/\/?$/, "/");
    }

    if (cwd instanceof RegExp && !/\/\/$/.test(cwd)) {
        replacer = ".";
    }

    for (var i = 0, l = lines.length; i < l; ++i) {
        if (/(\d+)?:\d+\)?$/.test(lines[i])) {
            if (!buster.stackFilter.match(lines[i])) {
                line = lines[i].trim();

                if (cwd) {
                    line = line.replace(cwd, replacer);
                }

                stackLines.push(line);
            }
        }
    }

    return stackLines;
};

var regexpes = {};

buster.stackFilter.match = function (line) {
    var filters = buster.stackFilter.filters;

    for (var i = 0, l = filters.length; i < l; ++i) {
        if (!regexpes[filters[i]]) {
            regexpes[filters[i]] = new RegExp(filters[i]);
        }

        if (regexpes[filters[i]].test(line)) {
            return true;
        }
    }

    return false;
}

buster.stackFilter.filters = ["buster-assert/lib",
                              "buster-test/lib",
                              "buster-util/lib",
                              "buster-core/lib",
                              "node.js",
                              "static/runner.js"/* JsTestDriver */];

if (typeof module != "undefined") {
    module.exports = buster.stackFilter;
}
<commit_msg>More default paths in stack filters<commit_after>if (typeof require != "undefined") {
    var buster = require("buster-core");
}

buster.stackFilter = function (stack, cwd) {
    var lines = (stack || "").split("\n");
    var stackLines = [], line, replacer = "./";

    if (typeof cwd == "string") {
        cwd = cwd.replace(/\/?$/, "/");
    }

    if (cwd instanceof RegExp && !/\/\/$/.test(cwd)) {
        replacer = ".";
    }

    for (var i = 0, l = lines.length; i < l; ++i) {
        if (/(\d+)?:\d+\)?$/.test(lines[i])) {
            if (!buster.stackFilter.match(lines[i])) {
                line = lines[i].trim();

                if (cwd) {
                    line = line.replace(cwd, replacer);
                }

                stackLines.push(line);
            }
        }
    }

    return stackLines;
};

var regexpes = {};

buster.stackFilter.match = function (line) {
    var filters = buster.stackFilter.filters;

    for (var i = 0, l = filters.length; i < l; ++i) {
        if (!regexpes[filters[i]]) {
            regexpes[filters[i]] = new RegExp(filters[i]);
        }

        if (regexpes[filters[i]].test(line)) {
            return true;
        }
    }

    return false;
}

buster.stackFilter.filters = ["buster-assertions/lib",
                              "buster-test/lib",
                              "buster-util/lib",
                              "buster-core/lib",
                              "node.js",
                              "/buster/lib",
                              "/buster/node_modules",
                              "static/runner.js"/* JsTestDriver */];

if (typeof module != "undefined") {
    module.exports = buster.stackFilter;
}
<|endoftext|>


<commit_before>google.load('visualization', '1', {packages:['orgchart']});
//TODO: Wrap this functionality as an object
var tbl;
var chart;
var clickHandler = function( id ){};//Dummy click-handler
function initChart() {
    //Initialize tbl (internal data table drawn on the chart) and chart
    tbl = new google.visualization.DataTable();
    tbl.addColumn('string', 'UrlAndLabel');
    tbl.addColumn('string', 'ParentUrl');
    tbl.addColumn('string', 'ToolTip');//Not used but specified by orgchart
    chart = new google.visualization.OrgChart(document.getElementById('chart_panel'));//TODO: replace chart_panel by parameter
    //Get a call to selectHandler() when chart is clicked
    google.visualization.events.addListener(chart, 'select', selectHandler);
}
function setClickHandler( callback ){
  clickHandler = callback;
}
function selectHandler() {
  var rowIndex = chart.getSelection()[0].row;//This may work badly if more than one node is selected
  var rowId = tbl.getValue(rowIndex, 0);
  clickHandler( rowId );
}
function updateChart() {
    chart.draw(tbl, {allowHtml:true, size:'small'});
}
function addNodeToChartIfNotThere( id, label, parentId, relation) {
  if ($.inArray( id, tbl.getDistinctValues(0)) === -1) {
    addNodeToChart( id, label, parentId, relation);
  }
}
function addNodeToChart( id, label, parentId, _relation) {
  tbl.addRow(
    [ { v: id, //v is the URL that child nodes can point to
        f: '
' + label + '
'},
        parentId,
        ""//No tooltip
    ]);
}
function removeAllNodesFromChart() {
  tbl.removeRows(0, tbl.getNumberOfRows());
}
<commit_msg>Fixed bug caused by renaming of DOM element For #master<commit_after>google.load('visualization', '1', {packages:['orgchart']});
//TODO: Wrap this functionality as an object
var tbl;
var chart;
var clickHandler = function( id ){};//Dummy click-handler
function initChart() {
    //Initialize tbl (internal data table drawn on the chart) and chart
    tbl = new google.visualization.DataTable();
    tbl.addColumn('string', 'UrlAndLabel');
    tbl.addColumn('string', 'ParentUrl');
    tbl.addColumn('string', 'ToolTip');//Not used but specified by orgchart
    chart = new google.visualization.OrgChart(document.getElementById('chartPanel'));//TODO: replace chart_panel by parameter
    //Get a call to selectHandler() when chart is clicked
    google.visualization.events.addListener(chart, 'select', selectHandler);
}
function setClickHandler( callback ){
  clickHandler = callback;
}
function selectHandler() {
  var rowIndex = chart.getSelection()[0].row;//This may work badly if more than one node is selected
  var rowId = tbl.getValue(rowIndex, 0);
  clickHandler( rowId );
}
function updateChart() {
    chart.draw(tbl, {allowHtml:true, size:'small'});
}
function addNodeToChartIfNotThere( id, label, parentId, relation) {
  if ($.inArray( id, tbl.getDistinctValues(0)) === -1) {
    addNodeToChart( id, label, parentId, relation);
  }
}
function addNodeToChart( id, label, parentId, _relation) {
  tbl.addRow(
    [ { v: id, //v is the URL that child nodes can point to
        f: '
' + label + '
'},
        parentId,
        ""//No tooltip
    ]);
}
function removeAllNodesFromChart() {
  tbl.removeRows(0, tbl.getNumberOfRows());
}
<|endoftext|>


<commit_before>var setupenv = require("../efront/setupenv");
var path = require("path");
var mixin = require("../efront/mixin");
var fs = require("fs");
var memery = require('../efront/memery');
var {
    APP = ".",
    EXPORT_AS,
    EXPORT_TO,
    RELEASE,
    PREFIX,
    POLYFILL,
    SOURCEDIR,
    DESTPATH,
} = memery

var PUBLIC_APP = /* process.argv[2] || */ APP;
var env = PUBLIC_APP ? setupenv(PUBLIC_APP) : setupenv('.');
var {
    PUBLIC_PATH = memery.PUBLIC_PATH || "./public",
} = memery;
var PAGE = env.PAGE || "";
var COMM = env.COMM;
var ICON = env.ICON;
var AAPI = env.APIS || "";
var PAGE_PATH = memery.PAGE_PATH;
var COMS_PATH = memery.coms_path;
var ICON_PATH = memery.ICON_PATH;
var joinpath = ([a, b]) => path.resolve(path.join(a || '', b || ''));
var comms_root = mixin(memery.coms_path, env.COMM).map(joinpath).filter(fs.existsSync);
var comms_root_length = comms_root.length;
var buildinpath = path.join(__dirname, '..');
comms_root = comms_root.filter(a => path.resolve(a) !== buildinpath);
if (comms_root.length < comms_root_length) comms_root.push(buildinpath);
var ccons_root = ICON && ICON_PATH ? mixin(env.ICON_PATH, env.ICON).map(joinpath).filter(fs.existsSync) : [];
var pages_root = mixin(memery.PAGE_PATH, env.PAGE).map(joinpath).filter(fs.existsSync);
POLYFILL = !/^(0|false|null)$/i.test(POLYFILL);
var resolve_component_file_path = function (public_path = APP, source_paths = [""].concat(pages_root, comms_root)) {
    for (var cx = 0, dx = source_paths.length; cx < dx; cx++) {
        var temp_path = source_paths[cx];
        var public_app = path.join(temp_path, public_path);
        if (fs.existsSync(public_app) && fs.statSync(public_app).isFile()) return public_app;
    }
    return "";
};
var public_app = resolve_component_file_path().replace(/\\/g, '/');
if (public_app && !pages_root.length) {
    var temp = path.resolve(APP), parent = path.dirname(temp);
    if (fs.existsSync(parent)) pages_root.push(parent);
    if (/^index(\.[cm]?[jt]sx?)?$/i.test(path.basename(temp))) pages_root.push(path.dirname(parent));
    while (temp && temp !== parent) {
        temp = parent;
        var modulepath = path.join(parent, 'node_modules');
        if (fs.existsSync(modulepath)) {
            if (!comms_root.indexOf(modulepath)) comms_root.push(modulepath);
        }
        parent = path.dirname(temp);
    }
}

if (EXPORT_TO === undefined) EXPORT_TO = public_app
    .replace(/\.[cm]?[jt]sx?$/i, '')
    .replace(/([\w\-]+)\/index$/i, "$1")
    .replace(/\-(\w)/g, (_, w) => w.toUpperCase())
    .replace(/[\s\S]*\/([^\\\/]+)$/, "$1");
var aapis_root = "./apis/" + AAPI;
module.exports = {
    comms_root,
    class_prefix: PREFIX || '',
    ccons_root,
    pages_root,
    aapis_root,
    PAGE,
    COMM,
    ICON,
    SOURCEDIR,
    AAPI,
    PUBLIC_PATH,
    PAGE_PATH,
    COMS_PATH,
    POLYFILL,
    public_app,
    EXPORT_TO,
    EXPORT_AS,
    DESTPATH,
    include_required: !!RELEASE || !public_app,
    APP
};
<commit_msg>解决无法导出非组件目录的组件的问题<commit_after>var setupenv = require("../efront/setupenv");
var path = require("path");
var mixin = require("../efront/mixin");
var fs = require("fs");
var memery = require('../efront/memery');
var {
    APP = ".",
    EXPORT_AS,
    EXPORT_TO,
    RELEASE,
    PREFIX,
    POLYFILL,
    SOURCEDIR,
    DESTPATH,
} = memery

var PUBLIC_APP = /* process.argv[2] || */ APP;
var env = PUBLIC_APP ? setupenv(PUBLIC_APP) : setupenv('.');
var {
    PUBLIC_PATH = memery.PUBLIC_PATH || "./public",
} = memery;
var PAGE = env.PAGE || "";
var COMM = env.COMM;
var ICON = env.ICON;
var AAPI = env.APIS || "";
var PAGE_PATH = memery.PAGE_PATH;
var COMS_PATH = memery.coms_path;
var ICON_PATH = memery.ICON_PATH;
var joinpath = ([a, b]) => path.resolve(path.join(a || '', b || ''));
var comms_root = mixin(memery.coms_path, env.COMM).map(joinpath).filter(fs.existsSync);
var comms_root_length = comms_root.length;
var buildinpath = path.join(__dirname, '..');
comms_root = comms_root.filter(a => path.resolve(a) !== buildinpath);
if (comms_root.length < comms_root_length) comms_root.push(buildinpath);
var ccons_root = ICON && ICON_PATH ? mixin(env.ICON_PATH, env.ICON).map(joinpath).filter(fs.existsSync) : [];
var pages_root = mixin(memery.PAGE_PATH, env.PAGE).map(joinpath).filter(fs.existsSync);
POLYFILL = !/^(0|false|null)$/i.test(POLYFILL);
var resolve_component_file_path = function (public_path = APP, source_paths = [""].concat(pages_root, comms_root)) {
    for (var cx = 0, dx = source_paths.length; cx < dx; cx++) {
        var temp_path = source_paths[cx];
        var public_app = path.join(temp_path, public_path);
        if (fs.existsSync(public_app) && fs.statSync(public_app).isFile()) {
            if (cx === 0) pages_root = [""];
            return public_app;
        }
    }
    return "";
};
var public_app = resolve_component_file_path().replace(/\\/g, '/');
if (public_app && !pages_root.length) {
    var temp = path.resolve(APP), parent = path.dirname(temp);
    if (fs.existsSync(parent)) pages_root.push(parent);
    if (/^index(\.[cm]?[jt]sx?)?$/i.test(path.basename(temp))) pages_root.push(path.dirname(parent));
    while (temp && temp !== parent) {
        temp = parent;
        var modulepath = path.join(parent, 'node_modules');
        if (fs.existsSync(modulepath)) {
            if (!comms_root.indexOf(modulepath)) comms_root.push(modulepath);
        }
        parent = path.dirname(temp);
    }
}

if (EXPORT_TO === undefined) EXPORT_TO = public_app
    .replace(/\.[cm]?[jt]sx?$/i, '')
    .replace(/([\w\-]+)\/index$/i, "$1")
    .replace(/\-(\w)/g, (_, w) => w.toUpperCase())
    .replace(/[\s\S]*\/([^\\\/]+)$/, "$1");
var aapis_root = "./apis/" + AAPI;
module.exports = {
    comms_root,
    class_prefix: PREFIX || '',
    ccons_root,
    pages_root,
    aapis_root,
    PAGE,
    COMM,
    ICON,
    SOURCEDIR,
    AAPI,
    PUBLIC_PATH,
    PAGE_PATH,
    COMS_PATH,
    POLYFILL,
    public_app,
    EXPORT_TO,
    EXPORT_AS,
    DESTPATH,
    include_required: !!RELEASE || !public_app,
    APP
};
<|endoftext|>


<commit_before>/*
    Copyright (C) 2014 Härnösands kommun

    This program 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.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * Initializes GUI from configuration
 * Initialize where to place the different GUI components, and if they should be floating components or not
 */
Ext.define('OpenEMap.Gui', {
    activeAction: null,
    requires: ['OpenEMap.action.DeleteAllFeatures',
               'OpenEMap.action.DeleteGeometry',
               'OpenEMap.action.DeleteMeasure',
               'OpenEMap.action.DetailReport',
               'OpenEMap.action.DrawGeometry',
               'OpenEMap.action.DrawObject',
               'OpenEMap.action.FullExtent',
               'OpenEMap.action.Identify',
               'OpenEMap.action.MeasureArea',
               'OpenEMap.action.MeasureLine',
               'OpenEMap.action.MetadataInfoColumn',
               'OpenEMap.action.ModifyGeometry',
               'OpenEMap.action.ModifyText',
               'OpenEMap.action.Popup',
               'OpenEMap.action.Print',
               'OpenEMap.action.SelectGeometry',
               'OpenEMap.view.BaseLayers',
               'OpenEMap.view.DetailReportResults',
               'OpenEMap.view.IdentifyResults',
               'OpenEMap.view.Map',
               'OpenEMap.view.ObjectConfig',
               'OpenEMap.view.SearchCoordinate',
               'OpenEMap.view.SearchFastighet',
               'OpenEMap.view.Scalebar',
               'OpenEMap.view.ShowCoordinate',
               'OpenEMap.view.ZoomTools',
               'OpenEMap.view.layer.Advanced',
               'OpenEMap.view.layer.Basic',
               'GeoExt.container.WmsLegend',
               'GeoExt.container.UrlLegend',
               'GeoExt.container.VectorLegend'],
    objectConfigWindowTitle: 'Object configuration',
    constructor : function(config) {
        this.config = config.config;
        this.gui = config.gui;
        this.map = config.map;
        this.orginalConfig = config.orginalConfig;
        this.serverStore = config.serverStore;
        this.search = config.config.search;
        this.client = config.client;

        // GUI defaults
        if (this.gui === undefined) {
            this.gui = {};
        }
        if (this.gui.map === undefined) {this.gui.map = false;}
        if (this.gui.rightPanel === undefined) {this.gui.rightPanel = {};}

        this.mapPanel = Ext.create('OpenEMap.view.Map', {
            map: this.map,
            extent: this.config.extent,
            config: this.config,
            listeners: {
                'afterrender': function() {
                    if (this.config.attribution) {
                        var el = this.mapPanel.getEl();
                        Ext.DomHelper.append(el, ''+this.config.attribution+'');
                    }
                },
                scope: this
            }
        });

        this.createToolbar();
        this.createZoomToolPanel();
        this.createObjectConfigPanel();
        this.createScalebarPanel();
        this.createShowCoordinatePanel();
        this.createSearchCoordinatePanel();
        this.createRightPanel();
        this.createBaseLayersPanel();

        var items = [];
        items.push(this.mapPanel);
        if (this.zoomTools && !this.gui.zoomTools.renderTo) items.push(this.zoomTools);
        if (this.objectConfig && !this.gui.objectConfig.renderTo) items.push(this.objectConfig);
        if (this.scalebar && !this.gui.scalebar.renderTo) items.push(this.scalebar);
        if (this.showCoordinate && !this.gui.showCoordinate.renderTo) items.push(this.showCoordinate);
        if (this.searchCoordinate && !this.gui.searchCoordinate.renderTo) items.push(this.searchCoordinate);
        if (this.rightPanel && !this.gui.rightPanel.renderTo) items.push(this.rightPanel);
        if (this.baseLayers && !this.gui.baseLayers.renderTo) items.push(this.baseLayers);
        if (this.toolbar && !this.gui.toolbar.renderTo) items.push(this.toolbar);

        // NOTE: Generic ES search as a floating centered field
        /*this.search = Ext.create('OpenEMap.form.Search', {
            mapPanel : this.mapPanel,
            width: 300,
            style: {
                right: '20px',
                bottom: '76px'
            }
        });
        items.push(this.search);*/

        // create map rendered to a target element or as viewport depending on config
        if (this.gui.map) {
            var element = this.gui.map.renderTo ? Ext.get(this.gui.map.renderTo) : undefined;
            this.container = Ext.create('Ext.container.Container', Ext.apply({
                layout : 'absolute',
                border: false,
                width: element ? element.getWidth() : undefined,
                height: element ? element.getHeight() : undefined,
                items : items
            }, this.gui.map));
        } else {
            this.container = Ext.create('Ext.container.Viewport', {
                layout : 'absolute',
                items : items
            });
        }
    },
    destroy: function() {
        if (this.mapPanel) this.mapPanel.destroy();
        if (this.zoomTools) this.zoomTools.destroy();
        if (this.mapLayers) this.mapLayers.destroy();
        if (this.searchFastighet) this.searchFastighet.destroy();
        if (this.searchCoordinate) this.searchCoordinate.destroy();
        if (this.showCoordinate) this.showCoordinate.destroy();
        if (this.toolbar) this.toolbar.destroy();
        if (this.rightPanel) this.rightPanel.destroy();
        if (this.baseLayers) this.baseLayers.destroy();
        if (this.objectConfig) this.objectConfig.destroy();
        if (this.objectConfigWindow) this.objectConfigWindow.destroy();
        if (this.scalebar) this.scalebar.destroy();
        //if (this.search) this.search.destroy();
    },
    onToggle: function(button, pressed) {
        var action = button.baseAction;

        if (!this.objectConfig) return;

        // NOTE: want the effect of unselecting all and hiding object dialog on detoggle, but that is triggered after toggle... so this will have to do
        if (pressed) {
            this.mapPanel.unselectAll();
            this.objectConfig.hide();
            this.activeAction = action;
        }

        action.toggle(pressed);
    },
	/**
	 * Create toolbar
     * @private
	 */
    createToolbar: function() {
        var basePath = this.config.basePath;
        var layers = this.config.layers;

        var createAction = function(type) {
            var cls;
            if((Ext.isObject(type) && Ext.Object.getSize(type) > 0) || (!Ext.isObject(type) && !Ext.isEmpty(type))) {
                if (type === this.config.tools[this.config.tools.length-1]) cls = 'oep-tools-last';

                var config = {
                    map: this.map,
                    mapPanel: this.mapPanel,
                    cls: cls
                };

                if (type.constructor === Object) {
                    Ext.apply(config, type);
                    type = config.type;
                    delete config.type;
                }

                if (type == 'ZoomSelector') {
                    return Ext.create('OpenEMap.form.ZoomSelector', {map: this.map});
                } else if (type == 'DrawObject') {
                     config.objectConfigView = this.objectConfig;
                } else if (type == 'Identify') {
                    config.basePath = basePath;
                    config.layers = layers;
                    config.client = this.client;
                } else if (type == 'Popup') {
                    config.layers = layers;
					if ((config.showOnlyFirstHit === undefined) || (config.showOnlyFirstHit === null)) {
						config.showOnlyFirstHit = true;
	                }
				}

                var action = Ext.create('OpenEMap.action.' + type, config);
                if (config.activate && action.control) {
                    this.controlToActivate = action.control;
                }
                var button = Ext.create('Ext.button.Button', action);
                button.on('toggle', this.onToggle, this);
                return button;
            }
        };

        if (!this.config.tools) {
            this.config.tools = [];
        }

        // TODO: need to apply cls: 'oep-tools-last' to last item...
        var tbar = this.config.tools.map(createAction, this);

        // calc width of toolbar
        var width = 6; // padding
        tbar.forEach(function(item) {
            if (item){
                if (!item.hideFromToolbar) {
	                if (item.constructor == String) {
	                    width += 1; // separator
	                } else if (item.width) {
	                    width += item.width;
	                } else {
	                    width += 24; // button
	                }
	                // add spacing to next control
	                width += 8;
                }
            }
        });
        width += 3; // padding

        // create toolbar as floating left panel if no renderTo target is configured
        if (this.gui.toolbar && !this.gui.toolbar.renderTo) {
            this.toolbar = Ext.create('Ext.toolbar.Toolbar', Ext.apply({
                cls: 'oep-tools',
                y : 20,
                x : 20,
                width: width,
                items: tbar
            }, this.gui.toolbar));
        } else if (this.gui.toolbar && this.gui.toolbar.renderTo) {
            this.toolbar = Ext.create('Ext.toolbar.Toolbar', Ext.apply({
                cls: 'oep-tools',
                width : this.gui.toolbar.width || width,
                items: tbar
            }, this.gui.toolbar));
        }
    },
    /**
     * Create right panel including
     * - Layers panel
     * - SearchParcel panel
     * @private
     */
    createRightPanel: function() {

        var rightPanelItems = [];
        // default position for rightPanel
        if (!this.gui.rightPanel.y) {this.gui.rightPanel.y = 20;}
        if (!this.gui.rightPanel.style) {this.gui.rightPanel.style = 'right: 20px';}

        if (this.gui.layers) {
	        // Checks whether the advanced or basic Layer control should be used
	        if (this.gui.layers && this.gui.layers.type === 'advanced') {
	            this.mapLayers = Ext.create('OpenEMap.view.layer.Advanced', Ext.apply({
	                mapPanel : this.mapPanel,
	                orginalConfig: this.orginalConfig,
	                client: this.client
	            }, this.gui.layers));
	        } else {
	            this.mapLayers = Ext.create('OpenEMap.view.layer.Basic', Ext.apply({
	                mapPanel : this.mapPanel,
	                client: this.client
	            }, this.gui.layers));
	        }

	        // If the layers panel not should be rendered to div, add it to the right panels items
	        if (!this.gui.layers.renderTo) {
	        	rightPanelItems.push(this.mapLayers);
	        }
	    }

        if (this.gui.searchFastighet)  {
	        // Create SearchParcel control
	        this.searchFastighet = Ext.create('OpenEMap.view.SearchFastighet', Ext.apply({
	            mapPanel : this.mapPanel,
	            basePath: this.config.basePath,
	            search: this.search
	        }, this.gui.searchFastighet));
            if (!this.gui.searchFastighet.renderTo) {
                rightPanelItems.push(this.searchFastighet);
            }
        }

        // Create right panel including both layrer control and searchParcel
        // create right panel containing layers and search panels if no renderTo target is configured
        if (rightPanelItems.length > 0) {
            this.rightPanel = Ext.create('Ext.panel.Panel', {
            	renderTo: this.gui.rightPanel.renderTo,
                y : this.gui.rightPanel.y,
                layout : {
                    type: 'vbox',
                    align : 'stretch'
                },
                width : 300,
                border: false,
                style : this.gui.rightPanel.style,
                bodyStyle: {
                    background: 'transparent'
                },
                items : rightPanelItems
	        });
	    }
	},

	/**
	 * Create base layers control
	 * @private
	 */
    createBaseLayersPanel: function() {
        // Create BaseLayers control
        if (!this.map.allOverlays && this.gui.baseLayers) {
            var layers = this.map.layers;
            var parser = Ext.create('OpenEMap.config.Parser');
            var baseLayers = parser.extractBaseLayers(layers);
	        // Only create if config has baselayers
        	if (baseLayers) {
        		if (!(this.gui.baseLayers.renderTo || this.gui.baseLayers.style)) {
    				this.gui.baseLayers.style = {
    					right: '20px',
    					bottom: '20px'
    				};
        		}
	            this.baseLayers = Ext.create("OpenEMap.view.BaseLayers", Ext.apply({
	                mapPanel : this.mapPanel,
	                renderTo : this.gui.baseLayers.renderTo
	            }, this.gui.baseLayers));
	        }
        }
	},

	/**
	 * Create ZoomTool panel
	 * @private
	 */
    createZoomToolPanel: function() {
        // Create ZoomTool control
        if (this.gui.zoomTools) {
    		if (!(this.gui.zoomTools.renderTo || this.gui.zoomTools.style)) {
				this.gui.zoomTools.style = {
					left: '20px',
					top: '76px'
				};
    		}
            this.zoomTools = Ext.create('OpenEMap.view.ZoomTools', Ext.apply({
                mapPanel : this.mapPanel,
                renderTo : this.gui.zoomTools.renderTo,
                width: 36
            }, this.gui.zoomTools));
        }
    },

	/**
	 * Create search coodinates panel
	 * @private
	 */
    createSearchCoordinatePanel: function() {
        // Create SearchCoordinate control
        // only create if renderTo
        if (this.gui.searchCoordinate && this.gui.searchCoordinate.renderTo) {
            this.searchCoordinate = Ext.create('OpenEMap.view.SearchCoordinate', Ext.apply({
                mapPanel : this.mapPanel
            }, this.gui.searchCoordinate));
        }
    },

	/**
	 * Create object config window
	 * always created inside map div
	 * @private
	 */
    createObjectConfigPanel: function() {
        // Create Object config
        if (this.gui.objectConfig) {
            this.objectConfig = Ext.create('OpenEMap.view.ObjectConfig', Ext.apply({
                mapPanel : this.mapPanel,
                gui: this
            }, this.gui.objectConfig));
            this.objectConfigWindow = Ext.create('Ext.window.Window', Ext.apply({
                title: this.objectConfigWindowTitle,
                width: 480,
                height: 300,
                layout: 'fit',
                closable: false,
                collapsible: true,
                items: this.objectConfig
            }, this.gui.objectConfig));
            this.objectConfigWindow.show();
        }
	},

	/**
	 * Create show coordinate panel
	 * @private
	 */
    createShowCoordinatePanel: function() {
        // Create Show Coordinate control
        // only create if renderTo
        if (this.gui.showCoordinate && this.gui.showCoordinate.renderTo) {
        	if (!this.cls) {
        		this.cls = 'oep-show-coordinate';
        	}
        	var cfg = {
                mapPanel : this.mapPanel,
                cls : this.cls,
			    setCoord: function(e) {
			    	var lonlat = this.getLonLatFromPixel(e.xy);
			    	var eC = parent.mapClient.gui.showCoordinate.getComponent('e');
			    	var nC = parent.mapClient.gui.showCoordinate.getComponent('n');
			    	eC.setValue(Math.round(lonlat.lon));
			    	nC.setValue(Math.round(lonlat.lat));
			    }
        	};
            this.showCoordinate = Ext.create('OpenEMap.view.ShowCoordinate', Ext.apply(cfg, this.gui.showCoordinate));

		    this.map.events.register("mousemove", this.map, this.showCoordinate.setCoord);
        }
	},

	/**
	 * Create scalebar panel
	 * @private
	 */
    createScalebarPanel: function() {
        // Create scalebar control
       	// Position defined in CSS - defaults to lower left corner of map
        if (this.gui.scalebar) {
            this.scalebar = Ext.create('OpenEMap.view.Scalebar', Ext.apply({
                mapPanel : this.mapPanel
            }, this.gui.scalebar));
        }
    }
});
<commit_msg>Fix GUI cleanup (#48)<commit_after>/*
    Copyright (C) 2014 Härnösands kommun

    This program 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.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * Initializes GUI from configuration
 * Initialize where to place the different GUI components, and if they should be floating components or not
 */
Ext.define('OpenEMap.Gui', {
    activeAction: null,
    requires: ['OpenEMap.action.DeleteAllFeatures',
               'OpenEMap.action.DeleteGeometry',
               'OpenEMap.action.DeleteMeasure',
               'OpenEMap.action.DetailReport',
               'OpenEMap.action.DrawGeometry',
               'OpenEMap.action.DrawObject',
               'OpenEMap.action.FullExtent',
               'OpenEMap.action.Identify',
               'OpenEMap.action.MeasureArea',
               'OpenEMap.action.MeasureLine',
               'OpenEMap.action.MetadataInfoColumn',
               'OpenEMap.action.ModifyGeometry',
               'OpenEMap.action.ModifyText',
               'OpenEMap.action.Popup',
               'OpenEMap.action.Print',
               'OpenEMap.action.SelectGeometry',
               'OpenEMap.view.BaseLayers',
               'OpenEMap.view.DetailReportResults',
               'OpenEMap.view.IdentifyResults',
               'OpenEMap.view.Map',
               'OpenEMap.view.ObjectConfig',
               'OpenEMap.view.SearchCoordinate',
               'OpenEMap.view.SearchFastighet',
               'OpenEMap.view.Scalebar',
               'OpenEMap.view.ShowCoordinate',
               'OpenEMap.view.ZoomTools',
               'OpenEMap.view.layer.Advanced',
               'OpenEMap.view.layer.Basic',
               'GeoExt.container.WmsLegend',
               'GeoExt.container.UrlLegend',
               'GeoExt.container.VectorLegend'],
    objectConfigWindowTitle: 'Object configuration',
    constructor : function(config) {
        this.config = config.config;
        this.gui = config.gui;
        this.map = config.map;
        this.orginalConfig = config.orginalConfig;
        this.serverStore = config.serverStore;
        this.search = config.config.search;
        this.client = config.client;

        // GUI defaults
        if (this.gui === undefined) {
            this.gui = {};
        }
        if (this.gui.map === undefined) {this.gui.map = false;}
        if (this.gui.rightPanel === undefined) {this.gui.rightPanel = {};}

        this.mapPanel = Ext.create('OpenEMap.view.Map', {
            map: this.map,
            extent: this.config.extent,
            config: this.config,
            listeners: {
                'afterrender': function() {
                    if (this.config.attribution) {
                        var el = this.mapPanel.getEl();
                        Ext.DomHelper.append(el, ''+this.config.attribution+'');
                    }
                },
                scope: this
            }
        });

        this.createToolbar();
        this.createZoomToolPanel();
        this.createObjectConfigPanel();
        this.createScalebarPanel();
        this.createShowCoordinatePanel();
        this.createSearchCoordinatePanel();
        this.createRightPanel();
        this.createBaseLayersPanel();

        var items = [];
        items.push(this.mapPanel);
        if (this.zoomTools && !this.gui.zoomTools.renderTo) items.push(this.zoomTools);
        if (this.objectConfig && !this.gui.objectConfig.renderTo) items.push(this.objectConfig);
        if (this.scalebar && !this.gui.scalebar.renderTo) items.push(this.scalebar);
        if (this.showCoordinate && !this.gui.showCoordinate.renderTo) items.push(this.showCoordinate);
        if (this.searchCoordinate && !this.gui.searchCoordinate.renderTo) items.push(this.searchCoordinate);
        if (this.rightPanel && !this.gui.rightPanel.renderTo) items.push(this.rightPanel);
        if (this.baseLayers && !this.gui.baseLayers.renderTo) items.push(this.baseLayers);
        if (this.toolbar && !this.gui.toolbar.renderTo) items.push(this.toolbar);

        // NOTE: Generic ES search as a floating centered field
        /*this.search = Ext.create('OpenEMap.form.Search', {
            mapPanel : this.mapPanel,
            width: 300,
            style: {
                right: '20px',
                bottom: '76px'
            }
        });
        items.push(this.search);*/

        // create map rendered to a target element or as viewport depending on config
        if (this.gui.map) {
            var element = this.gui.map.renderTo ? Ext.get(this.gui.map.renderTo) : undefined;
            this.container = Ext.create('Ext.container.Container', Ext.apply({
                layout : 'absolute',
                border: false,
                width: element ? element.getWidth() : undefined,
                height: element ? element.getHeight() : undefined,
                items : items
            }, this.gui.map));
        } else {
            this.container = Ext.create('Ext.container.Viewport', {
                layout : 'absolute',
                items : items
            });
        }
    },
    destroy: function() {
        if (this.mapPanel) this.mapPanel.destroy();
        if (this.zoomTools) this.zoomTools.destroy();
        if (this.mapLayers) this.mapLayers.destroy();
        if (this.searchFastighet) this.searchFastighet.destroy();
        if (this.searchCoordinate) this.searchCoordinate.destroy();
        if (this.showCoordinate) this.showCoordinate.destroy();
        if (this.toolbar) this.toolbar.destroy();
        if (this.rightPanel) this.rightPanel.destroy();
        if (this.baseLayers) this.baseLayers.destroy();
        if (this.objectConfig) this.objectConfig.destroy();
        if (this.objectConfigWindow) this.objectConfigWindow.destroy();
        if (this.scalebar) this.scalebar.destroy();
        if (this.container) this.container.destroy();
        //if (this.search) this.search.destroy();
    },
    onToggle: function(button, pressed) {
        var action = button.baseAction;

        if (!this.objectConfig) return;

        // NOTE: want the effect of unselecting all and hiding object dialog on detoggle, but that is triggered after toggle... so this will have to do
        if (pressed) {
            this.mapPanel.unselectAll();
            this.objectConfig.hide();
            this.activeAction = action;
        }

        action.toggle(pressed);
    },
	/**
	 * Create toolbar
     * @private
	 */
    createToolbar: function() {
        var basePath = this.config.basePath;
        var layers = this.config.layers;

        var createAction = function(type) {
            var cls;
            if((Ext.isObject(type) && Ext.Object.getSize(type) > 0) || (!Ext.isObject(type) && !Ext.isEmpty(type))) {
                if (type === this.config.tools[this.config.tools.length-1]) cls = 'oep-tools-last';

                var config = {
                    map: this.map,
                    mapPanel: this.mapPanel,
                    cls: cls
                };

                if (type.constructor === Object) {
                    Ext.apply(config, type);
                    type = config.type;
                    delete config.type;
                }

                if (type == 'ZoomSelector') {
                    return Ext.create('OpenEMap.form.ZoomSelector', {map: this.map});
                } else if (type == 'DrawObject') {
                     config.objectConfigView = this.objectConfig;
                } else if (type == 'Identify') {
                    config.basePath = basePath;
                    config.layers = layers;
                    config.client = this.client;
                } else if (type == 'Popup') {
                    config.layers = layers;
					if ((config.showOnlyFirstHit === undefined) || (config.showOnlyFirstHit === null)) {
						config.showOnlyFirstHit = true;
	                }
				}

                var action = Ext.create('OpenEMap.action.' + type, config);
                if (config.activate && action.control) {
                    this.controlToActivate = action.control;
                }
                var button = Ext.create('Ext.button.Button', action);
                button.on('toggle', this.onToggle, this);
                return button;
            }
        };

        if (!this.config.tools) {
            this.config.tools = [];
        }

        // TODO: need to apply cls: 'oep-tools-last' to last item...
        var tbar = this.config.tools.map(createAction, this);

        // calc width of toolbar
        var width = 6; // padding
        tbar.forEach(function(item) {
            if (item){
                if (!item.hideFromToolbar) {
	                if (item.constructor == String) {
	                    width += 1; // separator
	                } else if (item.width) {
	                    width += item.width;
	                } else {
	                    width += 24; // button
	                }
	                // add spacing to next control
	                width += 8;
                }
            }
        });
        width += 3; // padding

        // create toolbar as floating left panel if no renderTo target is configured
        if (this.gui.toolbar && !this.gui.toolbar.renderTo) {
            this.toolbar = Ext.create('Ext.toolbar.Toolbar', Ext.apply({
                cls: 'oep-tools',
                y : 20,
                x : 20,
                width: width,
                items: tbar
            }, this.gui.toolbar));
        } else if (this.gui.toolbar && this.gui.toolbar.renderTo) {
            this.toolbar = Ext.create('Ext.toolbar.Toolbar', Ext.apply({
                cls: 'oep-tools',
                width : this.gui.toolbar.width || width,
                items: tbar
            }, this.gui.toolbar));
        }
    },
    /**
     * Create right panel including
     * - Layers panel
     * - SearchParcel panel
     * @private
     */
    createRightPanel: function() {

        var rightPanelItems = [];
        // default position for rightPanel
        if (!this.gui.rightPanel.y) {this.gui.rightPanel.y = 20;}
        if (!this.gui.rightPanel.style) {this.gui.rightPanel.style = 'right: 20px';}

        if (this.gui.layers) {
	        // Checks whether the advanced or basic Layer control should be used
	        if (this.gui.layers && this.gui.layers.type === 'advanced') {
	            this.mapLayers = Ext.create('OpenEMap.view.layer.Advanced', Ext.apply({
	                mapPanel : this.mapPanel,
	                orginalConfig: this.orginalConfig,
	                client: this.client
	            }, this.gui.layers));
	        } else {
	            this.mapLayers = Ext.create('OpenEMap.view.layer.Basic', Ext.apply({
	                mapPanel : this.mapPanel,
	                client: this.client
	            }, this.gui.layers));
	        }

	        // If the layers panel not should be rendered to div, add it to the right panels items
	        if (!this.gui.layers.renderTo) {
	        	rightPanelItems.push(this.mapLayers);
	        }
	    }

        if (this.gui.searchFastighet)  {
	        // Create SearchParcel control
	        this.searchFastighet = Ext.create('OpenEMap.view.SearchFastighet', Ext.apply({
	            mapPanel : this.mapPanel,
	            basePath: this.config.basePath,
	            search: this.search
	        }, this.gui.searchFastighet));
            if (!this.gui.searchFastighet.renderTo) {
                rightPanelItems.push(this.searchFastighet);
            }
        }

        // Create right panel including both layrer control and searchParcel
        // create right panel containing layers and search panels if no renderTo target is configured
        if (rightPanelItems.length > 0) {
            this.rightPanel = Ext.create('Ext.panel.Panel', {
            	renderTo: this.gui.rightPanel.renderTo,
                y : this.gui.rightPanel.y,
                layout : {
                    type: 'vbox',
                    align : 'stretch'
                },
                width : 300,
                border: false,
                style : this.gui.rightPanel.style,
                bodyStyle: {
                    background: 'transparent'
                },
                items : rightPanelItems
	        });
	    }
	},

	/**
	 * Create base layers control
	 * @private
	 */
    createBaseLayersPanel: function() {
        // Create BaseLayers control
        if (!this.map.allOverlays && this.gui.baseLayers) {
            var layers = this.map.layers;
            var parser = Ext.create('OpenEMap.config.Parser');
            var baseLayers = parser.extractBaseLayers(layers);
	        // Only create if config has baselayers
        	if (baseLayers) {
        		if (!(this.gui.baseLayers.renderTo || this.gui.baseLayers.style)) {
    				this.gui.baseLayers.style = {
    					right: '20px',
    					bottom: '20px'
    				};
        		}
	            this.baseLayers = Ext.create("OpenEMap.view.BaseLayers", Ext.apply({
	                mapPanel : this.mapPanel,
	                renderTo : this.gui.baseLayers.renderTo
	            }, this.gui.baseLayers));
	        }
        }
	},

	/**
	 * Create ZoomTool panel
	 * @private
	 */
    createZoomToolPanel: function() {
        // Create ZoomTool control
        if (this.gui.zoomTools) {
    		if (!(this.gui.zoomTools.renderTo || this.gui.zoomTools.style)) {
				this.gui.zoomTools.style = {
					left: '20px',
					top: '76px'
				};
    		}
            this.zoomTools = Ext.create('OpenEMap.view.ZoomTools', Ext.apply({
                mapPanel : this.mapPanel,
                renderTo : this.gui.zoomTools.renderTo,
                width: 36
            }, this.gui.zoomTools));
        }
    },

	/**
	 * Create search coodinates panel
	 * @private
	 */
    createSearchCoordinatePanel: function() {
        // Create SearchCoordinate control
        // only create if renderTo
        if (this.gui.searchCoordinate && this.gui.searchCoordinate.renderTo) {
            this.searchCoordinate = Ext.create('OpenEMap.view.SearchCoordinate', Ext.apply({
                mapPanel : this.mapPanel
            }, this.gui.searchCoordinate));
        }
    },

	/**
	 * Create object config window
	 * always created inside map div
	 * @private
	 */
    createObjectConfigPanel: function() {
        // Create Object config
        if (this.gui.objectConfig) {
            this.objectConfig = Ext.create('OpenEMap.view.ObjectConfig', Ext.apply({
                mapPanel : this.mapPanel,
                gui: this
            }, this.gui.objectConfig));
            this.objectConfigWindow = Ext.create('Ext.window.Window', Ext.apply({
                title: this.objectConfigWindowTitle,
                width: 480,
                height: 300,
                layout: 'fit',
                closable: false,
                collapsible: true,
                items: this.objectConfig
            }, this.gui.objectConfig));
            this.objectConfigWindow.show();
        }
	},

	/**
	 * Create show coordinate panel
	 * @private
	 */
    createShowCoordinatePanel: function() {
        // Create Show Coordinate control
        // only create if renderTo
        if (this.gui.showCoordinate && this.gui.showCoordinate.renderTo) {
        	if (!this.cls) {
        		this.cls = 'oep-show-coordinate';
        	}
        	var cfg = {
                mapPanel : this.mapPanel,
                cls : this.cls,
			    setCoord: function(e) {
			    	var lonlat = this.getLonLatFromPixel(e.xy);
			    	var eC = parent.mapClient.gui.showCoordinate.getComponent('e');
			    	var nC = parent.mapClient.gui.showCoordinate.getComponent('n');
			    	eC.setValue(Math.round(lonlat.lon));
			    	nC.setValue(Math.round(lonlat.lat));
			    }
        	};
            this.showCoordinate = Ext.create('OpenEMap.view.ShowCoordinate', Ext.apply(cfg, this.gui.showCoordinate));

		    this.map.events.register("mousemove", this.map, this.showCoordinate.setCoord);
        }
	},

	/**
	 * Create scalebar panel
	 * @private
	 */
    createScalebarPanel: function() {
        // Create scalebar control
       	// Position defined in CSS - defaults to lower left corner of map
        if (this.gui.scalebar) {
            this.scalebar = Ext.create('OpenEMap.view.Scalebar', Ext.apply({
                mapPanel : this.mapPanel
            }, this.gui.scalebar));
        }
    }
});
<|endoftext|>


<commit_before>;(function($B){

var _b_ = $B.builtins
var $s=[]
for(var $b in _b_) $s.push('var ' + $b +'=_b_["'+$b+'"]')
eval($s.join(';'))

// set

var $SetDict = {
    __class__:$B.$type,
    __name__:'set',
    $native:true
}

$SetDict.__add__ = function(self,other){
    return set(self.$items.concat(other.$items))
}

$SetDict.__and__ = function(self,other){
    var res = set()
    for(var i=0, len = self.$items.length; i < len;i++){
        if(getattr(other,'__contains__')(self.$items[i])){
            $SetDict.add(res,self.$items[i])
        }
    }
    return res
}

$SetDict.__contains__ = function(self,item){
    if(self.$num && (typeof item=='number')){return self.$items.indexOf(item)>-1}
    if(self.$str && (typeof item=='string')){return self.$items.indexOf(item)>-1}
    for(var i=0, len = self.$items.length; i < len;i++){
        try{if(getattr(self.$items[i],'__eq__')(item)) return true
        }catch(err){void(0)}
    }
    return false
}

$SetDict.__eq__ = function(self,other){
    // compare class set
    if(other===undefined) return self===set

    if(isinstance(other,set)){
      if(other.$items.length==self.$items.length){
        for(var i=0, len = self.$items.length; i < len;i++){
           if($SetDict.__contains__(self,other.$items[i])===false) return false
        }
        return true
      }
    }
    return false
}

$SetDict.__ge__ = function(self,other){return !$SetDict.__lt__(self,other)}

// special method to speed up "for" loops
$SetDict.__getitems__ = function(self){return self.$items}

$SetDict.__gt__ = function(self,other){return !$SetDict.__le__(self,other)}

$SetDict.__hash__ = function(self) {throw _b_.TypeError("unhashable type: 'set'");}

$SetDict.__init__ = function(self){
    var args = []
    for(var i=1, len = arguments.length; i < len;i++){args.push(arguments[i])}
    self.$items = []
    if(args.length==0) return
    if(args.length==1){    // must be an iterable
        var arg=args[0]
        if(isinstance(arg,set)){
            self.$items = arg.$items
            return
        }
        try{
            var iterable = iter(arg)
            var obj = {$items:[],$str:true,$num:true}
            while(1){
                try{$SetDict.add(obj,next(iterable))}
                catch(err){
                    if(err.__name__=='StopIteration'){$B.$pop_exc();break}
                    throw err
                }
            }
            self.$items = obj.$items
            //console.log('set init, str '+obj.$str+' num '+obj.$num)
        }catch(err){
            console.log(''+err)
            throw _b_.TypeError("'"+arg.__class__.__name__+"' object is not iterable")
        }
    } else {
        throw _b_.TypeError("set expected at most 1 argument, got "+args.length)
    }
}

var $set_iterator = $B.$iterator_class('set iterator')
$SetDict.__iter__ = function(self){
    return $B.$iterator(self.$items,$set_iterator)
}

$SetDict.__le__ = function(self,other){
    var cfunc = getattr(other,'__contains__')
    for(var i=0, len = self.$items.length; i < len;i++){
        if(!cfunc(self.$items[i])) return false
    }
    return true
}

$SetDict.__len__ = function(self){return self.$items.length}

$SetDict.__lt__ = function(self,other){
    return $SetDict.__le__(self,other)&&$SetDict.__len__(self)<getattr(other,'__len__')()
}

$SetDict.__mro__ = [$SetDict,_b_.object.$dict]

$SetDict.__ne__ = function(self,other){return !$SetDict.__eq__(self,other)}

$SetDict.__or__ = function(self,other){
    var res = $SetDict.copy(self)
    for(var i=0, len = other.$items.length; i < len;i++) $SetDict.add(res,other.$items[i])
    return res
}

$SetDict.__str__ = $SetDict.toString = $SetDict.__repr__ = function(self){
    if(self===undefined) return "<class 'set'>"
    var head='',tail=''
    frozen = self.$real === 'frozen'
    if(self.$items.length===0){
        if(frozen) return 'frozenset()'
        return 'set()'
    }
    if(self.__class__===$SetDict && frozen){
        head = 'frozenset('
        tail = ')'
    }else if(self.__class__!==$SetDict){ // subclasses
        head = self.__class__.__name__+'('
        tail = ')'
    }
    var res = "{"
    for(var i=0, len = self.$items.length; i < len;i++){
        res += repr(self.$items[i])
        if(i<self.$items.length-1){res += ','}
    }
    res += '}'
    return head+res+tail
}

$SetDict.__sub__ = function(self,other){
    // Return a new set with elements in the set that are not in the others
    var res = set()
    var cfunc = getattr(other,'__contains__')
    for(var i=0, len = self.$items.length; i < len;i++){
        if(!cfunc(self.$items[i])){
            res.$items.push(self.$items[i])
        }
    }
    return res
}

$SetDict.__xor__ = function(self,other){
    // Return a new set with elements in either the set or other but not both
    var res = set()
    var cfunc = getattr(other,'__contains__')
    for(var i=0, len = self.$items.length; i < len;i++){
        if(!cfunc(self.$items[i])){
            $SetDict.add(res,self.$items[i])
        }
    }
    for(var i=0, len = other.$items.length; i < len;i++){
        if(!$SetDict.__contains__(self,other.$items[i])){
            $SetDict.add(res,other.$items[i])
        }
    }
    return res
}

// add "reflected" methods
$B.make_rmethods($SetDict)

$SetDict.add = function(self,item){
    if(self.$str && !(typeof item=='string')){self.$str=false}
    if(self.$num && !(typeof item=='number')){self.$num=false}
    if(self.$num||self.$str){
        if(self.$items.indexOf(item)==-1){self.$items.push(item)}
        return
    }
    var cfunc = getattr(item,'__eq__')
    for(var i=0, len = self.$items.length; i < len;i++){
        try{if(cfunc(self.$items[i])) return}
        catch(err){void(0)} // if equality test throws exception
    }
    self.$items.push(item)
}

$SetDict.clear = function(self){self.$items = []}

$SetDict.copy = function(self){
    var res = set() // copy returns an instance of set, even for subclasses
    for(var i=0, len = self.$items.length; i < len;i++) res.$items[i]=self.$items[i]
    return res
}

$SetDict.discard = function(self,item){
    try{$SetDict.remove(self,item)}
    catch(err){if(err.__name__!=='KeyError'){throw err}}
}

$SetDict.isdisjoint = function(self,other){
    for(var i=0, len = self.$items.length; i < len;i++){
        if(getattr(other,'__contains__')(self.$items[i])) return false
    }
    return true
}

$SetDict.pop = function(self){
    if(self.$items.length===0) throw _b_.KeyError('pop from an empty set')
    return self.$items.pop()
}

$SetDict.remove = function(self,item){
    for(var i=0, len = self.$items.length; i < len;i++){
        if(getattr(self.$items[i],'__eq__')(item)){
            self.$items.splice(i,1)
            return _b_.None
        }
    }
    throw _b_.KeyError(item)
}

$SetDict.update = function(self,other){
    if (other === undefined || other.$items === undefined) return

    for(var i=0, len = other.$items.length; i < len; i++) {
        $SetDict.add(self,other.$items[i])
    }
}

$SetDict.symmetric_difference = $SetDict.__xor__
$SetDict.difference = $SetDict.__sub__
$SetDict.intersection = $SetDict.__and__
$SetDict.issubset = $SetDict.__le__
$SetDict.issuperset = $SetDict.__ge__
$SetDict.union = $SetDict.__or__

function set(){
    // Instances of set have attributes $str and $num
    // $str is true if all the elements in the set are string, $num if
    // all the elements are integers
    // They are used to speed up operations on sets
    var res = {__class__:$SetDict,$str:true,$num:true}
    // apply __init__ with arguments of set()
    var args = [res]
    for(var i=0, len = arguments.length; i < len;i++){args.push(arguments[i])}
    $SetDict.__init__.apply(null,args)
    return res
}
set.__class__ = $B.$factory
set.$dict = $SetDict
$SetDict.$factory = set
$SetDict.__new__ = $B.$__new__(set)

var $FrozensetDict = {__class__:$B.$type,__name__:'frozenset'}

$FrozensetDict.__mro__ = [$FrozensetDict,object.$dict]

$FrozensetDict.__str__=$FrozensetDict.toString=$FrozensetDict.__repr__ = function(self){
    if(self===undefined) return "<class 'frozenset'>"
    if(self.$items.length===0) return 'frozenset()'
    var res = "{"
    for(var i=0, len = self.$items.length; i < len;i++){
        res += repr(self.$items[i])
        if(i<self.$items.length-1){res += ','}
    }
    res += '}'
    return 'frozenset('+res+')'
}

for(var attr in $SetDict){
    switch(attr) {
      case 'add':
      case 'clear':
      case 'discard':
      case 'pop':
      case 'remove':
      case 'update':
        break
      default:
        if($FrozensetDict[attr] ==undefined) $FrozensetDict[attr] = $SetDict[attr]
    }
}

// hash is allowed on frozensets
$FrozensetDict.__hash__ = function(self) {
   //taken from python repo /Objects/setobject.c

   if (self.__hashvalue__ !== undefined) return self.__hashvalue__

   var _hash=1927868237
   _hash *=self.$items.length

   for (var i=0, len = self.$items.length; i < len; i++) {
      var _h=hash(self.$items[i])
      _hash ^= ((_h ^ 89869747) ^ (_h << 16)) * 3644798167
   }

   _hash *= 69069 + 907133923

   if (_hash == -1) _hash = 590923713

   return self.__hashvalue__ = _hash
}

function frozenset(){
    var res = set.apply(null,arguments)
    res.__class__ = $FrozensetDict
    return res
}
frozenset.__class__ = $B.$factory
frozenset.$dict = $FrozensetDict
$FrozensetDict.__new__ = $B.$__new__(frozenset)
$FrozensetDict.$factory = frozenset

_b_.set = set
_b_.frozenset = frozenset

})(__BRYTHON__)
<commit_msg>modifications to cache for loops to improve performance, see http://jsperf.com/js-for-loops-cached-vs-basic<commit_after>;(function($B){

var _b_ = $B.builtins
var $s=[]
for(var $b in _b_) $s.push('var ' + $b +'=_b_["'+$b+'"]')
eval($s.join(';'))

// set

var $SetDict = {
    __class__:$B.$type,
    __name__:'set',
    $native:true
}

$SetDict.__add__ = function(self,other){
    return set(self.$items.concat(other.$items))
}

$SetDict.__and__ = function(self,other){
    var res = set()
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        if(getattr(other,'__contains__')(self.$items[i])){
            $SetDict.add(res,self.$items[i])
        }
    }
    return res
}

$SetDict.__contains__ = function(self,item){
    if(self.$num && (typeof item=='number')){return self.$items.indexOf(item)>-1}
    if(self.$str && (typeof item=='string')){return self.$items.indexOf(item)>-1}
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        try{if(getattr(self.$items[i],'__eq__')(item)) return true
        }catch(err){void(0)}
    }
    return false
}

$SetDict.__eq__ = function(self,other){
    // compare class set
    if(other===undefined) return self===set

    if(isinstance(other,set)){
      if(other.$items.length==self.$items.length){
        for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
           if($SetDict.__contains__(self,other.$items[i])===false) return false
        }
        return true
      }
    }
    return false
}

$SetDict.__ge__ = function(self,other){return !$SetDict.__lt__(self,other)}

// special method to speed up "for" loops
$SetDict.__getitems__ = function(self){return self.$items}

$SetDict.__gt__ = function(self,other){return !$SetDict.__le__(self,other)}

$SetDict.__hash__ = function(self) {throw _b_.TypeError("unhashable type: 'set'");}

$SetDict.__init__ = function(self){
    var args = []
    for(var i=1, _len_i = arguments.length; i < _len_i;i++){args.push(arguments[i])}
    self.$items = []
    if(args.length==0) return
    if(args.length==1){    // must be an iterable
        var arg=args[0]
        if(isinstance(arg,set)){
            self.$items = arg.$items
            return
        }
        try{
            var iterable = iter(arg)
            var obj = {$items:[],$str:true,$num:true}
            while(1){
                try{$SetDict.add(obj,next(iterable))}
                catch(err){
                    if(err.__name__=='StopIteration'){$B.$pop_exc();break}
                    throw err
                }
            }
            self.$items = obj.$items
            //console.log('set init, str '+obj.$str+' num '+obj.$num)
        }catch(err){
            console.log(''+err)
            throw _b_.TypeError("'"+arg.__class__.__name__+"' object is not iterable")
        }
    } else {
        throw _b_.TypeError("set expected at most 1 argument, got "+args.length)
    }
}

var $set_iterator = $B.$iterator_class('set iterator')
$SetDict.__iter__ = function(self){
    return $B.$iterator(self.$items,$set_iterator)
}

$SetDict.__le__ = function(self,other){
    var cfunc = getattr(other,'__contains__')
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        if(!cfunc(self.$items[i])) return false
    }
    return true
}

$SetDict.__len__ = function(self){return self.$items.length}

$SetDict.__lt__ = function(self,other){
    return $SetDict.__le__(self,other)&&$SetDict.__len__(self)<getattr(other,'__len__')()
}

$SetDict.__mro__ = [$SetDict,_b_.object.$dict]

$SetDict.__ne__ = function(self,other){return !$SetDict.__eq__(self,other)}

$SetDict.__or__ = function(self,other){
    var res = $SetDict.copy(self)
    for(var i=0, _len_i = other.$items.length; i < _len_i;i++) $SetDict.add(res,other.$items[i])
    return res
}

$SetDict.__str__ = $SetDict.toString = $SetDict.__repr__ = function(self){
    if(self===undefined) return "<class 'set'>"
    var head='',tail=''
    frozen = self.$real === 'frozen'
    if(self.$items.length===0){
        if(frozen) return 'frozenset()'
        return 'set()'
    }
    if(self.__class__===$SetDict && frozen){
        head = 'frozenset('
        tail = ')'
    }else if(self.__class__!==$SetDict){ // subclasses
        head = self.__class__.__name__+'('
        tail = ')'
    }
    var res = "{"
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        res += repr(self.$items[i])
        if(i<self.$items.length-1){res += ','}
    }
    res += '}'
    return head+res+tail
}

$SetDict.__sub__ = function(self,other){
    // Return a new set with elements in the set that are not in the others
    var res = set()
    var cfunc = getattr(other,'__contains__')
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        if(!cfunc(self.$items[i])){
            res.$items.push(self.$items[i])
        }
    }
    return res
}

$SetDict.__xor__ = function(self,other){
    // Return a new set with elements in either the set or other but not both
    var res = set()
    var cfunc = getattr(other,'__contains__')
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        if(!cfunc(self.$items[i])){
            $SetDict.add(res,self.$items[i])
        }
    }
    for(var i=0, _len_i = other.$items.length; i < _len_i;i++){
        if(!$SetDict.__contains__(self,other.$items[i])){
            $SetDict.add(res,other.$items[i])
        }
    }
    return res
}

// add "reflected" methods
$B.make_rmethods($SetDict)

$SetDict.add = function(self,item){
    if(self.$str && !(typeof item=='string')){self.$str=false}
    if(self.$num && !(typeof item=='number')){self.$num=false}
    if(self.$num||self.$str){
        if(self.$items.indexOf(item)==-1){self.$items.push(item)}
        return
    }
    var cfunc = getattr(item,'__eq__')
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        try{if(cfunc(self.$items[i])) return}
        catch(err){void(0)} // if equality test throws exception
    }
    self.$items.push(item)
}

$SetDict.clear = function(self){self.$items = []}

$SetDict.copy = function(self){
    var res = set() // copy returns an instance of set, even for subclasses
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++) res.$items[i]=self.$items[i]
    return res
}

$SetDict.discard = function(self,item){
    try{$SetDict.remove(self,item)}
    catch(err){if(err.__name__!=='KeyError'){throw err}}
}

$SetDict.isdisjoint = function(self,other){
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        if(getattr(other,'__contains__')(self.$items[i])) return false
    }
    return true
}

$SetDict.pop = function(self){
    if(self.$items.length===0) throw _b_.KeyError('pop from an empty set')
    return self.$items.pop()
}

$SetDict.remove = function(self,item){
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        if(getattr(self.$items[i],'__eq__')(item)){
            self.$items.splice(i,1)
            return _b_.None
        }
    }
    throw _b_.KeyError(item)
}

$SetDict.update = function(self,other){
    if (other === undefined || other.$items === undefined) return

    for(var i=0, _len_i = other.$items.length; i < _len_i; i++) {
        $SetDict.add(self,other.$items[i])
    }
}

$SetDict.symmetric_difference = $SetDict.__xor__
$SetDict.difference = $SetDict.__sub__
$SetDict.intersection = $SetDict.__and__
$SetDict.issubset = $SetDict.__le__
$SetDict.issuperset = $SetDict.__ge__
$SetDict.union = $SetDict.__or__

function set(){
    // Instances of set have attributes $str and $num
    // $str is true if all the elements in the set are string, $num if
    // all the elements are integers
    // They are used to speed up operations on sets
    var res = {__class__:$SetDict,$str:true,$num:true}
    // apply __init__ with arguments of set()
    var args = [res]
    for(var i=0, _len_i = arguments.length; i < _len_i;i++){args.push(arguments[i])}
    $SetDict.__init__.apply(null,args)
    return res
}
set.__class__ = $B.$factory
set.$dict = $SetDict
$SetDict.$factory = set
$SetDict.__new__ = $B.$__new__(set)

var $FrozensetDict = {__class__:$B.$type,__name__:'frozenset'}

$FrozensetDict.__mro__ = [$FrozensetDict,object.$dict]

$FrozensetDict.__str__=$FrozensetDict.toString=$FrozensetDict.__repr__ = function(self){
    if(self===undefined) return "<class 'frozenset'>"
    if(self.$items.length===0) return 'frozenset()'
    var res = "{"
    for(var i=0, _len_i = self.$items.length; i < _len_i;i++){
        res += repr(self.$items[i])
        if(i<self.$items.length-1){res += ','}
    }
    res += '}'
    return 'frozenset('+res+')'
}

for(var attr in $SetDict){
    switch(attr) {
      case 'add':
      case 'clear':
      case 'discard':
      case 'pop':
      case 'remove':
      case 'update':
        break
      default:
        if($FrozensetDict[attr] ==undefined) $FrozensetDict[attr] = $SetDict[attr]
    }
}

// hash is allowed on frozensets
$FrozensetDict.__hash__ = function(self) {
   //taken from python repo /Objects/setobject.c

   if (self.__hashvalue__ !== undefined) return self.__hashvalue__

   var _hash=1927868237
   _hash *=self.$items.length

   for (var i=0, _len_i = self.$items.length; i < _len_i; i++) {
      var _h=hash(self.$items[i])
      _hash ^= ((_h ^ 89869747) ^ (_h << 16)) * 3644798167
   }

   _hash *= 69069 + 907133923

   if (_hash == -1) _hash = 590923713

   return self.__hashvalue__ = _hash
}

function frozenset(){
    var res = set.apply(null,arguments)
    res.__class__ = $FrozensetDict
    return res
}
frozenset.__class__ = $B.$factory
frozenset.$dict = $FrozensetDict
$FrozensetDict.__new__ = $B.$__new__(frozenset)
$FrozensetDict.$factory = frozenset

_b_.set = set
_b_.frozenset = frozenset

})(__BRYTHON__)
<|endoftext|>


<commit_before>const ignore = 0;

module.exports = {
  overrides: [
    {
      files: '*/template/**',
      env: {
        browser: true,
      },
      rules: {
        'react/no-this-in-sfc': ignore,
        'import/no-unresolved': ignore,
        'import/no-extraneous-dependencies': ignore,
        'global-require': ignore,
        'react/react-in-jsx-scope': ignore,
      },
    },
    {
      files: 'REACT_NATIVE/template/**',
      env: {
        browser: false,
      },
    },
  ],
};
<commit_msg>New template directory pattern<commit_after>const ignore = 0;

module.exports = {
  overrides: [
    {
      files: '*/template[-?]*/**',
      env: {
        browser: true,
      },
      rules: {
        'react/no-this-in-sfc': ignore,
        'import/no-unresolved': ignore,
        'import/no-extraneous-dependencies': ignore,
        'global-require': ignore,
        'react/react-in-jsx-scope': ignore,
      },
    },
    {
      files: 'REACT_NATIVE/template/**',
      env: {
        browser: false,
      },
    },
  ],
};
<|endoftext|>


<commit_before>var request = require('request');
var url     = require('url');

function Bitcoind(href, opts) {
  this.opts = opts || {};
  this.url = url.parse(href);
  if(!url.port)
    url.port = 8332;
};

Bitcoind.prototype.rpc = function(method, params, callback) {
  this.request({jsonrpc: '2.0', method: method, params: params}, callback);
};

Bitcoind.prototype.batch = function(cmds, callback) {
  var payload = [];
  for(var i=0;i<cmds.length;i++)
    payload.push({jsonrpc: '2.0', method: cmds[i].method, params: cmds[i].params, id: i});
  this.request(payload, callback);
};

Bitcoind.prototype.request = function(payload, callback) {
  request({uri: this.url.href, method: 'POST', json: payload}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      if(body.result)
        callback(undefined, body.result);
      else
        callback(undefined, body);
      return;
    }

    if(error) {
      if(error.message == 'connect ECONNREFUSED') {
        console.log('bitcoind error: connection refused');
        callback({message: "Could not connect to the bitcoin server"});
      }

      console.log('bitcoind error: unrecognized: '+JSON.stringify(error));
      callback({message: 'Received an unrecognized error from the bitcoin server'});
      return;
    }

    if(response.statusCode == 401) {
      console.log('bitcoind error 401: invalid auth (check your user/pass)');
      callback({message: "Invalid auth"});
    } else {
      console.log('bitcoind error '+response.statusCode+': '+JSON.stringify(body.error));
      callback({message: 'Received an unrecognized error from the bitcoin server'});
    }
  });
};

module.exports = Bitcoind;<commit_msg>better return from connection refused<commit_after>var request = require('request');
var url     = require('url');

function Bitcoind(href, opts) {
  this.opts = opts || {};
  this.url = url.parse(href);
  if(!url.port)
    url.port = 8332;
};

Bitcoind.prototype.rpc = function(method, params, callback) {
  this.request({jsonrpc: '2.0', method: method, params: params}, callback);
};

Bitcoind.prototype.batch = function(cmds, callback) {
  var payload = [];
  for(var i=0;i<cmds.length;i++)
    payload.push({jsonrpc: '2.0', method: cmds[i].method, params: cmds[i].params, id: i});
  this.request(payload, callback);
};

Bitcoind.prototype.request = function(payload, callback) {
  request({uri: this.url.href, method: 'POST', json: payload}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      if(body.result)
        callback(undefined, body.result);
      else
        callback(undefined, body);
      return;
    }

    if(error) {
      if(error.message == 'connect ECONNREFUSED') {
        console.log('bitcoind error: connection refused');
        callback({message: "Could not connect to the bitcoin server"});
        return;
      }

      console.log('bitcoind error: unrecognized: '+JSON.stringify(error));
      callback({message: 'Received an unrecognized error from the bitcoin server'});
      return;
    }

    if(response.statusCode == 401) {
      console.log('bitcoind error 401: invalid auth (check your user/pass)');
      callback({message: "Invalid auth"});
    } else {
      console.log('bitcoind error '+response.statusCode+': '+JSON.stringify(body.error));
      callback({message: 'Received an unrecognized error from the bitcoin server'});
    }
  });
};

module.exports = Bitcoind;<|endoftext|>


<commit_before>//----------------------------------------------------------------------
// AdalJS v1.0.8
// @preserve Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//----------------------------------------------------------------------
// NOTICE: the code in this file originally developed by Microsoft
// source: https://github.com/AzureAD/azure-activedirectory-library-for-js/blob/master/lib/adal.js#L1029
// original license: https://github.com/AzureAD/azure-activedirectory-library-for-js/blob/master/LICENSE.txt

export default function random() {
    var guidHolder = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx';
    var hex = '0123456789abcdef';
    var r = 0;
    var guidResponse = "";
    for (var i = 0; i < guidHolder.length; i++) {
        if (guidHolder[i] !== '-' && guidHolder[i] !== '4') {
            // each x and y needs to be random
            r = Math.random() * 16 | 0;
        }

        if (guidHolder[i] === 'x') {
            guidResponse += hex[r];
        } else if (guidHolder[i] === 'y') {
            // clock-seq-and-reserved first hex is filtered and remaining hex values are random
            r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0??
            r |= 0x8; // set pos 3 to 1 as 1???
            guidResponse += hex[r];
        } else {
            guidResponse += guidHolder[i];
        }
    }
    return guidResponse;
}<commit_msg>remove link to license<commit_after>//----------------------------------------------------------------------
// AdalJS v1.0.8
// @preserve Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//----------------------------------------------------------------------
// NOTICE: the code in this file originally developed by Microsoft
// original source: https://github.com/AzureAD/azure-activedirectory-library-for-js/blob/master/lib/adal.js#L1029

export default function random() {
    var guidHolder = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx';
    var hex = '0123456789abcdef';
    var r = 0;
    var guidResponse = "";
    for (var i = 0; i < guidHolder.length; i++) {
        if (guidHolder[i] !== '-' && guidHolder[i] !== '4') {
            // each x and y needs to be random
            r = Math.random() * 16 | 0;
        }

        if (guidHolder[i] === 'x') {
            guidResponse += hex[r];
        } else if (guidHolder[i] === 'y') {
            // clock-seq-and-reserved first hex is filtered and remaining hex values are random
            r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0??
            r |= 0x8; // set pos 3 to 1 as 1???
            guidResponse += hex[r];
        } else {
            guidResponse += guidHolder[i];
        }
    }
    return guidResponse;
}<|endoftext|>


<commit_before>const rethink = require('rethinkdb');
const config = require('config');

const TABLE_NAME = 'jenkins_metrics';
const INDEX_NAME = 'jobName';
const DATABASE_NAME = config.get('database.name');
const EXECUTION_RESULTS_EARLIEST_LIMIT = 'statistics.executionResults.earliestBatchLimitPercent';
const EXECUTION_RESULTS_LATEST_LIMIT = 'statistics.executionResults.latestBatchLimitPercent';
const EXECUTION_TIMES_EARLIEST_LIMIT = 'statistics.executionTimes.earliestBatchLimitPercent';
const EXECUTION_TIMES_LATEST_LIMIT = 'statistics.executionTimes.latestBatchLimitPercent';
const DEFAULT_LIMIT_PERCENT = 10;

function getJobs(conn) {
  return getTable()
    .distinct({ index: INDEX_NAME })
    .run(conn)
    .then((cursor) => cursor.toArray());
}

function getBuilds(conn, jobName) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .orderBy(rethink.desc('id'))
    .run(conn);
}

function getExecutionTimes(conn, jobName) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .filter(rethink.row('result').eq('SUCCESS')
      .or(rethink.row('result').eq('UNSTABLE')))
    .orderBy('timestamp')
    .pluck('timestamp', 'duration', 'result')
    .run(conn);
}

function getLatestExecutionTimes(conn, jobName) {
  const percent = config.has(EXECUTION_TIMES_LATEST_LIMIT)
    ? config.get(EXECUTION_TIMES_LATEST_LIMIT)
    : DEFAULT_LIMIT_PERCENT;
  return getLimitedExecutionTimes(conn, jobName, percent, rethink.asc('timestamp'));
}

function getEarliestExecutionTimes(conn, jobName) {
  const percent = config.has(EXECUTION_TIMES_EARLIEST_LIMIT)
    ? config.get(EXECUTION_TIMES_EARLIEST_LIMIT)
    : DEFAULT_LIMIT_PERCENT;
  return getLimitedExecutionTimes(conn, jobName, percent, rethink.desc('timestamp'));
}

function getExecutionResults(conn, jobName) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .pluck('result')
    .group('result')
    .count()
    .run(conn);
}

function getLatestExecutionResults(conn, jobName) {
  const percent = config.has(EXECUTION_RESULTS_LATEST_LIMIT)
    ? config.get(EXECUTION_RESULTS_LATEST_LIMIT)
    : DEFAULT_LIMIT_PERCENT;
  return getLimitedExecutionResults(conn, jobName, percent, rethink.asc('timestamp'));
}

function getEarliestExecutionResults(conn, jobName) {
  const percent = config.has(EXECUTION_RESULTS_EARLIEST_LIMIT)
    ? config.get(EXECUTION_RESULTS_EARLIEST_LIMIT)
    : DEFAULT_LIMIT_PERCENT;
  return getLimitedExecutionResults(conn, jobName, percent, rethink.desc('timestamp'));
}

function getLimitedExecutionResults(conn, jobName, percent, order) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .orderBy(order)
    .limit(percentBasedLimit(jobName, percent))
    .pluck('result')
    .group('result')
    .count()
    .run(conn);
}

function getLimitedExecutionTimes(conn, jobName, percent, order) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .filter(rethink.row('result').eq('SUCCESS')
      .or(rethink.row('result').eq('UNSTABLE')))
    .orderBy(order)
    .limit(percentBasedLimit(jobName, percent))
    .orderBy('timestamp')
    .pluck('timestamp', 'duration', 'result')
    .run(conn);}

function percentBasedLimit(jobName, percent) {
  return getTable().getAll(jobName, { index: INDEX_NAME })
    .count()
    .mul(percent)
    .div(100)
    .ceil();
}

function getTable() {
  return getDb().table(TABLE_NAME);
}

function getDb() {
  return rethink.db(DATABASE_NAME);
}

module.exports = {
  getJobs,
  getBuilds,
  getExecutionTimes,
  getLatestExecutionTimes,
  getEarliestExecutionTimes,
  getExecutionResults,
  getLatestExecutionResults,
  getEarliestExecutionResults
};
<commit_msg>query for test results<commit_after>const rethink = require('rethinkdb');
const config = require('config');

const TABLE_NAME = 'jenkins_metrics';
const INDEX_NAME = 'jobName';
const DATABASE_NAME = config.get('database.name');
const EXECUTION_RESULTS_EARLIEST_LIMIT = 'statistics.executionResults.earliestBatchLimitPercent';
const EXECUTION_RESULTS_LATEST_LIMIT = 'statistics.executionResults.latestBatchLimitPercent';
const EXECUTION_TIMES_EARLIEST_LIMIT = 'statistics.executionTimes.earliestBatchLimitPercent';
const EXECUTION_TIMES_LATEST_LIMIT = 'statistics.executionTimes.latestBatchLimitPercent';
const DEFAULT_LIMIT_PERCENT = 10;

function getJobs(conn) {
  return getTable()
    .distinct({ index: INDEX_NAME })
    .run(conn)
    .then((cursor) => cursor.toArray());
}

function getBuilds(conn, jobName) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .orderBy(rethink.desc('id'))
    .run(conn);
}

function getExecutionTimes(conn, jobName) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .filter(rethink.row('result').eq('SUCCESS')
      .or(rethink.row('result').eq('UNSTABLE')))
    .orderBy('timestamp')
    .pluck('timestamp', 'duration', 'result')
    .run(conn);
}

function getExecutionResults(conn, jobName) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .pluck('result')
    .group('result')
    .count()
    .run(conn);
}

function getTestResults(conn, jobName) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .pluck('actions', 'timestamp')
    .map(toMergedTestResults)
    .without('actions')
    .map(toCalculatedSuccessfulTests)
    .orderBy('timestamp')
    .run(conn);
}

function getLatestExecutionTimes(conn, jobName) {
  const percent = config.has(EXECUTION_TIMES_LATEST_LIMIT)
    ? config.get(EXECUTION_TIMES_LATEST_LIMIT)
    : DEFAULT_LIMIT_PERCENT;
  return getLimitedExecutionTimes(conn, jobName, percent, rethink.asc('timestamp'));
}

function getEarliestExecutionTimes(conn, jobName) {
  const percent = config.has(EXECUTION_TIMES_EARLIEST_LIMIT)
    ? config.get(EXECUTION_TIMES_EARLIEST_LIMIT)
    : DEFAULT_LIMIT_PERCENT;
  return getLimitedExecutionTimes(conn, jobName, percent, rethink.desc('timestamp'));
}

function getLatestExecutionResults(conn, jobName) {
  const percent = config.has(EXECUTION_RESULTS_LATEST_LIMIT)
    ? config.get(EXECUTION_RESULTS_LATEST_LIMIT)
    : DEFAULT_LIMIT_PERCENT;
  return getLimitedExecutionResults(conn, jobName, percent, rethink.asc('timestamp'));
}

function getEarliestExecutionResults(conn, jobName) {
  const percent = config.has(EXECUTION_RESULTS_EARLIEST_LIMIT)
    ? config.get(EXECUTION_RESULTS_EARLIEST_LIMIT)
    : DEFAULT_LIMIT_PERCENT;
  return getLimitedExecutionResults(conn, jobName, percent, rethink.desc('timestamp'));
}

function getLimitedExecutionResults(conn, jobName, percent, order) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .orderBy(order)
    .limit(percentBasedLimit(jobName, percent))
    .pluck('result')
    .group('result')
    .count()
    .run(conn);
}

function getLimitedExecutionTimes(conn, jobName, percent, order) {
  return getTable()
    .getAll(jobName, { index: INDEX_NAME })
    .filter(rethink.row('result').eq('SUCCESS')
      .or(rethink.row('result').eq('UNSTABLE')))
    .orderBy(order)
    .limit(percentBasedLimit(jobName, percent))
    .orderBy('timestamp')
    .pluck('timestamp', 'duration', 'result')
    .run(conn);
}

function percentBasedLimit(jobName, percent) {
  return getTable().getAll(jobName, { index: INDEX_NAME })
    .count()
    .mul(percent)
    .div(100)
    .ceil();
}

function getTable() {
  return getDb().table(TABLE_NAME);
}

function getDb() {
  return rethink.db(DATABASE_NAME);
}

function toMergedTestResults(val) {
  return val
    .merge({
      failed: val.getField('actions')
        .reduce(sumField('failCount'))
        .default(0)
    })
    .merge({
      skipped: val.getField('actions')
        .reduce(sumField('skipCount'))
        .default(0)
    })
    .merge({
      total: val.getField('actions')
        .reduce(sumField('totalCount'))
        .default(0)
    });
}

function toCalculatedSuccessfulTests(val) {
  return val
    .merge({
      successful: val.getField('total').sub(
          val.getField('failed').add(val.getField('skipped')))
    })
    .without('total');
}

function sumField(fieldName) {
  return (left, right) =>
    left.getField(fieldName)
      .add(right.getField(fieldName));
}

module.exports = {
  getJobs,
  getBuilds,
  getExecutionTimes,
  getLatestExecutionTimes,
  getEarliestExecutionTimes,
  getExecutionResults,
  getLatestExecutionResults,
  getEarliestExecutionResults,
  getTestResults
};
<|endoftext|>


<commit_before>/*jshint bitwise: true, camelcase: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, regexp: true, undef: true, unused: true, strict: true*/
/*global define*/
define(["util"], function (util) {

    "use strict";

    function error(msg) {
        return function (state) {
            throw new Error(msg + " (line " + state.lineNum + ", char " + state.charNum + ")");
        };
    }

    var skip = { toString: function () { return "{skip}"; } };

    function newline(state) {
        state.i++;
        state.lineNum++;
        state.charNum = 1;
    }

    function readList(state) {
        var origState = state.clone();
        var openChr = state.input.charAt(state.i);
        var closeChr = openChr === "(" ? ")" :
                       openChr === "[" ? "]" :
                       openChr === "{" ? "}" :
                       error("Unknown list opener '" + openChr + "'")(state);
        var sym = openChr === "(" ? "paren" :
                  openChr === "[" ? "bracket" :
                  openChr === "{" ? "brace" : null;
        state.i++;
        var values = [];
        var closed = false;
        while (state.i < state.l) {
            if (state.input.charAt(state.i) === closeChr) {
                state.i++;
                closed = true;
                break;
            } else {
                var s = read(state);
                values.push(s);
            }
        }
        if (!closed) {
            error("Expected '" + closeChr + "'")(origState);
        }
        return util.createForm("list", values, { sym: sym });
    }

    function readNum(state) {
        var rxNum = /^[0-9\.]+$/;
        var rxHex = /^0x[0-9A-F]+$/i;
        var chunk = readToDelim(state);
        if (rxNum.test(chunk)) {
            return util.createForm("literal", parseFloat(chunk, 10));
        } else if (rxHex.test(chunk)) {
            return util.createForm("literal", parseInt(chunk, 16));
        } else {
            error("Invalid characters in number literal '" + chunk + "'")(state);
        }
    }

    function readString(state) {
        state.i++;
        var origState = state.clone();

        var chunk = "";
        var lastChr = null;
        var input = state.input;
        while (state.i < state.l) {
            var chr = input.charAt(state.i);
            if (chr === '"' && lastChr !== "\\") {
                break;
            } else {
                chunk += chr;
                lastChr = chr;
                state.i++;
                state.charNum++;
            }
        }

        if (state.i === state.l) {
            error("Unclosed string")(origState);
        }
        state.i++;
        return util.createForm("literal", '"' + chunk + '"');
    }

    function readSymbol(state) {
        // TODO: this might be a tad too relaxed
        return util.createForm("symbol", readToDelim(state));
    }

    function readComment(state) {
        var text = "";
        state.i++;
        while (state.i < state.l) {
            var chr = state.input.charAt(state.i++);
            if (chr === "\n") {
                break;
            } else if (chr !== "\r") {
                text += chr;
            }
        }
        return util.createForm("list", [util.createForm("symbol", "comment"), text]);
    }

    function readQuote(type) {
        return function (state) {
            state.i++;
            var x = read(state);
            if (x === null) {
                error("Expected something for " + type.substring(0, type.length - 1) + "ing")(state);
            }
            return util.createForm("list", [util.createForm("symbol", type), x]);
        };
    }

    function readUnquote(state) {
        state.i++;
        var type = "unquote";
        if (state.input.charAt(state.i) === "@") {
            type += "-splicing";
            state.i++;
        }
        var x = read(state);
        if (x === null) {
            error("Expected something for " + (type === "unquote" ? "unquoting" : type))(state);
        }
        return util.createForm("list", [util.createForm("symbol", type), x]);
    }

    var delimiters = {
        "(" : true,
        "[" : true,
        "{" : true,
        ")" : true,
        "]" : true,
        "}" : true,
        '"' : true,
        "'" : true,
        "`" : true,
        "," : true,
        ";" : true,
        " " : true,
        "\t": true,
        "\r": true,
        "\n": true
    };

    function readToDelim(state) {
        var chunk = "";
        var input = state.input;
        while (state.i < state.l) {
            var chr = input.charAt(state.i);
            if (delimiters.hasOwnProperty(chr)) {
                break;
            } else {
                chunk += chr;
                state.i++;
                state.charNum++;
            }
        }
        return chunk;
    }

    var readers = {
        "(" : readList,
        "[" : readList,
        "{" : readList,
        ")" : error("Unexpected ')' in input"),
        "]" : error("Unexpected ']' in input"),
        "}" : error("Unexpected '}' in input"),
        "'" : readQuote("quote"),
        "`" : readQuote("quasiquote"),
        "," : readUnquote,
        ";" : readComment,
        "0" : readNum,
        "1" : readNum,
        "2" : readNum,
        "3" : readNum,
        "4" : readNum,
        "5" : readNum,
        "6" : readNum,
        "7" : readNum,
        "8" : readNum,
        "9" : readNum,
        '"' : readString,
        " " : skip,
        "\t": skip,
        "\n": newline,
        "\r": skip
    };

    function read(state) {
        while (state.i < state.l) {
            var chr = state.input.charAt(state.i);
            var reader = readers[chr];
            if (reader === skip) {
                state.i++;
                continue;
            } else if (reader) {
                return reader(state);
            } else {
                return readSymbol(state);
            }
        }
        return null;
    }

    function readAll(input) {
        var result = [];
        var state = {
            input: input,
            i: 0,
            l: input.length,
            lineNum: 1,
            charNum: 1,
            clone: function () {
                return util.copyProps(state, {});
            }
        };
        while (true) {
            var atom = read(state);
            if (atom === null) {
                return result;
            } else {
                result.push(atom);
            }
        }
    }

    return { read: readAll };

});<commit_msg>Reader wasn't handling newlines correctly<commit_after>/*jshint bitwise: true, camelcase: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, regexp: true, undef: true, unused: true, strict: true*/
/*global define*/
define(["util"], function (util) {

    "use strict";

    function error(msg) {
        return function (state) {
            throw new Error(msg + " (line " + state.lineNum + ", char " + state.charNum + ")");
        };
    }

    var skip = { toString: function () { return "{skip}"; } };

    function newline(state) {
        state.i++;
        state.lineNum++;
        state.charNum = 1;
        return read(state);
    }

    function readList(state) {
        var origState = state.clone();
        var openChr = state.input.charAt(state.i);
        var closeChr = openChr === "(" ? ")" :
                       openChr === "[" ? "]" :
                       openChr === "{" ? "}" :
                       error("Unknown list opener '" + openChr + "'")(state);
        var sym = openChr === "(" ? "paren" :
                  openChr === "[" ? "bracket" :
                  openChr === "{" ? "brace" : null;
        state.i++;
        var values = [];
        var closed = false;
        while (state.i < state.l) {
            if (state.input.charAt(state.i) === closeChr) {
                state.i++;
                closed = true;
                break;
            } else {
                var s = read(state);
                values.push(s);
            }
        }
        if (!closed) {
            error("Expected '" + closeChr + "'")(origState);
        }
        return util.createForm("list", values, { sym: sym });
    }

    function readNum(state) {
        var rxNum = /^[0-9\.]+$/;
        var rxHex = /^0x[0-9A-F]+$/i;
        var chunk = readToDelim(state);
        if (rxNum.test(chunk)) {
            return util.createForm("literal", parseFloat(chunk, 10));
        } else if (rxHex.test(chunk)) {
            return util.createForm("literal", parseInt(chunk, 16));
        } else {
            error("Invalid characters in number literal '" + chunk + "'")(state);
        }
    }

    function readString(state) {
        state.i++;
        var origState = state.clone();

        var chunk = "";
        var lastChr = null;
        var input = state.input;
        while (state.i < state.l) {
            var chr = input.charAt(state.i);
            if (chr === '"' && lastChr !== "\\") {
                break;
            } else {
                chunk += chr;
                lastChr = chr;
                state.i++;
                state.charNum++;
            }
        }

        if (state.i === state.l) {
            error("Unclosed string")(origState);
        }
        state.i++;
        return util.createForm("literal", '"' + chunk + '"');
    }

    function readSymbol(state) {
        // TODO: this might be a tad too relaxed
        return util.createForm("symbol", readToDelim(state));
    }

    function readComment(state) {
        var text = "";
        state.i++;
        while (state.i < state.l) {
            var chr = state.input.charAt(state.i++);
            if (chr === "\n") {
                break;
            } else if (chr !== "\r") {
                text += chr;
            }
        }
        return util.createForm("list", [util.createForm("symbol", "comment"), text]);
    }

    function readQuote(type) {
        return function (state) {
            state.i++;
            var x = read(state);
            if (x === null) {
                error("Expected something for " + type.substring(0, type.length - 1) + "ing")(state);
            }
            return util.createForm("list", [util.createForm("symbol", type), x]);
        };
    }

    function readUnquote(state) {
        state.i++;
        var type = "unquote";
        if (state.input.charAt(state.i) === "@") {
            type += "-splicing";
            state.i++;
        }
        var x = read(state);
        if (x === null) {
            error("Expected something for " + (type === "unquote" ? "unquoting" : type))(state);
        }
        return util.createForm("list", [util.createForm("symbol", type), x]);
    }

    var delimiters = {
        "(" : true,
        "[" : true,
        "{" : true,
        ")" : true,
        "]" : true,
        "}" : true,
        '"' : true,
        "'" : true,
        "`" : true,
        "," : true,
        ";" : true,
        " " : true,
        "\t": true,
        "\r": true,
        "\n": true
    };

    function readToDelim(state) {
        var chunk = "";
        var input = state.input;
        while (state.i < state.l) {
            var chr = input.charAt(state.i);
            if (delimiters.hasOwnProperty(chr)) {
                break;
            } else {
                chunk += chr;
                state.i++;
                state.charNum++;
            }
        }
        return chunk;
    }

    var readers = {
        "(" : readList,
        "[" : readList,
        "{" : readList,
        ")" : error("Unexpected ')' in input"),
        "]" : error("Unexpected ']' in input"),
        "}" : error("Unexpected '}' in input"),
        "'" : readQuote("quote"),
        "`" : readQuote("quasiquote"),
        "," : readUnquote,
        ";" : readComment,
        "0" : readNum,
        "1" : readNum,
        "2" : readNum,
        "3" : readNum,
        "4" : readNum,
        "5" : readNum,
        "6" : readNum,
        "7" : readNum,
        "8" : readNum,
        "9" : readNum,
        '"' : readString,
        " " : skip,
        "\t": skip,
        "\n": newline,
        "\r": skip
    };

    function read(state) {
        while (state.i < state.l) {
            var chr = state.input.charAt(state.i);
            var reader = readers[chr];
            if (reader === skip) {
                state.i++;
                continue;
            } else if (reader) {
                return reader(state);
            } else {
                return readSymbol(state);
            }
        }
        return null;
    }

    function readAll(input) {
        var result = [];
        var state = {
            input: input,
            i: 0,
            l: input.length,
            lineNum: 1,
            charNum: 1,
            clone: function () {
                return util.copyProps(state, {});
            }
        };
        while (true) {
            var atom = read(state);
            if (atom === null) {
                return result;
            } else {
                result.push(atom);
            }
        }
    }

    return { read: readAll };

});<|endoftext|>