<commit_before>import assign from 'object-assign';

import diff from 'virtual-dom/diff';
import patch from 'virtual-dom/patch';
import createElement from 'virtual-dom/create-element';

import CustomNode from './custom-node';

export default function createComponent(lifecycle) {
	return new CustomNode(Component, lifecycle);
}

const excludeList = [
	'init',
	'update',
	'destroy',
	'setState',
];

export class Component {
	constructor(props, lifecycle) {
		Object
			.keys(lifecycle)
			.filter(name => {
				let isExcluded = !!~excludeList.indexOf(name);
				if (isExcluded) throw `Can't override system method "${name}"`;
				return !isExcluded;
			})
			.forEach(name => this[name] = lifecycle[name].bind(this));

		this._props = assign({}, props);
		this.type = 'Widget';
	}

	init(options) {
		this._queue = null;

		this.props = assign({}, this._props, this.getDefaultProps());
		this.state = assign({}, this.getInitialState());

		this._vdom = render.call(this);
		this._rootNode = createElement(this._vdom, options);
		this.componentWillMount();

		setTimeout(this.componentDidMount.bind(this), 0);
		return this._rootNode;
	}

	update(previous, domNode) {
		let props = this._props;

		this._queue = {};
		this._rootNode = domNode;
		this._vdom = previous._vdom;
		this.componentWillReceiveProps(props);

		let {state} = this._queue;
		this._queue = null;

		update.call(this, props, assign({}, previous.state, state));
	}

	destroy(domNode) {
		this.componentWillUnmount();
		this._rootNode = null;
		this._queue = null;
		this._vdom = null;
	}

	setState(newState = {}) {
		let nextState = assign({}, this.state, newState);

		if (this._queue) {
			this._queue.state = nextState;
			return;
		}

		update.call(this, null, nextState);
	}

	getDefaultProps() {}

	getInitialState() {}

	componentWillMount() {}

	componentDidMount() {}

	componentWillReceiveProps(nextProps) {}

	shouldComponentUpdate(nextProps, nextState) {
		return true;
	}

	render() {
		return null;
	}

	componentWillUpdate(nextProps, nextState) {}

	componentDidUpdate(prevProps, prevState) {}

	componentWillUnmount() {}
};

function render() {
	this._queue = {};

	let result = this.render();

	if (this._queue.state) {
		throw `You can't use setState during rendering phase`;
	}

	this._queue = null;
	return result;
}

function update(nextProps, nextState) {
	let prevProps = this.props;
	let prevState = this.state;

	nextProps || (nextProps = prevProps);
	nextState || (nextState = prevState);

	let shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);

	this.props = nextProps;
	this.state = nextState;

	if (shouldUpdate) {
		let prev = this._vdom;
		let next = render.call(this);

		let update = diff(prev, next);
		this._vdom = next;
		this.componentWillUpdate(nextProps, nextState);

		this._rootNode = patch(this._rootNode, update);
		this.componentDidUpdate(prevProps, prevState);
	}
}
<commit_msg>Better error handling<commit_after>import assign from 'object-assign';

import diff from 'virtual-dom/diff';
import patch from 'virtual-dom/patch';
import createElement from 'virtual-dom/create-element';

import CustomNode from './custom-node';

export default function createComponent(lifecycle) {
	return new CustomNode(Component, lifecycle);
}

const excludeList = [
	'init',
	'update',
	'destroy',
	'setState',
];

export class Component {
	constructor(props, lifecycle) {
		Object
			.keys(lifecycle)
			.filter(name => {
				let isExcluded = !!~excludeList.indexOf(name);
				if (isExcluded) throw `Can't override system method "${name}"`;
				return !isExcluded;
			})
			.forEach(name => this[name] = lifecycle[name].bind(this));

		this._props = assign({}, props);
		this.type = 'Widget';
	}

	init(options) {
		this._queue = null;

		this.props = assign({}, this._props, this.getDefaultProps());
		this.state = assign({}, this.getInitialState());

		this._vdom = render.call(this);
		this._rootNode = createElement(this._vdom, options);
		this.componentWillMount();

		setTimeout(this.componentDidMount.bind(this), 0);
		return this._rootNode;
	}

	update(previous, domNode) {
		let props = this._props;

		this._queue = {};
		this._rootNode = domNode;
		this._vdom = previous._vdom;
		this.componentWillReceiveProps(props);

		let {state} = this._queue;
		this._queue = null;

		update.call(this, props, assign({}, previous.state, state));
	}

	destroy(domNode) {
		this.componentWillUnmount();
		this._rootNode = null;
		this._queue = null;
		this._vdom = null;
	}

	setState(newState = {}) {
		let nextState = assign({}, this.state, newState);

		if (this._queue) {
			this._queue.state = nextState;
			return;
		}

		update.call(this, null, nextState);
	}

	getDefaultProps() {}

	getInitialState() {}

	componentWillMount() {}

	componentDidMount() {}

	componentWillReceiveProps(nextProps) {}

	shouldComponentUpdate(nextProps, nextState) {
		return true;
	}

	render() {
		return null;
	}

	componentWillUpdate(nextProps, nextState) {}

	componentDidUpdate(prevProps, prevState) {}

	componentWillUnmount() {}
};

function render() {
	let result;

	this._queue = {};

	try {
		result = this.render();
	} catch(error) {
		console.error(error);
	}

	if (this._queue.state) {
		throw `You can't use setState during rendering phase`;
	}

	this._queue = null;
	return result;
}

function update(nextProps, nextState) {
	let prevProps = this.props;
	let prevState = this.state;

	nextProps || (nextProps = prevProps);
	nextState || (nextState = prevState);

	let shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);

	this.props = nextProps;
	this.state = nextState;

	if (shouldUpdate) {
		let prev = this._vdom;
		let next = render.call(this);

		let update = diff(prev, next);
		this._vdom = next;
		this.componentWillUpdate(nextProps, nextState);

		this._rootNode = patch(this._rootNode, update);
		this.componentDidUpdate(prevProps, prevState);
	}
}
<|endoftext|>


<commit_before><commit_msg>fix: attribute pointer should use GeometryData.size<commit_after><|endoftext|>


<commit_before>/**
 * @author Karl-Magnus Jönsson
 * @copyright Kristianstads kommun
 * @license MIT license
 */

/**
 * @requires sMap/Module.js
 */

sMap.Module.Export = OpenLayers.Class(sMap.Module, {

	/**
	 * The events that this module will listen to. Each event listener
	 * is connected to a method defined in this module, with the same
	 * name as the event. When another module triggers this event, the
	 * method will be called (and other modules which are listening
	 * to the same event).
	 *
	 * Look at the event listeners as a public API of the module.
	 */
	EVENT_LISTENERS : [],

	/**
	 * The events triggered from this module. Note that some modules
	 * both listens to and trigger events.
	 */
	EVENT_TRIGGERS : [],

	initialize : function(options) {
		options = options || {};

		this.EVENT_LISTENERS =
			sMap.Module.Export.prototype.EVENT_LISTENERS.concat(
				sMap.Module.prototype.EVENT_LISTENERS
        );
		this.EVENT_TRIGGERS =
			sMap.Module.Export.prototype.EVENT_TRIGGERS.concat(
				sMap.Module.prototype.EVENT_TRIGGERS
        );

		// This allows your control to be extended by sending in a parameter hash object
		// For example overriding a method in this class or in the parent class (see next step).
		OpenLayers.Util.applyDefaults(this, options);
		// This calls the parent class's constructor and allows to
		// extend it (e.g. override methods).
		sMap.Module.prototype.initialize.apply(this, [options]);

	},

	activate : function() {
		if (this.active===true) {
			return false;
		}
		if (!this.dialogDiv){
			this.dialogDiv = this.makeExportDialog();
			this.addDialogContent(this.dialogDiv);
		}
		this.dialogDiv.dialog("open");
		// Call the activate method of the parent class
		return sMap.Module.prototype.activate.apply(
	            this, arguments);
	},

	deactivate : function() {
		if (this.active!==true) {
			return false;
		}
		if (this.exportExtentLayer) {
			this.exportExtentLayer.destroyFeatures();
			this.map.removeLayer(this.exportExtentLayer);
			this.exportExtentLayer.destroy();
			this.exportExtentLayer = null;
		}
		// Call the deactivate method of the parent class
		return sMap.Module.prototype.deactivate.apply(
	            this, arguments
	        );
	},

	destroy : function() {
		// Call the destroy method of the parent class
		return sMap.Module.prototype.destroy.apply(this, arguments);
	},

    /**
     * Called when all modules are initialized, i.e. after initialize.
     * All initial HTML should be produced from here.
     * @returns {void}
     */
	drawContent : function() {
		var eventChooser = this.addToToolsMenu ? "addtomenu" : "addtoolbutton";

		sMap.events.triggerEvent(eventChooser, this, {
			index : this.toolbarIndex,
			iconCSS : "ui-icon-arrowthickstop-1-s",
			label : this.lang.buttonText,
			hoverText : this.lang.hoverText,
			tagID : "button-export",
			menuId : this.addToToolsMenu
		});
	},
	/**
	 * Make the dialog to which all html is added.
	 */
	makeExportDialog : function() {
		var dialogDiv = $("
");
		this.dialogDiv = dialogDiv;
		var self = this;
		dialogDiv.dialog({
			autoOpen : false,
			title : this.lang.dialogTitle,
			position : this.dialogStartPosition,
			width : this.width,
			height : this.height,
			resizable : true,
			close : function() {
				// Deactivate module
				self.deactivate.call(self);
			},
			open : null
		});

		return dialogDiv;
	},
	/**
	 * Construct the dialog content
	 * @param dialogDiv
	 */
	addDialogContent : function(dialogDiv) {
		var self = this;
		var helptext = $("
"+this.lang.helptext+"

");
		dialogDiv.append(helptext);

		dialogDiv.append(this.lang.lblRoutine+"
");
		var selectRoutine = $("<select id='export-selectRoutine' />");
		for (var key in this.exportRoutines){
			var format = this.exportRoutines[key];
			var option = $("<option value="+key+" >"+format.name+"</option>");
			selectRoutine.append(option);
		}
		dialogDiv.append(selectRoutine);
		dialogDiv.append("
");

		dialogDiv.append("
"+this.lang.lblCRS+"
");
		var selectCRS = $("<select id='export-crsSelectTag' />");
		for (var i=0;i<this.crsList.length;i++){
			var crs = this.crsList[i];
			var option = $("<option value="+crs.code+" >"+crs.name+"</option>");
			selectCRS.append(option);
		}
		dialogDiv.append(selectCRS);
		dialogDiv.append("

");

		var extbtn = $("<button id='export-extent'>"+this.lang.btnExtent+"</button>");
		extbtn.button();
		extbtn.click(function() {
			self.toggleDraw();
		});
		dialogDiv.append(extbtn);
		dialogDiv.append("

");

		var button = $("<button id='export-submit'>"+this.lang.btnExport+"</button>");
		button.click(function() {
			self.exportData();
		});
		button.button();
		dialogDiv.append(button);
	},
	/**
	 * Adds a vector layer for export extent with an OL drawfeature control
	 */
	addExportExtentLayer : function(){
		if (!this.exportExtentLayer) {
			this.exportExtentLayer = new OpenLayers.Layer.Vector("export_extentlayer", {
				styleMap: new OpenLayers.StyleMap({
					"default": new OpenLayers.Style({
						fillOpacity: 0,
						fillColor: "#FFF",
						strokeWidth: 1,
						strokeOpacity: 1,
						strokeColor: "#F00"
					}),
					"temporary": new OpenLayers.Style({
						fillOpacity: 0,
						fillColor: "#FFF",
						strokeWidth: 1,
						strokeOpacity: 1,
						strokeColor: "#F00"
					})
				})
			});
			this.map.addLayer(this.exportExtentLayer);
			this.exportExtentLayer.events.register("featureadded", this, function(e) {
				this.toggleDraw();
			});
			this.drawPolygon = new OpenLayers.Control.DrawFeature(
					this.exportExtentLayer, OpenLayers.Handler.RegularPolygon, {
						handlerOptions: {
                            sides: 4,
                            irregular: true
                        }
				});
			this.map.addControl(this.drawPolygon);
		}
	},
	/**
	 * Toggles the OL drawfeature control
	 */
	toggleDraw : function(){
		this.addExportExtentLayer();
		if (this.drawPolygon.active){
			this.drawPolygon.deactivate();
		}
		else{
			this.drawPolygon.activate();
			this.clearDraw();
		}
	},
	/**
	 * Clears all drawed features
	 */
	clearDraw : function(){
		this.exportExtentLayer.removeAllFeatures();
	},
	/**
	 * Assemble and open the export URL
	 */
	exportData : function(){
		var map = this.map,
			extent = map.getExtent(),
			routine = this.exportRoutines[$("#export-selectRoutine").val()],
			url = routine.url;
		if (routine.addVisibleLayers){
			var visibleLayerNames = "",
				layercount = 0,
				layer = {};
			for (var i=0;i<map.layers.length;i++){
				layer = map.layers[i];
				if (layer.visibility && layer.displayInLayerSwitcher && !layer.isBaseLayer && layer.CLASS_NAME != "OpenLayers.Layer.Vector"){
					var t = sMap.cmd.getLayerConfig(layer.name);
					visibleLayerNames += t.resource ? t.resource.replace(",","+") + "+" : "";  //replace
					layercount++;
				}
			}
			if (visibleLayerNames){
				url += "pglayers="+visibleLayerNames;
			}
			if (layercount > this.maxlayers) {
				alert('För många lager! Det går endast att exportera ' + this.maxlayers + ' lager samtidigt');
				return;
			}
		}
		if (routine.addBaseLayer){
			url += "blayer="+map.baseLayer.name;
		}
		if(this.exportExtentLayer && this.exportExtentLayer.features.length>0){
			extent = this.exportExtentLayer.features[0].geometry.bounds;
		}
		url += "&minx=" + extent.left;
		url += "&miny=" + extent.bottom;
		url += "&maxx=" + extent.right;
		url += "&maxy=" + extent.top;
		url += "&cs=" + $("#export-crsSelectTag").val();
		//alert('Export ' + url);
		window.open(url,"_blank");
	},
	// Class name needed when you want to fetch your module...
	// should correspond to the real class name.
	CLASS_NAME : "sMap.Module.Export"

});<commit_msg>#7 Minor bug fixing<commit_after>/**
 * @author Karl-Magnus Jönsson
 * @copyright Kristianstads kommun
 * @license MIT license
 */

/**
 * @requires sMap/Module.js
 */

sMap.Module.Export = OpenLayers.Class(sMap.Module, {

	/**
	 * The events that this module will listen to. Each event listener
	 * is connected to a method defined in this module, with the same
	 * name as the event. When another module triggers this event, the
	 * method will be called (and other modules which are listening
	 * to the same event).
	 *
	 * Look at the event listeners as a public API of the module.
	 */
	EVENT_LISTENERS : [],

	/**
	 * The events triggered from this module. Note that some modules
	 * both listens to and trigger events.
	 */
	EVENT_TRIGGERS : [],

	initialize : function(options) {
		options = options || {};

		this.EVENT_LISTENERS =
			sMap.Module.Export.prototype.EVENT_LISTENERS.concat(
				sMap.Module.prototype.EVENT_LISTENERS
        );
		this.EVENT_TRIGGERS =
			sMap.Module.Export.prototype.EVENT_TRIGGERS.concat(
				sMap.Module.prototype.EVENT_TRIGGERS
        );

		// This allows your control to be extended by sending in a parameter hash object
		// For example overriding a method in this class or in the parent class (see next step).
		OpenLayers.Util.applyDefaults(this, options);
		// This calls the parent class's constructor and allows to
		// extend it (e.g. override methods).
		sMap.Module.prototype.initialize.apply(this, [options]);

	},

	activate : function() {
		if (this.active===true) {
			return false;
		}
		if (!this.dialogDiv){
			this.dialogDiv = this.makeExportDialog();
			this.addDialogContent(this.dialogDiv);
		}
		this.dialogDiv.dialog("open");
		// Call the activate method of the parent class
		return sMap.Module.prototype.activate.apply(
	            this, arguments);
	},

	deactivate : function() {
		if (this.active!==true) {
			return false;
		}
		if (this.exportExtentLayer) {
			this.exportExtentLayer.destroyFeatures();
			this.map.removeLayer(this.exportExtentLayer);
			this.exportExtentLayer.destroy();
			this.exportExtentLayer = null;
		}
		if (this.dialogDiv && this.dialogDiv.dialog("isOpen") === true) {
			return this.dialogDiv.dialog("close");
		}
		// Call the deactivate method of the parent class
		return sMap.Module.prototype.deactivate.apply(
	            this, arguments
	        );
	},

	destroy : function() {
		// Call the destroy method of the parent class
		return sMap.Module.prototype.destroy.apply(this, arguments);
	},

    /**
     * Called when all modules are initialized, i.e. after initialize.
     * All initial HTML should be produced from here.
     * @returns {void}
     */
	drawContent : function() {
		var eventChooser = this.addToToolsMenu ? "addtomenu" : "addtoolbutton";

		sMap.events.triggerEvent(eventChooser, this, {
			index : this.toolbarIndex,
			iconCSS : "ui-icon-arrowthickstop-1-s",
			label : this.lang.buttonText,
			hoverText : this.lang.hoverText,
			tagID : "button-export",
			menuId : this.addToToolsMenu
		});
	},
	/**
	 * Make the dialog to which all html is added.
	 */
	makeExportDialog : function() {
		var dialogDiv = $("
");
		this.dialogDiv = dialogDiv;
		var self = this;
		dialogDiv.dialog({
			autoOpen : false,
			title : this.lang.dialogTitle,
			position : this.dialogStartPosition,
			width : this.width,
			height : this.height,
			resizable : true,
			close : function() {
				// Deactivate module
				self.deactivate.call(self);
			},
			open : null
		});

		return dialogDiv;
	},
	/**
	 * Construct the dialog content
	 * @param dialogDiv
	 */
	addDialogContent : function(dialogDiv) {
		var self = this;
		var helptext = $("
"+this.lang.helptext+"

");
		dialogDiv.append(helptext);

		dialogDiv.append(this.lang.lblRoutine+"
");
		var selectRoutine = $("<select id='export-selectRoutine' />");
		for (var key in this.exportRoutines){
			var format = this.exportRoutines[key];
			var option = $("<option value="+key+" >"+format.name+"</option>");
			selectRoutine.append(option);
		}
		dialogDiv.append(selectRoutine);
		dialogDiv.append("
");

		dialogDiv.append("
"+this.lang.lblCRS+"
");
		var selectCRS = $("<select id='export-crsSelectTag' />");
		for (var i=0;i<this.crsList.length;i++){
			var crs = this.crsList[i];
			var option = $("<option value="+crs.code+" >"+crs.name+"</option>");
			selectCRS.append(option);
		}
		dialogDiv.append(selectCRS);
		dialogDiv.append("

");

		var extbtn = $("<button id='export-extent'>"+this.lang.btnExtent+"</button>");
		extbtn.button();
		extbtn.click(function() {
			self.toggleDraw();
		});
		dialogDiv.append(extbtn);
		dialogDiv.append("

");

		var button = $("<button id='export-submit'>"+this.lang.btnExport+"</button>");
		button.click(function() {
			self.exportData();
		});
		button.button();
		dialogDiv.append(button);
	},
	/**
	 * Adds a vector layer for export extent with an OL drawfeature control
	 */
	addExportExtentLayer : function(){
		if (!this.exportExtentLayer) {
			this.exportExtentLayer = new OpenLayers.Layer.Vector("export_extentlayer", {
				styleMap: new OpenLayers.StyleMap({
					"default": new OpenLayers.Style({
						fillOpacity: 0,
						fillColor: "#FFF",
						strokeWidth: 1,
						strokeOpacity: 1,
						strokeColor: "#F00"
					}),
					"temporary": new OpenLayers.Style({
						fillOpacity: 0,
						fillColor: "#FFF",
						strokeWidth: 1,
						strokeOpacity: 1,
						strokeColor: "#F00"
					})
				})
			});
			this.map.addLayer(this.exportExtentLayer);
			this.exportExtentLayer.events.register("featureadded", this, function(e) {
				this.toggleDraw();
			});
			this.drawPolygon = new OpenLayers.Control.DrawFeature(
					this.exportExtentLayer, OpenLayers.Handler.RegularPolygon, {
						handlerOptions: {
                            sides: 4,
                            irregular: true
                        }
				});
			this.map.addControl(this.drawPolygon);
		}
	},
	/**
	 * Toggles the OL drawfeature control
	 */
	toggleDraw : function(){
		this.addExportExtentLayer();
		if (this.drawPolygon.active){
			this.drawPolygon.deactivate();
		}
		else{
			this.drawPolygon.activate();
			this.clearDraw();
		}
	},
	/**
	 * Clears all drawed features
	 */
	clearDraw : function(){
		this.exportExtentLayer.removeAllFeatures();
	},
	/**
	 * Assemble and open the export URL
	 */
	exportData : function(){
		var map = this.map,
			extent = map.getExtent(),
			routine = this.exportRoutines[$("#export-selectRoutine").val()],
			url = routine.url;
		if (routine.addVisibleLayers){
			var visibleLayerNames = "",
				layercount = 0,
				layer = {};
			for (var i=0;i<map.layers.length;i++){
				layer = map.layers[i];
				if (layer.visibility && layer.displayInLayerSwitcher && !layer.isBaseLayer && layer.CLASS_NAME != "OpenLayers.Layer.Vector"){
					var t = sMap.cmd.getLayerConfig(layer.name);
					visibleLayerNames += t.resource ? t.resource.replace(",","+") + "+" : "";  //replace
					layercount++;
				}
			}
			if (visibleLayerNames){
				url += "pglayers="+visibleLayerNames;
			}
			if (layercount > this.maxlayers) {
				alert('För många lager! Det går endast att exportera ' + this.maxlayers + ' lager samtidigt');
				return;
			}
		}
		if (routine.addBaseLayer){
			url += "blayer="+map.baseLayer.name;
		}
		if(this.exportExtentLayer && this.exportExtentLayer.features.length>0){
			extent = this.exportExtentLayer.features[0].geometry.bounds;
		}
		url += "&minx=" + extent.left;
		url += "&miny=" + extent.bottom;
		url += "&maxx=" + extent.right;
		url += "&maxy=" + extent.top;
		url += "&cs=" + $("#export-crsSelectTag").val();
		//alert('Export ' + url);
		window.open(url,"_blank");
	},
	// Class name needed when you want to fetch your module...
	// should correspond to the real class name.
	CLASS_NAME : "sMap.Module.Export"

});<|endoftext|>


<commit_before>/*
    Copyright 2010 Emilis Dambauskas

    This file is part of PolicyFeed module.

    PolicyFeed 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.

    PolicyFeed 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 PolicyFeed.  If not, see <http://www.gnu.org/licenses/>.
*/

require("core/date");

var DB_old = loadObject("DB_old");
var JsonStorage = require("ctl/JsonStorage");
var Sequence = require("ctl/SimpleSequence");

// original_id to new added_id:
exports.oid2new = {};

// old-source -> type map:
var typemap = {
    LRS_darbotvarkes: "darbotvarke",
    LRS_pranesimai_spaudai: "pranesimas",
    LRS_teises_aktai: "projektas",
    LRV_darbotvarkes: "darbotvarke",
    LRV_naujienos: "pranesimas"
};

var orgs = {
    LRS: ["Seimas", "Lietuvos Respublikos Seimas"],
    LRV: ["Vyriausybė", "Lietuvos Respublikos Vyriausybė"]
};

// Create special chars RegExp:
var special_chars = ["["];
for (var i=0;i<32;i++)
    special_chars.push(String.fromCharCode(i));
special_chars.push("]");
special_chars = new RegExp(special_chars.join(""), "g");

/**
 *
 */
var fixString = function(str) {
    return str.replace(special_chars, " ").replace(/\s+/g, " ").trim();
}

//----------------------------------------------------------------------------

/**
 * Migrate everything.
 */
exports.migrate = function() {

    print(new Date());

    this.originals();

    print(new Date());

    this.docs();

    print(new Date());
}

/**
 *
 */
exports.docs = function(ids) {
    if (ids === undefined)
        var sql = "select * from docs order by published asc";
    else
        var sql = "select * from docs where id in('" + ids.join("','") + "')";

    var rs = DB_old.query(sql);
    if (!rs.first())
        return false;

    rs.beforeFirst();
    while (rs.next())
    {
        var doc = DB_old.get_row(rs);
        try {
            var data = JSON.parse(doc.meta);
        } catch (e) {
            print(doc.meta);
            print(e);
        }

        //data.id             = doc.id;
        //data.original_id    = doc.original_id;
        data.updated        = doc.updated;
        data.published      = doc.published;
        data.comment_count  = doc.comment_count;
        data.html           = doc.html;

        data.title = fixString(data.title);
        data.html  = fixString(data.html);

        data.type = typemap[data.source];
        data.org = orgs[data.source.substr(0, 3)][0];
        data.organization = orgs[data.source.substr(0, 3)][1];

        var id = oid2new[data.original_id].replace("originals", "docs");
        JsonStorage.write(id, data);
    }

    rs.getStatement().close();
}

/**
 *
 */
exports.originals = function() {
    var sql = "select * from originals";

    var rs = DB_old.query(sql);
    if (!rs.first())
        return false;

    rs.beforeFirst();
    while (rs.next())
    {
        var original = DB_old.get_row(rs);
        try {
            var data = JSON.parse(original.meta);
        } catch (e) {
            print(original.meta);
            print(e);
        }

        data.updated    = original.updated;
        data.published  = original.published;
        data.parser     = original.source;
        data.url        = original.url
        data.html       = original.html;

        data.type = typemap[original.source];
        data.org = orgs[original.source.substr(0, 3)][0];
        data.organization = orgs[original.source.substr(0, 3)][1];

        var id = "/originals/" + data.published.substr(0, 10).replace(/-/g, "/") + "/" + original.id;

        JsonStorage.write(id, data);

        oid2new[original.id] = id;
    }

    rs.getStatement().close();
}

/**
 *
 */
exports.comments = function() {

    var sql="select updated, parent_id, thread_id, author, user_id, score, text from govsrvr.comments";

    var rs = db.query(sql);
}
<commit_msg>Added sourceToNewFields() to PolicyFeed/Migration.<commit_after>/*
    Copyright 2010 Emilis Dambauskas

    This file is part of PolicyFeed module.

    PolicyFeed 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.

    PolicyFeed 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 PolicyFeed.  If not, see <http://www.gnu.org/licenses/>.
*/

require("core/date");

//var DB_old = loadObject("DB_old");
var JsonStorage = require("ctl/JsonStorage");
var Sequence = require("ctl/SimpleSequence");

// original_id to new added_id:
exports.oid2new = {};

// old-source -> type map:
exports.sourcemap = {
    LRS_darbotvarkes: ["lrs.lt-darbotvarkes", "darbotvarke", "Seimas", "Lietuvos Respublikos Seimas"],
    LRS_pranesimai_spaudai: ["lrs.lt-pranesimai", "pranesimas", "Seimas", "Lietuvos Respublikos Seimas"],
    LRS_teises_aktai: ["lrs.lt-teises-aktai", "projektas", "Seimas", "Lietuvos Respublikos Seimas"],
    LRV_darbotvarkes: ["lrv.lt-darbotvarkes", "darbotvarke", "Vyriausybė", "Lietuvos Respublikos Vyriausybė"],
    LRV_naujienos: ["lrv.lt-naujienos", "pranesimas", "Vyriausybė", "Lietuvos Respublikos Vyriausybė"]
};

// Create special chars RegExp:
var special_chars = ["["];
for (var i=0;i<32;i++)
    special_chars.push(String.fromCharCode(i));
special_chars.push("]");
special_chars = new RegExp(special_chars.join(""), "g");

/**
 *
 */
var fixString = function(str) {
    return str.replace(special_chars, " ").replace(/\s+/g, " ").trim();
}

//----------------------------------------------------------------------------

/**
 * Migrate everything.
 */
exports.migrate = function() {

    print(new Date());

    this.originals();

    print(new Date());

    this.docs();

    print(new Date());
}

/**
 *
 */
exports.sourceToNewFields = function(doc, source) {
    if (!source) {
        throw Error('Migration.sourceToNewFields: document ' + doc.id + '/' + doc._id + ' has no source field.');
    } else if (!this.sourcemap[source]) {
        throw Error('Migration.sourceToNewFields: unsupported source "' + source + '" for document ' + doc.id + '/' + doc._id + '.');
    } else {
        [doc.parser, doc.type, doc.org, doc.organization] = this.sourcemap[source];
        return doc;
    }
}

/**
 *
 */
exports.docs = function(ids) {
    if (ids === undefined)
        var sql = "select * from docs order by published asc";
    else
        var sql = "select * from docs where id in('" + ids.join("','") + "')";

    var rs = DB_old.query(sql);
    if (!rs.first())
        return false;

    rs.beforeFirst();
    while (rs.next())
    {
        var doc = DB_old.get_row(rs);
        try {
            var data = JSON.parse(doc.meta);
        } catch (e) {
            print(doc.meta);
            print(e);
        }

        //data.id             = doc.id;
        //data.original_id    = doc.original_id;
        data.updated        = doc.updated;
        data.published      = doc.published;
        data.comment_count  = doc.comment_count;
        data.html           = doc.html;

        data.title = fixString(data.title);
        data.html  = fixString(data.html);

        data = this.sourceToNewFields(data, doc.source);

        var id = oid2new[data.original_id].replace("originals", "docs");
        JsonStorage.write(id, data);
    }

    rs.getStatement().close();
}

/**
 *
 */
exports.originals = function() {
    var sql = "select * from originals";

    var rs = DB_old.query(sql);
    if (!rs.first())
        return false;

    rs.beforeFirst();
    while (rs.next())
    {
        var original = DB_old.get_row(rs);
        try {
            var data = JSON.parse(original.meta);
        } catch (e) {
            print(original.meta);
            print(e);
        }

        data.updated    = original.updated;
        data.published  = original.published;
        data.url        = original.url
        data.html       = original.html;

        data = this.sourceToNewFields(data, original.source);

        var id = "/originals/" + data.published.substr(0, 10).replace(/-/g, "/") + "/" + original.id;

        JsonStorage.write(id, data);

        oid2new[original.id] = id;
    }

    rs.getStatement().close();
}

/**
 *
 */
exports.comments = function() {

    var sql="select updated, parent_id, thread_id, author, user_id, score, text from govsrvr.comments";

    var rs = db.query(sql);
}
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react'
import Look, { StyleSheet } from 'react-look'
const c = StyleSheet.combineStyles
import { $, pushLocation } from 'bauhaus-ui-module-utils'
import _ from 'lodash'

class SimpleLinkList extends Component {
  constructor(props) {
    super(props)
    this.handleFilterChange = this
      .handleFilterChange
      .bind(this)
  }
  handleFilterChange(event) {
    const {bauhaus} = this.props
    this.setState({
      filter: event.target.value
    })
  }
  pushLocation(location) {
    const {bauhaus} = this.props
    return function() {
      pushLocation(location)
    }
  }
  componentWillMount() {
    const {bauhaus} = this.props
    this.setState({
      filter: ''
    })
  }
  render() {
    const {bauhaus} = this.props

    return (

        { $(bauhaus.props.title) }

        { $('$core.commons.filter') }: <input className={ styles.textInput } type="text" value={ this.state.filter } onChange={ this.handleFilterChange } />

        { _.map(bauhaus.props.list, function(value, key) {
            if (value.name.search(this.state.filter) >= 0) {
              return (

                        { $(value.name) }

)
            } else {
              return
            }
          }.bind(this)) }

    )
  }
}

import styleSheet from './style.js'
var styles = StyleSheet.create(styleSheet)

export default Look(SimpleLinkList)
<commit_msg>Case insensitive SimpleLinkList Filter<commit_after>import React, { PropTypes, Component } from 'react'
import Look, { StyleSheet } from 'react-look'
const c = StyleSheet.combineStyles
import { $, pushLocation } from 'bauhaus-ui-module-utils'
import _ from 'lodash'

class SimpleLinkList extends Component {
  constructor(props) {
    super(props)
    this.handleFilterChange = this
      .handleFilterChange
      .bind(this)
  }
  handleFilterChange(event) {
    const {bauhaus} = this.props
    this.setState({
      filter: event.target.value
    })
  }
  pushLocation(location) {
    const {bauhaus} = this.props
    return function() {
      pushLocation(location)
    }
  }
  componentWillMount() {
    const {bauhaus} = this.props
    this.setState({
      filter: ''
    })
  }
  render() {
    const {bauhaus} = this.props

    return (

        { $(bauhaus.props.title) }

        { $('$core.commons.filter') }: <input className={ styles.textInput } type="text" value={ this.state.filter } onChange={ this.handleFilterChange } />

        { _.map(bauhaus.props.list, function(value, key) {
            if (value.name.toLowerCase().search(this.state.filter.toLowerCase()) >= 0) {
              return (

                        { $(value.name) }

)
            } else {
              return
            }
          }.bind(this)) }

    )
  }
}

import styleSheet from './style.js'
var styles = StyleSheet.create(styleSheet)

export default Look(SimpleLinkList)
<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs');
const vm = require('vm');

const verbose = process.env.NODE_ENV === 'test';

module.exports = function(filePath, fileType, basePath) {
  let lastMTime = null;
  let isUpdating = null;
  let middleware = null;

  function createMiddleware(data) {
    switch(fileType) {
      case 'json':
        return function(req, res) {
          res.json(JSON.parse(data));
        };
      case 'js':
        const newRequire = function(modPath) {
          let resolved = modPath;
          if (path.parse(modPath).dir !== '') {
            resolved = path.resolve(basePath, modPath);
          }
          return module.require(resolved);
        };
        const sandbox = { module: {}, require: newRequire };
        vm.runInNewContext(data, sandbox);
        return sandbox.module.exports;
    }
  }

  function updateFile(cb) {
    if (isUpdating) return;
    isUpdating = true;
    fs.stat(filePath, function(err, stat) {
      if (err) throw err;
      if (lastMTime && stat.mtime.getTime() === lastMTime.getTime()) {
        if (verbose) console.log('no update needed: %s',
            filePath, fileType);
        isUpdating = false;
        cb && cb();
        return;
      }
      if (verbose) console.log('updating file: %s (%s) (%s, %s)', filePath, fileType,
          stat.mtime.getTime(), lastMTime && lastMTime.getTime());
      lastMTime = stat.mtime;
      fs.readFile(filePath, 'utf8', function(_err, data) {
        if (_err) throw _err;
        middleware = createMiddleware(data);
        isUpdating = false;
        cb && cb();
      });
    });
  }

  updateFile();  // first cache

  return function(/* req, res, ... */) {
    const that = this;
    const args = arguments;
    updateFile(function() {
      middleware.apply(that, args);
    });
  };
};
<commit_msg>Improved error handling<commit_after>const path = require('path');
const fs = require('fs');
const vm = require('vm');

const verbose = process.env.NODE_ENV === 'test';

module.exports = function(filePath, fileType, basePath) {
  let lastMTime = null;
  let isUpdating = null;
  let middleware = null;

  function createMiddleware(data) {
    switch(fileType) {
      case 'json':
        return function(req, res) {
          res.json(JSON.parse(data));
        };
      case 'js':
        const newRequire = function(modPath) {
          let resolved = modPath;
          if (path.parse(modPath).dir !== '') {
            resolved = path.resolve(basePath, modPath);
          }
          return module.require(resolved);
        };
        const sandbox = {
          module: {
            exports: {},
            require: newRequire,
          },
          require: newRequire
        };
        vm.runInNewContext(data, sandbox);
        return sandbox.module.exports;
    }
  }

  function updateFile(cb) {
    if (isUpdating) {
      cb && cb();
      return;
    }
    isUpdating = true;
    fs.stat(filePath, function(err, stat) {
      if (err) {
        if (cb) cb(err);
        else throw err; // unhandled
        return;
      }
      if (lastMTime && stat.mtime.getTime() === lastMTime.getTime()) {
        if (verbose) console.log('no update needed: %s',
            filePath, fileType);
        isUpdating = false;
        cb && cb();
        return;
      }
      if (verbose) console.log('updating file: %s (%s) (%s, %s)', filePath, fileType,
          stat.mtime.getTime(), lastMTime && lastMTime.getTime());
      lastMTime = stat.mtime;
      fs.readFile(filePath, 'utf8', function(_err, data) {
        if (_err) {
          if (cb) cb(_err);
          else throw _err; // unhandled
          return;
        }
        middleware = createMiddleware(data);
        isUpdating = false;
        cb && cb();
      });
    });
  }

  function handleError(res, err) {
    res.status(500).json({
      ok: false,
      error: err.message || err,
      file: filePath,
    });
    return;
  }

  updateFile();  // first cache

  return function(req, res) {
    const that = this;
    const args = arguments;
    updateFile(function(err) {
      if (err) {
        handleError(res, err);
        return;
      }
      try {
        middleware.apply(that, args);
      } catch (_err) {
        handleError(res, _err);
        return;
      }
    });
  };
};
<|endoftext|>


<commit_before>(function (app) {
  'use strict';

  // Start by defining the main module and adding the module dependencies
  angular
    .module(app.applicationModuleName, app.applicationModuleVendorDependencies);

  // Setting HTML5 Location Mode
  angular
    .module(app.applicationModuleName)
    .config(bootstrapConfig);

  bootstrapConfig.$inject = ['$compileProvider', '$locationProvider', '$httpProvider', '$logProvider'];

  function bootstrapConfig($compileProvider, $locationProvider, $httpProvider, $logProvider) {
    $locationProvider.html5Mode({
      enabled: true,
      requireBase: false
    }).hashPrefix('!');

    $httpProvider.interceptors.push('authInterceptor');

    // Disable debug data for production environment
    // @link https://docs.angularjs.org/guide/production
    $compileProvider.debugInfoEnabled(app.applicationEnvironment !== 'production');
    $logProvider.debugEnabled(app.applicationEnvironment !== 'production');
  }

  // Then define the init function for starting up the application
  angular.element(document).ready(init);

  function init() {
    // Fixing facebook bug with redirect
    if (window.location.hash && window.location.hash === '#_=_') {
      if (window.history && history.pushState) {
        window.history.pushState('', document.title, window.location.pathname);
      } else {
        // Prevent scrolling by storing the page's current scroll offset
        var scroll = {
          top: document.body.scrollTop,
          left: document.body.scrollLeft
        };
        window.location.hash = '';
        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scroll.top;
        document.body.scrollLeft = scroll.left;
      }
    }

    // Then init the app
    angular.bootstrap(document, [app.applicationModuleName]);
  }
}(ApplicationConfiguration));
<commit_msg>Loading change state<commit_after>(function (app) {
  'use strict';

  // Start by defining the main module and adding the module dependencies
  angular
    .module(app.applicationModuleName, app.applicationModuleVendorDependencies);

  // Setting HTML5 Location Mode
  angular
    .module(app.applicationModuleName)
    .config(bootstrapConfig);

  // Setting HTML5 Location Mode
  angular
    .module(app.applicationModuleName)
    .run(runBlock);

  bootstrapConfig.$inject = ['$compileProvider', '$locationProvider', '$httpProvider', '$logProvider'];

  function bootstrapConfig($compileProvider, $locationProvider, $httpProvider, $logProvider) {
    $locationProvider.html5Mode({
      enabled: true,
      requireBase: false
    }).hashPrefix('!');

    $httpProvider.interceptors.push('authInterceptor');

    // Disable debug data for production environment
    // @link https://docs.angularjs.org/guide/production
    $compileProvider.debugInfoEnabled(app.applicationEnvironment !== 'production');
    $logProvider.debugEnabled(app.applicationEnvironment !== 'production');
  }

  // Then define the init function for starting up the application
  angular.element(document).ready(init);

  function init() {
    // Fixing facebook bug with redirect
    if (window.location.hash && window.location.hash === '#_=_') {
      if (window.history && history.pushState) {
        window.history.pushState('', document.title, window.location.pathname);
      } else {
        // Prevent scrolling by storing the page's current scroll offset
        var scroll = {
          top: document.body.scrollTop,
          left: document.body.scrollLeft
        };
        window.location.hash = '';
        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scroll.top;
        document.body.scrollLeft = scroll.left;
      }
    }

    // Then init the app
    angular.bootstrap(document, [app.applicationModuleName]);
  }

  runBlock.$inject = ['$rootScope', '$timeout'];

  function runBlock($rootScope, $timeout) {
    // Activate loading indicator
    var stateChangeStartEvent = $rootScope.$on('$stateChangeStart', function () {
      $rootScope.loadingProgress = true;
    });

    // De-activate loading indicator
    var stateChangeSuccessEvent = $rootScope.$on('$stateChangeSuccess', function () {
      $timeout(function () {
        $rootScope.loadingProgress = false;
      });
    });

    // Cleanup
    $rootScope.$on('$destroy', function () {
      stateChangeStartEvent();
      stateChangeSuccessEvent();
    });
  }

}(ApplicationConfiguration));
<|endoftext|>


<commit_before>//__BEGIN_LICENSE__
// Copyright (c) 2015, United States Government, as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All rights reserved.
//
// The xGDS platform is 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.
//__END_LICENSE__

$(function() {

    function getSimState(sim) {
        return {
            elapsedTimeSeconds: sim.getElapsedTimeSeconds(),
            distanceTraveledMeters: sim.getDistanceTraveledMeters()
        };
    }

    function getSimInfo(sim, startState) {
        var currentState = getSimState(sim);
        return _.extend({}, startState, {
            deltaTimeSeconds: currentState.elapsedTimeSeconds -
                startState.elapsedTimeSeconds,
            deltaDistanceMeters: currentState.distanceTraveledMeters -
                startState.distanceTraveledMeters
        });
    }

    function setSimInfo(sim, object, startState) {
    	var newSimInfo = getSimInfo(sim, startState);
    	if (!_.isUndefined(object._simInfo)){
    		if (JSON.stringify(newSimInfo) === JSON.stringify(object._simInfo)){
    			return; // has not changed
    		}
    	}
        object._simInfo = newSimInfo;
        object.trigger('change');
    }

    app.simulatePlan = function() {
        if (app.State.disableSimulate)
            return; // don't simulate while we simulate

        app.State.disableSimulate = true;
        app.Actions.disable();
        console.log('----SIMULATING PLAN----');
        var sim = new app.Simulator();
        var plan = app.currentPlan;
        if (plan.get('sequence').length == 0) {
            // no stations means we don't simulate
            setSimInfo(sim, plan, getSimState(sim));
            app.State.disableSimulate = false;
            app.Actions.enable();
            return;
        }

        var prePlanSimState = getSimState(sim);
        sim.startPlan(plan);

        var context = {
            plan: plan
        };
        plan.get('sequence').each(function(pathElement, i, sequence) {
            var ctx = _.extend({}, context); // make a copy
            var prePathElementSimState = getSimState(sim);

            var type = pathElement.get('type');
            if (type == 'Station') {
                sim.startStation(pathElement, ctx);
            } else if (type == 'Segment') {
                ctx.nextStation = sequence[i + 1];
                sim.startSegment(pathElement, ctx);
            } else {
                throw 'Invalid PathElement type.';
            }

            pathElement.get('commands').each(function(command) {
                var preCommandSimState = getSimState(sim);
                sim.executeCommand(command);
                setSimInfo(sim, command, preCommandSimState);
            });

            if (type == 'Station') {
                sim.endStation(pathElement, ctx);
            } else if (type == 'Segment') {
                sim.endSegment(pathElement, ctx);
            } else {
                throw 'How did you even get here?';
            }

            setSimInfo(sim, pathElement, prePathElementSimState);

        });

        sim.endPlan(plan);
        setSimInfo(sim, plan, prePlanSimState);
        app.Actions.enable();
        app.State.disableSimulate = false;
        console.log('----DONE SIMULATING PLAN----');
        app.vent.trigger('updatePlanDuration', app.currentPlan._simInfo.deltaTimeSeconds);
        if (app.State.stationSelected != undefined){
        	var stationStartTime = app.getStartTime().add(app.State.stationSelected._simInfo.elapsedTimeSeconds, 's');
        	app.vent.trigger('playback:setCurrentTime', stationStartTime);
        }
    };

    function renderSimState(plan) {
        output = '
 \n';
        output = output + getRow('id,dt,t,dd,d'.split(','), 'th');
        output = output + getItemRow(plan);
        plan.get('sequence').each(function(item) {
            output = output + getItemRow(item);
            item.get('commands').each(function(command) {
                output = output + getItemRow(command);
            });
        });
        output = output + '
';
        return output;
    }

    function getRow(list, tag) {
        if (tag == undefined)
            tag = 'td';
        var ths = _.map(list, function(v) {
            return '<' + tag + '>' + v + '</' + tag + '>';
        });
        return '
' + ths.join('') + '
';
    }

    function getItemRow(item) {
        var si = item._simInfo;
        var infoArr = [item.get('id'), si.deltaTimeSeconds,
                       si.elapsedTimeSeconds, si.deltaDistanceMeters,
                       si.distanceTraveledMeters];
        return getRow(infoArr);
    }

    window.debugSim = function() {
        app.simulatePlan();
        var html = renderSimState(app.currentPlan);
        $('body').append($(html));
    };

});
<commit_msg>removed debug printouts<commit_after>//__BEGIN_LICENSE__
// Copyright (c) 2015, United States Government, as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All rights reserved.
//
// The xGDS platform is 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.
//__END_LICENSE__

$(function() {

    function getSimState(sim) {
        return {
            elapsedTimeSeconds: sim.getElapsedTimeSeconds(),
            distanceTraveledMeters: sim.getDistanceTraveledMeters()
        };
    }

    function getSimInfo(sim, startState) {
        var currentState = getSimState(sim);
        return _.extend({}, startState, {
            deltaTimeSeconds: currentState.elapsedTimeSeconds -
                startState.elapsedTimeSeconds,
            deltaDistanceMeters: currentState.distanceTraveledMeters -
                startState.distanceTraveledMeters
        });
    }

    function setSimInfo(sim, object, startState) {
    	var newSimInfo = getSimInfo(sim, startState);
    	if (!_.isUndefined(object._simInfo)){
    		if (JSON.stringify(newSimInfo) === JSON.stringify(object._simInfo)){
    			return; // has not changed
    		}
    	}
        object._simInfo = newSimInfo;
        object.trigger('change');
    }

    app.simulatePlan = function() {
        if (app.State.disableSimulate)
            return; // don't simulate while we simulate

        app.State.disableSimulate = true;
        app.Actions.disable();
        var sim = new app.Simulator();
        var plan = app.currentPlan;
        if (plan.get('sequence').length == 0) {
            // no stations means we don't simulate
            setSimInfo(sim, plan, getSimState(sim));
            app.State.disableSimulate = false;
            app.Actions.enable();
            return;
        }

        var prePlanSimState = getSimState(sim);
        sim.startPlan(plan);

        var context = {
            plan: plan
        };
        plan.get('sequence').each(function(pathElement, i, sequence) {
            var ctx = _.extend({}, context); // make a copy
            var prePathElementSimState = getSimState(sim);

            var type = pathElement.get('type');
            if (type == 'Station') {
                sim.startStation(pathElement, ctx);
            } else if (type == 'Segment') {
                ctx.nextStation = sequence[i + 1];
                sim.startSegment(pathElement, ctx);
            } else {
                throw 'Invalid PathElement type.';
            }

            pathElement.get('commands').each(function(command) {
                var preCommandSimState = getSimState(sim);
                sim.executeCommand(command);
                setSimInfo(sim, command, preCommandSimState);
            });

            if (type == 'Station') {
                sim.endStation(pathElement, ctx);
            } else if (type == 'Segment') {
                sim.endSegment(pathElement, ctx);
            } else {
                throw 'How did you even get here?';
            }

            setSimInfo(sim, pathElement, prePathElementSimState);

        });

        sim.endPlan(plan);
        setSimInfo(sim, plan, prePlanSimState);
        app.Actions.enable();
        app.State.disableSimulate = false;
        app.vent.trigger('updatePlanDuration', app.currentPlan._simInfo.deltaTimeSeconds);
        if (app.State.stationSelected != undefined){
        	var stationStartTime = app.getStartTime().add(app.State.stationSelected._simInfo.elapsedTimeSeconds, 's');
        	app.vent.trigger('playback:setCurrentTime', stationStartTime);
        }
    };

    function renderSimState(plan) {
        output = '
 \n';
        output = output + getRow('id,dt,t,dd,d'.split(','), 'th');
        output = output + getItemRow(plan);
        plan.get('sequence').each(function(item) {
            output = output + getItemRow(item);
            item.get('commands').each(function(command) {
                output = output + getItemRow(command);
            });
        });
        output = output + '
';
        return output;
    }

    function getRow(list, tag) {
        if (tag == undefined)
            tag = 'td';
        var ths = _.map(list, function(v) {
            return '<' + tag + '>' + v + '</' + tag + '>';
        });
        return '
' + ths.join('') + '
';
    }

    function getItemRow(item) {
        var si = item._simInfo;
        var infoArr = [item.get('id'), si.deltaTimeSeconds,
                       si.elapsedTimeSeconds, si.deltaDistanceMeters,
                       si.distanceTraveledMeters];
        return getRow(infoArr);
    }

    window.debugSim = function() {
        app.simulatePlan();
        var html = renderSimState(app.currentPlan);
        $('body').append($(html));
    };

});
<|endoftext|>


<commit_before>/* jshint loopfunc: true */
/*
 * 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.
 */
'use strict';

angular.module('zeppelinWebApp').controller('CredentialCtrl', function($scope, $route, $routeParams, $location, $rootScope,
                                                                         $http, baseUrlSrv) {
  $scope._ = _;

  $scope.credentialEntity = '';
  $scope.credentialUsername = '';
  $scope.credentialPassword = '';

  $scope.updateCredentials = function() {
    $http.put(baseUrlSrv.getRestApiBase() + '/credential',
      { 'entity': $scope.credentialEntity,
        'username': $scope.credentialUsername,
        'password': $scope.credentialPassword
      } ).
    success(function (data, status, headers, config) {
      alert('Successfully saved credentials');
      $scope.credentialEntity = '';
      $scope.credentialUsername = '';
      $scope.credentialPassword = '';
      console.log('Success %o %o', status, data.message);
    }).
    error(function (data, status, headers, config) {
      alert('Error saving credentials');
      console.log('Error %o %o', status, data.message);
    });
  };

});
<commit_msg>BugFix-blocking of blank values insertion on the Credential page.<commit_after>/* jshint loopfunc: true */
/*
 * 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.
 */
'use strict';

angular.module('zeppelinWebApp').controller('CredentialCtrl', function($scope, $route, $routeParams, $location, $rootScope,
                                                                         $http, baseUrlSrv) {
  $scope._ = _;

  $scope.credentialEntity = '';
  $scope.credentialUsername = '';
  $scope.credentialPassword = '';

  $scope.updateCredentials = function() {
    if (_.isEmpty($scope.credentialEntity.trim()) ||
        _.isEmpty($scope.credentialUsername.trim())) {
      BootstrapDialog.alert({
        closable: true,
        message: 'Username \\ Entity can not be empty.'
      });
      return;
    }

    $http.put(baseUrlSrv.getRestApiBase() + '/credential',
      { 'entity': $scope.credentialEntity,
        'username': $scope.credentialUsername,
        'password': $scope.credentialPassword
      } ).
    success(function (data, status, headers, config) {
      BootstrapDialog.alert({
        closable: true,
        message: 'Successfully saved credentials.'
      });
      $scope.credentialEntity = '';
      $scope.credentialUsername = '';
      $scope.credentialPassword = '';
      console.log('Success %o %o', status, data.message);
    }).
    error(function (data, status, headers, config) {
      alert('Error saving credentials');
      console.log('Error %o %o', status, data.message);
    });
  };

});
<|endoftext|>


<commit_before>import macro from 'vtk.js/Sources/macro';
import vtkPolyData from 'vtk.js/Sources/Common/DataModel/PolyData';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkMath from 'vtk.js/Sources/Common/Core/Math';

import atomElem from 'vtk.js/Utilities/XMLConverter/chemistry/elements.json';

const { vtkErrorMacro, vtkDebugMacro } = macro;

// ----------------------------------------------------------------------------
// Globals
// ----------------------------------------------------------------------------

const ATOMS = {};
atomElem.atoms.forEach((a) => {
  ATOMS[a.atomicNumber] = a;
});

// ----------------------------------------------------------------------------
// vtkMoleculeToRepresentation methods
// ----------------------------------------------------------------------------

function vtkMoleculeToRepresentation(publicAPI, model) {
  const bondPositionData = [];
  const bondScaleData = [];
  const bondOrientationData = [];

  // Set our className
  model.classHierarchy.push('vtkMoleculeToRepresentation');

  function addBond(position, orientation, length, radius = model.bondRadius) {
    bondScaleData.push(length);
    bondScaleData.push(radius);

    bondOrientationData.push(orientation[0]);
    bondOrientationData.push(orientation[1]);
    bondOrientationData.push(orientation[2]);

    bondPositionData.push(position[0]);
    bondPositionData.push(position[1]);
    bondPositionData.push(position[2]);
  }

  publicAPI.requestData = (inData, outData) => {
    // input
    const moleculedata = inData[0];

    if (!moleculedata) {
      vtkErrorMacro('Invalid or missing input');
      return 1;
    }

    // output
    const SphereData = vtkPolyData.newInstance();
    const StickData = vtkPolyData.newInstance();

    // Fetch from input molecule data
    let numPts = 0;
    let numBonds = 0;
    let pointsArray = null;
    let atomicNumber = null;
    let bondIndex = null;
    let bondOrder = null;

    if (moleculedata.getAtoms()) {
      if (moleculedata.getAtoms().coords !== undefined) {
        if (moleculedata.getAtoms().coords['3d'] !== undefined) {
          pointsArray = moleculedata.getAtoms().coords['3d'];
          numPts = pointsArray.length / 3;
        }
      }
      if (moleculedata.getAtoms().elements !== undefined) {
        if (moleculedata.getAtoms().elements.number !== undefined) {
          atomicNumber = moleculedata.getAtoms().elements.number;
        }
      }
    }
    if (moleculedata.getBonds()) {
      if (moleculedata.getBonds().connections !== undefined) {
        if (moleculedata.getBonds().connections.index !== undefined) {
          bondIndex = moleculedata.getBonds().connections.index;
          numBonds = bondIndex.length / 2;
        }
      }
      if (moleculedata.getBonds().order !== undefined) {
        bondOrder = moleculedata.getBonds().order;
      }
    }

    const pointsData = [];
    const scaleData = [];
    const colorData = [];

    const radiusArray = [];
    const covalentArray = [];
    const colorArray = [];

    vtkDebugMacro('Checking for bonds with tolerance ', model.tolerance);

    // go through each points and fill from elements.json
    /* eslint-disable no-continue */
    let ptsIdx = 0;
    for (let i = 0; i < numPts; i++) {
      // fetch from elements.json
      if (atomicNumber) {
        radiusArray.push(ATOMS[atomicNumber[i]][model.radiusType]);
        covalentArray.push(ATOMS[atomicNumber[i]].radiusCovalent);
        colorArray.push(ATOMS[atomicNumber[i]].elementColor[0]);
        colorArray.push(ATOMS[atomicNumber[i]].elementColor[1]);
        colorArray.push(ATOMS[atomicNumber[i]].elementColor[2]);
      }

      // skip atoms specified by hideElements
      // model.hideHydrogen = false; // show hydrogen
      if (model.hideElements.includes(ATOMS[atomicNumber[i]].id)) {
        continue;
      }

      // points
      ptsIdx = i * 3;
      pointsData.push(pointsArray[ptsIdx]);
      pointsData.push(pointsArray[ptsIdx + 1]);
      pointsData.push(pointsArray[ptsIdx + 2]);

      // radius
      if (radiusArray) {
        scaleData.push(radiusArray[i] * model.atomicRadiusScaleFactor);
      }

      // colors
      if (colorArray) {
        ptsIdx = i * 3;
        colorData.push(colorArray[ptsIdx] * 255);
        colorData.push(colorArray[ptsIdx + 1] * 255);
        colorData.push(colorArray[ptsIdx + 2] * 255);
      }
    }

    // if we don't have Bonds provided
    // we fill up a bondIndex and a bondOrder
    if (!bondIndex) {
      bondIndex = [];
      bondOrder = [];
      // default bond display
      /* eslint-disable no-continue */
      for (let i = 0; i < numPts; i++) {
        for (let j = i + 1; j < numPts; j++) {
          const cutoff = covalentArray[i] + covalentArray[j] + model.tolerance;
          const jPtsIdx = j * 3;
          const iPtsIdx = i * 3;
          const diff = [
            pointsArray[jPtsIdx],
            pointsArray[jPtsIdx + 1],
            pointsArray[jPtsIdx + 2],
          ];
          diff[0] -= pointsArray[iPtsIdx];
          diff[1] -= pointsArray[iPtsIdx + 1];
          diff[2] -= pointsArray[iPtsIdx + 2];

          if (
            Math.abs(diff[0]) > cutoff ||
            Math.abs(diff[1]) > cutoff ||
            Math.abs(diff[2]) > cutoff
          ) {
            continue;
          }

          // Check radius and add bond if needed
          const cutoffSq = cutoff * cutoff;
          const diffsq =
            diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];
          if (diffsq < cutoffSq && diffsq > 0.1) {
            // appendBond between i and j
            bondIndex.push(i);
            bondIndex.push(j);
            bondOrder.push(1);
          }
        }
      }
      numBonds = bondIndex.length / 2;
    }

    // now we have the bonds, draw them
    for (let index = 0; index < numBonds; index++) {
      // appendBond between i and j
      const i = bondIndex[index * 2];
      const j = bondIndex[index * 2 + 1];

      // Do not append if i or j belong to element to not display
      if (
        model.hideElements.includes(ATOMS[atomicNumber[i]].id) ||
        model.hideElements.includes(ATOMS[atomicNumber[j]].id)
      ) {
        continue;
      }

      const jPtsIdx = j * 3;
      const iPtsIdx = i * 3;
      const diff = [
        pointsArray[jPtsIdx],
        pointsArray[jPtsIdx + 1],
        pointsArray[jPtsIdx + 2],
      ];
      diff[0] -= pointsArray[iPtsIdx];
      diff[1] -= pointsArray[iPtsIdx + 1];
      diff[2] -= pointsArray[iPtsIdx + 2];
      const diffsq = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];

      const radiusJsq =
        radiusArray[j] *
        model.atomicRadiusScaleFactor *
        radiusArray[j] *
        model.atomicRadiusScaleFactor;
      const radiusIsq =
        radiusArray[i] *
        model.atomicRadiusScaleFactor *
        radiusArray[i] *
        model.atomicRadiusScaleFactor;
      let bondDelta = (2 + model.deltaBondFactor) * model.bondRadius; // distance between 2 bonds

      // scale bonds if total distance from bonds is bigger than 2r*factor with r = min(r_i, r_j)
      const r = Math.min(
        radiusArray[i] * model.atomicRadiusScaleFactor,
        radiusArray[j] * model.atomicRadiusScaleFactor
      );
      const t = (bondOrder[index] - 1) * bondDelta + 2 * model.bondRadius;
      if (t > 2 * r * 0.6) {
        model.bondRadius *= 2 * r * 0.6 / t;
        // recompute bondDelta
        bondDelta = (2 + model.deltaBondFactor) * model.bondRadius; // distance between 2 bonds
      }

      // Display multiple bond
      // loop such as 0 11 22 if odd order / 00 11 22 33 if even order
      // To make:     0 22 44 66 88 ...      11 33 55 77 ....
      // because the offset has to be:
      // (with bd= bondDelta. Note the minus is added just before creating bondPos)
      //   - odd order: 0 2bd/2 -2bd/2 4bd/2 -4bd/2 ...
      //   - even order:  1bd/2 -1bd/2 3bd/2 -3bd/2 ...
      // Then, to transform loop to offset we have:
      //   - odd order: x * 2 <=> x * 2 + 1 - 1
      //   - even order: x * 2 + 1
      // (with x the loop <=> floor(k/2))
      const oddOrEven = bondOrder[index] % 2; // zero if even order / one if odd order
      for (let k = oddOrEven; k < bondOrder[index] + oddOrEven; k++) {
        // dist from center to bond depending of number of bond
        let offset = (Math.floor(k / 2) * 2 + 1 - oddOrEven) * bondDelta / 2;

        // offset between center of SphereJ (resp. SphereI) and the start of the bond
        const offsetJ = Math.sqrt(radiusJsq - (model.bondRadius + offset) ** 2);
        const offsetI = Math.sqrt(radiusIsq - (model.bondRadius + offset) ** 2);
        const vectUnitJI = [
          diff[0] / Math.sqrt(diffsq),
          diff[1] / Math.sqrt(diffsq),
          diff[2] / Math.sqrt(diffsq),
        ];
        const vectUnitJIperp = [0, 0, 0];
        // Search perp to vectUnitJI: find axis != 0 to create vectUnitJIperp such as dot(vectUnitJIperp,vectUnitJI) = 0
        for (let coord = 0; coord < 3; coord++) {
          if (Math.abs(vectUnitJI[coord]) < 0.000001) {
            continue;
          }
          vectUnitJIperp[coord] =
            -(
              vectUnitJI[(coord + 2) % 3] * vectUnitJI[(coord + 2) % 3] +
              vectUnitJI[(coord + 1) % 3] * vectUnitJI[(coord + 1) % 3]
            ) / vectUnitJI[coord];
          vectUnitJIperp[(coord + 1) % 3] = vectUnitJI[(coord + 1) % 3];
          vectUnitJIperp[(coord + 2) % 3] = vectUnitJI[(coord + 2) % 3];
          vtkMath.normalize(vectUnitJIperp);
          break;
        }

        offset *= -(1 ** (k % 2));
        const bondPos = [
          pointsArray[jPtsIdx] -
            (offsetJ - offsetI) * vectUnitJI[0] / 2.0 -
            diff[0] / 2.0 +
            offset * vectUnitJIperp[0],
          pointsArray[jPtsIdx + 1] -
            (offsetJ - offsetI) * vectUnitJI[1] / 2.0 -
            diff[1] / 2.0 +
            offset * vectUnitJIperp[1],
          pointsArray[jPtsIdx + 2] -
            (offsetJ - offsetI) * vectUnitJI[2] / 2.0 -
            diff[2] / 2.0 +
            offset * vectUnitJIperp[2],
        ];
        const bondLenght = Math.sqrt(diffsq) - offsetJ - offsetI;

        addBond(bondPos, vectUnitJI, bondLenght);
      }
    }

    SphereData.getPoints().setData(pointsData, 3);

    if (radiusArray) {
      const scales = vtkDataArray.newInstance({
        numberOfComponents: 1,
        values: scaleData,
        name: publicAPI.getSphereScaleArrayName(),
      });
      SphereData.getPointData().addArray(scales);
    }

    if (colorArray) {
      const colors = vtkDataArray.newInstance({
        numberOfComponents: 3,
        values: Uint8Array.from(colorData),
        name: 'colors',
      });
      SphereData.getPointData().setScalars(colors);
    }

    StickData.getPoints().setData(bondPositionData, 3);

    const stickScales = vtkDataArray.newInstance({
      numberOfComponents: 2,
      values: bondScaleData,
      name: 'stickScales',
    });
    StickData.getPointData().addArray(stickScales);

    const orientation = vtkDataArray.newInstance({
      numberOfComponents: 3,
      values: bondOrientationData,
      name: 'orientation',
    });
    StickData.getPointData().addArray(orientation);

    // Update output
    outData[0] = SphereData;
    outData[1] = StickData;

    return 1;
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  sphereScaleArrayName: 'radius',
  tolerance: 0.45,
  atomicRadiusScaleFactor: 0.3,
  bondRadius: 0.075,
  deltaBondFactor: 0.6,
  radiusType: 'radiusVDW',
  hideElements: [],
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);
  macro.setGet(publicAPI, model, [
    'sphereScaleArrayName',
    'radiusType',
    'hideElements',
  ]);
  macro.algo(publicAPI, model, 1, 2);
  vtkMoleculeToRepresentation(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(
  extend,
  'vtkMoleculeToRepresentation'
);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(MoleculeToRepresentation): Properly rewrite pow with **<commit_after>import macro from 'vtk.js/Sources/macro';
import vtkPolyData from 'vtk.js/Sources/Common/DataModel/PolyData';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkMath from 'vtk.js/Sources/Common/Core/Math';

import atomElem from 'vtk.js/Utilities/XMLConverter/chemistry/elements.json';

const { vtkErrorMacro, vtkDebugMacro } = macro;

// ----------------------------------------------------------------------------
// Globals
// ----------------------------------------------------------------------------

const ATOMS = {};
atomElem.atoms.forEach((a) => {
  ATOMS[a.atomicNumber] = a;
});

// ----------------------------------------------------------------------------
// vtkMoleculeToRepresentation methods
// ----------------------------------------------------------------------------

function vtkMoleculeToRepresentation(publicAPI, model) {
  const bondPositionData = [];
  const bondScaleData = [];
  const bondOrientationData = [];

  // Set our className
  model.classHierarchy.push('vtkMoleculeToRepresentation');

  function addBond(position, orientation, length, radius = model.bondRadius) {
    bondScaleData.push(length);
    bondScaleData.push(radius);

    bondOrientationData.push(orientation[0]);
    bondOrientationData.push(orientation[1]);
    bondOrientationData.push(orientation[2]);

    bondPositionData.push(position[0]);
    bondPositionData.push(position[1]);
    bondPositionData.push(position[2]);
  }

  publicAPI.requestData = (inData, outData) => {
    // input
    const moleculedata = inData[0];

    if (!moleculedata) {
      vtkErrorMacro('Invalid or missing input');
      return 1;
    }

    // output
    const SphereData = vtkPolyData.newInstance();
    const StickData = vtkPolyData.newInstance();

    // Fetch from input molecule data
    let numPts = 0;
    let numBonds = 0;
    let pointsArray = null;
    let atomicNumber = null;
    let bondIndex = null;
    let bondOrder = null;

    if (moleculedata.getAtoms()) {
      if (moleculedata.getAtoms().coords !== undefined) {
        if (moleculedata.getAtoms().coords['3d'] !== undefined) {
          pointsArray = moleculedata.getAtoms().coords['3d'];
          numPts = pointsArray.length / 3;
        }
      }
      if (moleculedata.getAtoms().elements !== undefined) {
        if (moleculedata.getAtoms().elements.number !== undefined) {
          atomicNumber = moleculedata.getAtoms().elements.number;
        }
      }
    }
    if (moleculedata.getBonds()) {
      if (moleculedata.getBonds().connections !== undefined) {
        if (moleculedata.getBonds().connections.index !== undefined) {
          bondIndex = moleculedata.getBonds().connections.index;
          numBonds = bondIndex.length / 2;
        }
      }
      if (moleculedata.getBonds().order !== undefined) {
        bondOrder = moleculedata.getBonds().order;
      }
    }

    const pointsData = [];
    const scaleData = [];
    const colorData = [];

    const radiusArray = [];
    const covalentArray = [];
    const colorArray = [];

    vtkDebugMacro('Checking for bonds with tolerance ', model.tolerance);

    // go through each points and fill from elements.json
    /* eslint-disable no-continue */
    let ptsIdx = 0;
    for (let i = 0; i < numPts; i++) {
      // fetch from elements.json
      if (atomicNumber) {
        radiusArray.push(ATOMS[atomicNumber[i]][model.radiusType]);
        covalentArray.push(ATOMS[atomicNumber[i]].radiusCovalent);
        colorArray.push(ATOMS[atomicNumber[i]].elementColor[0]);
        colorArray.push(ATOMS[atomicNumber[i]].elementColor[1]);
        colorArray.push(ATOMS[atomicNumber[i]].elementColor[2]);
      }

      // skip atoms specified by hideElements
      // model.hideHydrogen = false; // show hydrogen
      if (model.hideElements.includes(ATOMS[atomicNumber[i]].id)) {
        continue;
      }

      // points
      ptsIdx = i * 3;
      pointsData.push(pointsArray[ptsIdx]);
      pointsData.push(pointsArray[ptsIdx + 1]);
      pointsData.push(pointsArray[ptsIdx + 2]);

      // radius
      if (radiusArray) {
        scaleData.push(radiusArray[i] * model.atomicRadiusScaleFactor);
      }

      // colors
      if (colorArray) {
        ptsIdx = i * 3;
        colorData.push(colorArray[ptsIdx] * 255);
        colorData.push(colorArray[ptsIdx + 1] * 255);
        colorData.push(colorArray[ptsIdx + 2] * 255);
      }
    }

    // if we don't have Bonds provided
    // we fill up a bondIndex and a bondOrder
    if (!bondIndex) {
      bondIndex = [];
      bondOrder = [];
      // default bond display
      /* eslint-disable no-continue */
      for (let i = 0; i < numPts; i++) {
        for (let j = i + 1; j < numPts; j++) {
          const cutoff = covalentArray[i] + covalentArray[j] + model.tolerance;
          const jPtsIdx = j * 3;
          const iPtsIdx = i * 3;
          const diff = [
            pointsArray[jPtsIdx],
            pointsArray[jPtsIdx + 1],
            pointsArray[jPtsIdx + 2],
          ];
          diff[0] -= pointsArray[iPtsIdx];
          diff[1] -= pointsArray[iPtsIdx + 1];
          diff[2] -= pointsArray[iPtsIdx + 2];

          if (
            Math.abs(diff[0]) > cutoff ||
            Math.abs(diff[1]) > cutoff ||
            Math.abs(diff[2]) > cutoff
          ) {
            continue;
          }

          // Check radius and add bond if needed
          const cutoffSq = cutoff * cutoff;
          const diffsq =
            diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];
          if (diffsq < cutoffSq && diffsq > 0.1) {
            // appendBond between i and j
            bondIndex.push(i);
            bondIndex.push(j);
            bondOrder.push(1);
          }
        }
      }
      numBonds = bondIndex.length / 2;
    }

    // now we have the bonds, draw them
    for (let index = 0; index < numBonds; index++) {
      // appendBond between i and j
      const i = bondIndex[index * 2];
      const j = bondIndex[index * 2 + 1];

      // Do not append if i or j belong to element to not display
      if (
        model.hideElements.includes(ATOMS[atomicNumber[i]].id) ||
        model.hideElements.includes(ATOMS[atomicNumber[j]].id)
      ) {
        continue;
      }

      const jPtsIdx = j * 3;
      const iPtsIdx = i * 3;
      const diff = [
        pointsArray[jPtsIdx],
        pointsArray[jPtsIdx + 1],
        pointsArray[jPtsIdx + 2],
      ];
      diff[0] -= pointsArray[iPtsIdx];
      diff[1] -= pointsArray[iPtsIdx + 1];
      diff[2] -= pointsArray[iPtsIdx + 2];
      const diffsq = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];

      const radiusJsq =
        radiusArray[j] *
        model.atomicRadiusScaleFactor *
        radiusArray[j] *
        model.atomicRadiusScaleFactor;
      const radiusIsq =
        radiusArray[i] *
        model.atomicRadiusScaleFactor *
        radiusArray[i] *
        model.atomicRadiusScaleFactor;
      let bondDelta = (2 + model.deltaBondFactor) * model.bondRadius; // distance between 2 bonds

      // scale bonds if total distance from bonds is bigger than 2r*factor with r = min(r_i, r_j)
      const r = Math.min(
        radiusArray[i] * model.atomicRadiusScaleFactor,
        radiusArray[j] * model.atomicRadiusScaleFactor
      );
      const t = (bondOrder[index] - 1) * bondDelta + 2 * model.bondRadius;
      if (t > 2 * r * 0.6) {
        model.bondRadius *= 2 * r * 0.6 / t;
        // recompute bondDelta
        bondDelta = (2 + model.deltaBondFactor) * model.bondRadius; // distance between 2 bonds
      }

      // Display multiple bond
      // loop such as 0 11 22 if odd order / 00 11 22 33 if even order
      // To make:     0 22 44 66 88 ...      11 33 55 77 ....
      // because the offset has to be:
      // (with bd= bondDelta. Note the minus is added just before creating bondPos)
      //   - odd order: 0 2bd/2 -2bd/2 4bd/2 -4bd/2 ...
      //   - even order:  1bd/2 -1bd/2 3bd/2 -3bd/2 ...
      // Then, to transform loop to offset we have:
      //   - odd order: x * 2 <=> x * 2 + 1 - 1
      //   - even order: x * 2 + 1
      // (with x the loop <=> floor(k/2))
      const oddOrEven = bondOrder[index] % 2; // zero if even order / one if odd order
      for (let k = oddOrEven; k < bondOrder[index] + oddOrEven; k++) {
        // dist from center to bond depending of number of bond
        let offset = (Math.floor(k / 2) * 2 + 1 - oddOrEven) * bondDelta / 2;

        // offset between center of SphereJ (resp. SphereI) and the start of the bond
        const offsetJ = Math.sqrt(radiusJsq - (model.bondRadius + offset) ** 2);
        const offsetI = Math.sqrt(radiusIsq - (model.bondRadius + offset) ** 2);
        const vectUnitJI = [
          diff[0] / Math.sqrt(diffsq),
          diff[1] / Math.sqrt(diffsq),
          diff[2] / Math.sqrt(diffsq),
        ];
        const vectUnitJIperp = [0, 0, 0];
        // Search perp to vectUnitJI: find axis != 0 to create vectUnitJIperp such as dot(vectUnitJIperp,vectUnitJI) = 0
        for (let coord = 0; coord < 3; coord++) {
          if (Math.abs(vectUnitJI[coord]) < 0.000001) {
            continue;
          }
          vectUnitJIperp[coord] =
            -(
              vectUnitJI[(coord + 2) % 3] * vectUnitJI[(coord + 2) % 3] +
              vectUnitJI[(coord + 1) % 3] * vectUnitJI[(coord + 1) % 3]
            ) / vectUnitJI[coord];
          vectUnitJIperp[(coord + 1) % 3] = vectUnitJI[(coord + 1) % 3];
          vectUnitJIperp[(coord + 2) % 3] = vectUnitJI[(coord + 2) % 3];
          vtkMath.normalize(vectUnitJIperp);
          break;
        }

        offset *= (-1) ** (k % 2);
        const bondPos = [
          pointsArray[jPtsIdx] -
            (offsetJ - offsetI) * vectUnitJI[0] / 2.0 -
            diff[0] / 2.0 +
            offset * vectUnitJIperp[0],
          pointsArray[jPtsIdx + 1] -
            (offsetJ - offsetI) * vectUnitJI[1] / 2.0 -
            diff[1] / 2.0 +
            offset * vectUnitJIperp[1],
          pointsArray[jPtsIdx + 2] -
            (offsetJ - offsetI) * vectUnitJI[2] / 2.0 -
            diff[2] / 2.0 +
            offset * vectUnitJIperp[2],
        ];
        const bondLenght = Math.sqrt(diffsq) - offsetJ - offsetI;

        addBond(bondPos, vectUnitJI, bondLenght);
      }
    }

    SphereData.getPoints().setData(pointsData, 3);

    if (radiusArray) {
      const scales = vtkDataArray.newInstance({
        numberOfComponents: 1,
        values: scaleData,
        name: publicAPI.getSphereScaleArrayName(),
      });
      SphereData.getPointData().addArray(scales);
    }

    if (colorArray) {
      const colors = vtkDataArray.newInstance({
        numberOfComponents: 3,
        values: Uint8Array.from(colorData),
        name: 'colors',
      });
      SphereData.getPointData().setScalars(colors);
    }

    StickData.getPoints().setData(bondPositionData, 3);

    const stickScales = vtkDataArray.newInstance({
      numberOfComponents: 2,
      values: bondScaleData,
      name: 'stickScales',
    });
    StickData.getPointData().addArray(stickScales);

    const orientation = vtkDataArray.newInstance({
      numberOfComponents: 3,
      values: bondOrientationData,
      name: 'orientation',
    });
    StickData.getPointData().addArray(orientation);

    // Update output
    outData[0] = SphereData;
    outData[1] = StickData;

    return 1;
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  sphereScaleArrayName: 'radius',
  tolerance: 0.45,
  atomicRadiusScaleFactor: 0.3,
  bondRadius: 0.075,
  deltaBondFactor: 0.6,
  radiusType: 'radiusVDW',
  hideElements: [],
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);
  macro.setGet(publicAPI, model, [
    'sphereScaleArrayName',
    'radiusType',
    'hideElements',
  ]);
  macro.algo(publicAPI, model, 1, 2);
  vtkMoleculeToRepresentation(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(
  extend,
  'vtkMoleculeToRepresentation'
);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>//(function () {

  var devmetrics = {
    init: function (app_id) {
      window.dm_app_id = app_id;
    },
    sendData: function (event_name, user_id, event_tags) {
      var req = new XMLHttpRequest();
      var url = 'http://www.devmetrics.com/api/event';
      url += '?app_id=' + window.dm_app_id;
      url += '&event_name=' + event_name;
      url += '&user_id=' + user_id;
      req.open("GET", url, true);
      req.onreadystatechange = function (e) {
        if (req.readyState === 4) {
          if (req.status === 200) {
            console.log('ok');
          } else {
            var error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
            console.error(error);
          }
        }
      };
      req.send(null);
    },
    userEvent: function (event_name, user_id, event_tags) {
      event_name = event_name.replace(/[\W_]+/g, "_");
      user_id = (user_id || '-1');
      devmetrics.sendData(event_name, user_id, event_tags);
    }
  };

  window.devmetrics = devmetrics;

  /**
   * Send event to localhost api. jQuery is required.
   * @param event string, event name
   * @param eventOptions array, addition event properties
   * @param libOptions array, lib options, like host and token
   */
  function devmetricsEvent(event, eventOptions, libOptions) {
    $.ajax({
      method: 'POST',
      url: '/api/jsevents',
      data: {
        'name': event,
        'options': eventOptions
      },
      success: function (res) {
      },
      error: function (res) {
      },
      dataType: 'json'
    });
  }

  /**
   * @param event_name Metric name, all events with same metric name are aggregated
   * @param user_id optional, User unique identifier, used only for log
   * @param event_tags optional, Additional info, metric dimensions, string or array
   */
  function devmetricsUserEvent(event_name, user_id, event_tags) {
    $.ajax({
      method: 'POST',
      url: '/api/js_userevents',
      data: {
        'event_name': event_name,
        'user_id': user_id,
        'event_tags': event_tags || []
      },
      success: function (res) {
      },
      error: function (res) {
      },
      dataType: 'json'
    });
  }

//});<commit_msg>js lib support web<commit_after>//(function () {

  var devmetrics = {
    init: function (app_id) {
      window.dm_app_id = app_id;
    },
    sendData: function (event_name, user_id, event_tags) {
      var req = new XMLHttpRequest();
      var url = 'http://www.devmetrics.io/api/event';
      url += '?app_id=' + window.dm_app_id;
      url += '&event_name=' + event_name;
      url += '&user_id=' + user_id;
      req.open("GET", url, true);
      req.onreadystatechange = function (e) {
        if (req.readyState === 4) {
          if (req.status === 200) {
            console.log('ok');
          } else {
            var error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
            console.error(error);
          }
        }
      };
      req.send(null);
    },
    userEvent: function (event_name, user_id, event_tags) {
      event_name = event_name.replace(/[\W_]+/g, "_");
      user_id = (user_id || '-1');
      devmetrics.sendData(event_name, user_id, event_tags);
    }
  };

  window.devmetrics = devmetrics;

  /**
   * Send event to localhost api. jQuery is required.
   * @param event string, event name
   * @param eventOptions array, addition event properties
   * @param libOptions array, lib options, like host and token
   */
  function devmetricsEvent(event, eventOptions, libOptions) {
    $.ajax({
      method: 'POST',
      url: '/api/jsevents',
      data: {
        'name': event,
        'options': eventOptions
      },
      success: function (res) {
      },
      error: function (res) {
      },
      dataType: 'json'
    });
  }

  /**
   * @param event_name Metric name, all events with same metric name are aggregated
   * @param user_id optional, User unique identifier, used only for log
   * @param event_tags optional, Additional info, metric dimensions, string or array
   */
  function devmetricsUserEvent(event_name, user_id, event_tags) {
    $.ajax({
      method: 'POST',
      url: '/api/js_userevents',
      data: {
        'event_name': event_name,
        'user_id': user_id,
        'event_tags': event_tags || []
      },
      success: function (res) {
      },
      error: function (res) {
      },
      dataType: 'json'
    });
  }

//});<|endoftext|>


<commit_before>module.exports = {
  displayName: 'unit',
  rootDir: './',
  collectCoverage: true,
  collectCoverageFrom: [
    'src/**/*.{js,jsx}',
    '!**/*.constant.js',
    '!**/*.config.js',
    '!**/*.{integration}.test.{js,jsx}',
    '!**/*.mock.js',
    '!**/index.js',
    '!**/angularModules.js',
    '!src/*.js',
    '!src/.*.js',
  ],
  coverageDirectory: 'coverage',
  coverageThreshold: {
    global: {
      statements: 78,
      branches: 50,
      functions: 70,
      lines: 80,
    },
  },
  coverageReporters: process.env.CI ? ['html', 'text'] : ['lcov'],
  moduleNameMapper: {
    '^.+\\.(css|scss)$': 'identity-obj-proxy',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/test/file-mock.js',
    '\\.(svg)$': '<rootDir>/test/file-svg-mock.js',
  },
  setupFiles: ['raf/polyfill', './test/setup-jest.js'],
  snapshotSerializers: ['enzyme-to-json/serializer'],
  testMatch: ['**/*.test.js?(x)'],
  setupFilesAfterEnv: ['./test/mocks.js'],
  testURL: 'http://localhost:8080/',
  testEnvironment: 'jsdom',
  testPathIgnorePatterns: ['/modules/', '/node_modules/', '/test/'],
  watchPathIgnorePatterns: ['/modules/'],
}
<commit_msg>DP-7094 lowered coverage temporary<commit_after>module.exports = {
  displayName: 'unit',
  rootDir: './',
  collectCoverage: true,
  collectCoverageFrom: [
    'src/**/*.{js,jsx}',
    '!**/*.constant.js',
    '!**/*.config.js',
    '!**/*.{integration}.test.{js,jsx}',
    '!**/*.mock.js',
    '!**/index.js',
    '!**/angularModules.js',
    '!src/*.js',
    '!src/.*.js',
  ],
  coverageDirectory: 'coverage',
  coverageThreshold: {
    global: {
      statements: 78,
      branches: 50,
      functions: 70,
      lines: 78,
    },
  },
  coverageReporters: process.env.CI ? ['html', 'text'] : ['lcov'],
  moduleNameMapper: {
    '^.+\\.(css|scss)$': 'identity-obj-proxy',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/test/file-mock.js',
    '\\.(svg)$': '<rootDir>/test/file-svg-mock.js',
  },
  setupFiles: ['raf/polyfill', './test/setup-jest.js'],
  snapshotSerializers: ['enzyme-to-json/serializer'],
  testMatch: ['**/*.test.js?(x)'],
  setupFilesAfterEnv: ['./test/mocks.js'],
  testURL: 'http://localhost:8080/',
  testEnvironment: 'jsdom',
  testPathIgnorePatterns: ['/modules/', '/node_modules/', '/test/'],
  watchPathIgnorePatterns: ['/modules/'],
}
<|endoftext|>


<commit_before>module.exports = {
	globals: {
		'ts-jest': {
			tsConfig: 'tsconfig.json'
		}
	},
	moduleFileExtensions: [
		'ts',
		'js'
	],
	transform: {
		'^.+\\.(ts|tsx)$': 'ts-jest'
	},
	testMatch: [
		'**/__tests__/**/*.spec.(ts|js)'
	],
	testPathIgnorePatterns: [
		'integrationTests'
	],
	testEnvironment: 'node',
	coverageThreshold: {
		global: {
		  branches: 0,
		  functions: 0,
		  lines: 0,
		  statements: 0
		}
	},
	coverageDirectory: "./coverage/",
	collectCoverage: true
}
<commit_msg>chore: reformat<commit_after>module.exports = {
	globals: {
		'ts-jest': {
			tsConfig: 'tsconfig.json',
		},
	},
	moduleFileExtensions: ['ts', 'js'],
	transform: {
		'^.+\\.(ts|tsx)$': 'ts-jest',
	},
	testMatch: ['**/__tests__/**/*.spec.(ts|js)'],
	testPathIgnorePatterns: ['integrationTests'],
	testEnvironment: 'node',
	coverageThreshold: {
		global: {
			branches: 0,
			functions: 0,
			lines: 0,
			statements: 0,
		},
	},
	coverageDirectory: './coverage/',
	collectCoverage: true,
}
<|endoftext|>


<commit_before>module.exports = {
  preset: "ts-jest",
  roots: ["src/"],
  testPathIgnorePatterns: ["/src/__tests__/helpers/"],
  collectCoverageFrom: ["src/{!(__tests___),}.ts"]
}
<commit_msg>Format jest.config.js<commit_after>module.exports = {
  preset: "ts-jest",
  roots: ["src/"],
  testPathIgnorePatterns: ["/src/__tests__/helpers/"],
  collectCoverageFrom: ["src/{!(__tests___),}.ts"],
}
<|endoftext|>


<commit_before>module.exports = {
  collectCoverage: false, //process.env.NODE_ENV === 'production' ? true : false,
  globals: {
    WITH_NETWORK: false,
    VERSION: 'test',
    NODE_ENV: 'test',
    ROUTER_MODE: 'hash',
    BUILD_TYPE: 'web'
  },
  collectCoverageFrom: ['src/**/*.{js,vue}'],
  coveragePathIgnorePatterns: [
    '.*index.js$',
    'src/components/FaqContents/.*',
    'src/wallets/hardware/.*',
    'src/networks/.*'
  ],
  coverageDirectory: '<rootDir>/tests/unit/coverage',
  moduleFileExtensions: ['js', 'jsx', 'json', 'vue', 'node', 'svg'],
  reporters: ['default', 'jest-skipped-reporter'],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub',
    '^.+\\.jsx?$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/networks$': '<rootDir>/tests/unit/__mocks__/networksMock.js',
    '^@/(.*)$': '<rootDir>/src/$1',
    '^@@/(.*)$': '<rootDir>/tests/unit/$1',
    '^@/tests$': '<rootDir>/tests/index.js',
    '^@/tests/(.*)$': '<rootDir>/tests/$1',
    '\\.worker.js': '<rootDir>/tests/unit/__mocks__/workerMock.js'
  },
  transformIgnorePatterns: [
    'node_modules/(?!(vue-router|bootstrap|register-service-worker|vue-tel-input))'
  ],
  moduleDirectories: ['node_modules'],
  snapshotSerializers: ['jest-serializer-vue'],
  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ],
  testEnvironmentOptions: {},
  testURL: 'http://localhost/',
  setupTestFrameworkScriptFile: '<rootDir>/tests/unit/__mocks__/mocks.js'
};
<commit_msg>reenable coverage<commit_after>module.exports = {
  collectCoverage: true, //process.env.NODE_ENV === 'production' ? true : false,
  globals: {
    WITH_NETWORK: false,
    VERSION: 'test',
    NODE_ENV: 'test',
    ROUTER_MODE: 'hash',
    BUILD_TYPE: 'web'
  },
  collectCoverageFrom: ['src/**/*.{js,vue}'],
  coveragePathIgnorePatterns: [
    '.*index.js$',
    'src/components/FaqContents/.*',
    'src/wallets/hardware/.*',
    'src/networks/.*'
  ],
  coverageDirectory: '<rootDir>/tests/unit/coverage',
  moduleFileExtensions: ['js', 'jsx', 'json', 'vue', 'node', 'svg'],
  reporters: ['default', 'jest-skipped-reporter'],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub',
    '^.+\\.jsx?$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/networks$': '<rootDir>/tests/unit/__mocks__/networksMock.js',
    '^@/(.*)$': '<rootDir>/src/$1',
    '^@@/(.*)$': '<rootDir>/tests/unit/$1',
    '^@/tests$': '<rootDir>/tests/index.js',
    '^@/tests/(.*)$': '<rootDir>/tests/$1',
    '\\.worker.js': '<rootDir>/tests/unit/__mocks__/workerMock.js'
  },
  transformIgnorePatterns: [
    'node_modules/(?!(vue-router|bootstrap|register-service-worker|vue-tel-input))'
  ],
  moduleDirectories: ['node_modules'],
  snapshotSerializers: ['jest-serializer-vue'],
  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ],
  testEnvironmentOptions: {},
  testURL: 'http://localhost/',
  setupTestFrameworkScriptFile: '<rootDir>/tests/unit/__mocks__/mocks.js'
};
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.11.1
var Konnector, async, handleNotification, localization, log;

async = require('async');

handleNotification = require('./notification_handler');

log = require('printit')({
  prefix: null,
  date: true
});

Konnector = require('../models/konnector');

localization = require('./localization_manager');

module.exports = function(konnector, callback) {
  var model, ref;
  if (((ref = konnector.accounts) != null ? ref.length : void 0) > 0 && konnector.isImporting === false) {
    log.info("Run import for " + konnector.slug + ".");
    model = require(path.join('..', 'konnectors', konnector.slug));
    if (model["default"] != null) {
      model = model["default"];
    }
    return konnector["import"](function(err, notifContents) {
      var data, localizationKey;
      if ((err != null) && ((typeof err === 'object' && Object.keys(err).length > 0) || typeof err === String)) {
        log.error(err);
        localizationKey = 'notification import error';
        notifContents = [
          localization.t(localizationKey), {
            name: model.name
          }
        ];
      }
      handleNotification(konnector, notifContents);
      data = {
        lastAutoImport: new Date()
      };
      return konnector.updateAttributes(data, function(err) {
        if (err != null) {
          log.error(err);
        }
        return typeof callback === "function" ? callback() : void 0;
      });
    });
  } else {
    log.info("Connector " + konnector.slug + " is already importing.");
    return typeof callback === "function" ? callback() : void 0;
  }
};
<commit_msg>built<commit_after>// Generated by CoffeeScript 1.11.1
var Konnector, async, handleNotification, localization, log, path;

async = require('async');

handleNotification = require('./notification_handler');

log = require('printit')({
  prefix: null,
  date: true
});

path = require('path');

Konnector = require('../models/konnector');

localization = require('./localization_manager');

module.exports = function(konnector, callback) {
  var model, ref;
  if (((ref = konnector.accounts) != null ? ref.length : void 0) > 0 && konnector.isImporting === false) {
    log.info("Run import for " + konnector.slug + ".");
    model = require(path.join('..', 'konnectors', konnector.slug));
    if (model["default"] != null) {
      model = model["default"];
    }
    return konnector["import"](function(err, notifContents) {
      var data, localizationKey;
      if ((err != null) && ((typeof err === 'object' && Object.keys(err).length > 0) || typeof err === String)) {
        log.error(err);
        localizationKey = 'notification import error';
        notifContents = [
          localization.t(localizationKey), {
            name: model.name
          }
        ];
      }
      handleNotification(konnector, notifContents);
      data = {
        lastAutoImport: new Date()
      };
      return konnector.updateAttributes(data, function(err) {
        if (err != null) {
          log.error(err);
        }
        return typeof callback === "function" ? callback() : void 0;
      });
    });
  } else {
    log.info("Connector " + konnector.slug + " is already importing.");
    return typeof callback === "function" ? callback() : void 0;
  }
};
<|endoftext|>