text:
/**
   @namespace Oryx name space for plugins
   @name ORYX.Plugins
*/
 if(!ORYX.Plugins)
	ORYX.Plugins = new Object();

/**
 * This plugin provides methodes to layout the choreography diagrams of BPMN 2.0.
 *
 * @class ORYX.Plugins.Bpmn2_0Choreography
 * @extends ORYX.Plugins.AbstractPlugin
 * @param {Object} facade
 * 		The facade of the Editor
 */
ORYX.Plugins.Bpmn2_0Choreography = {

	/**
	 *	Constructor
	 *	@param {Object} Facade: The Facade of the Editor
	 */
	construct: function(facade) {
		this.facade = facade;

		/* Register on event ORYX.CONFIG.EVENT_STENCIL_SET_LOADED and ensure that
		 * the stencil set extension is loaded.
		 */
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_STENCIL_SET_LOADED,
										this.handleStencilSetLoaded.bind(this));

		/**
		 * FF 3.0 Bugfixing: Check if all events are loaded
		 */
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LOADED, function(){
			if (!this._eventsRegistered) {
				this.handleStencilSetLoaded({});
				this.afterLoad();
			}
		}.bind(this));

		this.participantSize = 20;
		this.extensionSizeForMarker = 10;
		this.choreographyTasksMeta = new Hash();

		/* Disable the layout callback until the diagram is loaded. */
		this._isLayoutEnabled = false;
	},

	/**
	 * Check if the 'http://oryx-editor.org/stencilsets/extensions/bpmn2.0choreography#'
	 * stencil set extension is loaded and thus register or unregisters on the
	 * appropriated events.
	 */
	handleStencilSetLoaded : function(event) {

		/* Enable layout callback */
		if(event.lazyLoaded) {
			this._isLayoutEnabled = true;
		}

		this.registerPluginOnEvents();
	},

	/**
	 * Register this plugin on the events.
	 */
	registerPluginOnEvents: function() {
		this._eventsRegistered = true;
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_PROPWINDOW_PROP_CHANGED, this.handlePropertyChanged.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SELECTION_CHANGED, this.addParticipantsOnCreation.bind(this));
		this.facade.registerOnEvent('layout.bpmn2_0.choreography.task', this.handleLayoutChoreographyTask.bind(this));
		this.facade.registerOnEvent('layout.bpmn2_0.choreography.subprocess.expanded', this.handleLayoutChoreographySubprocessExpanded.bind(this));
		this.facade.registerOnEvent('layout.bpmn2_0.choreography.subprocess.collapsed', this.handleLayoutChoreographySubprocessCollapsed.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LOADED, this.afterLoad.bind(this));

//		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_PROPERTY_CHANGED, this.handlePropertyChanged.bind(this));
	},

	/**
	 * Unregisters this plugin from the events.
	 */
	unregisterPluginOnEvents: function() {
//		this.facade.unregisterOnEvent(ORYX.CONFIG.EVENT_PROPWINDOW_PROP_CHANGED, this.handlePropertyChanged.bind(this));
		//this.facade.unregisterOnEvent(ORYX.CONFIG.EVENT_SHAPEADDED, this.addParticipantsOnCreation.bind(this));
//		this.facade.unregisterOnEvent('layout.bpmn2_0.choreography.task', this.handleLayoutChoreographyTask.bind(this));
//		this.facade.unregisterOnEvent('layout.bpmn2_0.choreography.subprocess.expanded', this.handleLayoutChoreographySubprocessExpanded.bind(this));
//		this.facade.unregisterOnEvent('layout.bpmn2_0.choreography.subprocess.collapsed', this.handleLayoutChoreographySubprocessCollapsed.bind(this));
		this.facade.unregisterOnEvent(ORYX.CONFIG.EVENT_LOADED, this.afterLoad.bind(this));
	},

	/**
	 * Init the meta values for the layout mechanism of the choreography task
	 * and enables the layout callback
	 *
	 * @param {Object} event
	 * 		The event object
	 */
	afterLoad : function(event) {

		//if(this._isLayoutEnabled) {return;}
		/* Enable the layout callback for choreography activities */
		this._isLayoutEnabled = true;

		/* Initialize layout meta values for each choreography task */
		this.facade.getCanvas().getChildNodes(true).each(function(shape){
			if (!(shape.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyTask" ||
				shape.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographySubprocessCollapsed" ||
				shape.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographySubprocessExpanded")) {
				return;
			}

			var participantsOnTop = new Array();
			var participantsOnBottom = new Array();

			var choreographyTaskMeta = this.addOrGetChoreographyTaskMeta(shape);

			/* Get participants */
			var participants = shape.getChildNodes(false).findAll(function(node) {
				return node.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyParticipant";
			});

			/* Sort participants from up to bottom */
			participants = participants.sort(function(a,b) {
				var ay = Math.round(a.absoluteBounds().upperLeft().y);
				var by = Math.round(b.absoluteBounds().upperLeft().y);
				return  ay < by ? -1 : (ay > by ? 1 : 0);
			});

			/* Determine participants on top and bottom side */
			var expectedYValue = 0;
			var participantsExtendedOnTop = 0;
			var participantsExtendedOnBottom = 0;
			participants.each(function(participant) {
				/* Disable Resizing */
				participant.isResizable = false;

				var extended = (participant.properties['oryx-multiple_instance'] === "" ?
						false : participant.properties['oryx-multiple_instance']);
				if(participant.bounds.upperLeft().y == expectedYValue) {
					participantsOnTop.push(participant);
					expectedYValue = participant.bounds.lowerRight().y;
					if (extended) {
						participantsExtendedOnTop++;
					}
				} else {
					/* Participant is member of the bottom band */
					participantsOnBottom.push(participant);
					if (extended) {
						participantsExtendedOnBottom++;
					}
				}
			});

			/* Initialize meta values */
			choreographyTaskMeta.numOfParticipantsOnTop = participantsOnTop.length;
			choreographyTaskMeta.numOfParticipantsOnBottom = participantsOnBottom.length;
			choreographyTaskMeta.numOfParticipantsExtendedOnBottom = participantsExtendedOnBottom;
			choreographyTaskMeta.numOfParticipantsExtendedOnTop = participantsExtendedOnTop;

			choreographyTaskMeta.bottomYStartValue = (participantsOnBottom.first() ?
					participantsOnBottom.first().bounds.upperLeft().y : shape.bounds.height());

			choreographyTaskMeta.topYEndValue = (participantsOnTop.last() ?
					participantsOnTop.last().bounds.lowerRight().y : 0);

			choreographyTaskMeta.center = choreographyTaskMeta.topYEndValue +
				(choreographyTaskMeta.bottomYStartValue - choreographyTaskMeta.topYEndValue) / 2;

			choreographyTaskMeta.oldHeight = shape.bounds.height();
			choreographyTaskMeta.oldBounds = shape.bounds.clone();

			choreographyTaskMeta.topParticipants = participantsOnTop;
			choreographyTaskMeta.bottomParticipants = participantsOnBottom;

			shape.isChanged = true;
			shape.initialParticipantsAdded = true;
		}.bind(this));

		/* Update to force marker positioning */
		this.facade.getCanvas().update();
	},

	/**
	 * Handler for 'layout.bpmn2_0.choreography.subprocess.expanded'
	 * Applies the layout for an expanded subprocess. e.g. positioning of the
	 * text field.
	 *
	 * @param {Object} event
	 * 		The layout event.
	 */
	handleLayoutChoreographySubprocessExpanded : function(event) {
		if(!this._isLayoutEnabled) {return;}

		var choreographyTask = event.shape;
		var choreographyTaskMeta = this.addOrGetChoreographyTaskMeta(choreographyTask);
		var heightDelta = choreographyTask.bounds.height() / choreographyTask._oldBounds.height();

		/* Handle text field position */
		var textField = choreographyTask._labels[choreographyTask.getId() + 'text_name'];
		if(textField) {
			var top = choreographyTaskMeta.topYEndValue + 5;

			/* Consider changed in update cycle */
			if(choreographyTask.isResized && heightDelta) {
				textField.y = top / heightDelta;
			} else {
				textField.y = top;
			}

		}
	},

	/**
	 * Handler for 'layout.bpmn2_0.choreography.subprocess.collapsed'
	 * Applies the layout for a collapsed subprocess.
	 * e.g. plus marker
	 *
	 * @param {Object} event
	 * 		The layout event.
	 */
	handleLayoutChoreographySubprocessCollapsed : function(event) {
		if(!this._isLayoutEnabled) {return;}

		var choreographyTask = event.shape;
		var choreographyTaskMeta = this.addOrGetChoreographyTaskMeta(choreographyTask);

		/* Calculate position of the "plus" marker of the subprocess */
		var plusMarker = choreographyTask._svgShapes.find(function(svgShape) {
			return svgShape.element.id == choreographyTask.getId() + 'plus_marker';
		});

		var plusMarkerBorder = choreographyTask._svgShapes.find(function(svgShape) {
			return svgShape.element.id == choreographyTask.getId() + 'plus_marker_border';
		});

		if(plusMarker && plusMarkerBorder) {
				plusMarker._isYLocked = true;
				plusMarker.y = choreographyTaskMeta.bottomYStartValue - 12;

				plusMarkerBorder._isYLocked = true;
				plusMarkerBorder.y = choreographyTaskMeta.bottomYStartValue - 14;
		}
	},

	/**
	 * When a choreography task is created, two participants automatically will
	 * be added (one initiating and one returning)
	 *
	 * @param {Object} event
	 * 		The ORYX.CONFIG.EVENT_SHAPEADDED event
	 */
	addParticipantsOnCreation: function(event) {
		if(!this._isLayoutEnabled) {return;}

		var choreographyTask = event.elements.findAll(function(shape){
				return 	shape._stencil&&
						!shape.initialParticipantsAdded &&
						(shape.getStencil().id() ===
							"http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyTask" ||
						 shape.getStencil().id() ===
							"http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographySubprocessCollapsed" ||
						 shape.getStencil().id() ===
							"http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographySubprocessExpanded")
			})

		if (choreographyTask.length === 0){
			return;
		}

		// Begin Transaction
		this._isLayoutEnabled = false;

		choreographyTask.each(function(shape){
			shape.initialParticipantsAdded = true;

			if(this.hasParticipants(shape)) {return;}

			/* Insert initial participants */
			var participant1 = {
				type:"http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyParticipant",
				position:{x:0,y:0},
				namespace:shape.getStencil().namespace(),
				parent:shape
			};
			var shapeParticipant1 = this.facade.createShape(participant1);
			shapeParticipant1.setProperty('oryx-initiating', true);
			var propEvent = {
				elements 	: [shapeParticipant1],
				key 		: "oryx-initiating",
				value		: true
			};
			this.handlePropertyChanged(propEvent);

			var participant2 = {
				type:"http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyParticipant",
				position:{x:0,y:shape.bounds.lowerRight().y},
				namespace:shape.getStencil().namespace(),
				parent:shape
			};
			this.facade.createShape(participant2);

		}.bind(this));

		// End Transaction
		this._isLayoutEnabled = true;

		this.facade.getCanvas().update();
		this.facade.setSelection(choreographyTask);
	},

	/**
	 * Returns true if a shape has at least one ChoreographyParticipant
	 * as a children
	 * @param {Object} shape
	 * @return {Boolean}
	 */
	hasParticipants: function(shape){
		return  shape.getChildNodes().any(function(node) {
				return (node.getStencil().id() ===
							"http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyParticipant");
			});
	},

	/**
	 * Initialize the meta data object for the choreography task if necessary and
	 * return it.
	 *
	 * @param {Object} choregraphyTask
	 * 		The choreography task
	 * @return {Object} choreographyTaskMetaData
	 * 		Positioning values to handle child participants.
	 */
	addOrGetChoreographyTaskMeta: function(choreographyTask) {
		if(!this.choreographyTasksMeta[choreographyTask.getId()]) {

			/* Initialize meta values */
			this.choreographyTasksMeta[choreographyTask.getId()] = new Object();
			this.choreographyTasksMeta[choreographyTask.getId()].numOfParticipantsOnTop = 0;
			this.choreographyTasksMeta[choreographyTask.getId()].numOfParticipantsOnBottom = 0;
			this.choreographyTasksMeta[choreographyTask.getId()].numOfParticipantsExtendedOnBottom = 0;
			this.choreographyTasksMeta[choreographyTask.getId()].numOfParticipantsExtendedOnTop = 0;

			this.choreographyTasksMeta[choreographyTask.getId()].bottomYStartValue =
				choreographyTask.bounds.height();
			this.choreographyTasksMeta[choreographyTask.getId()].topYEndValue = 0;
			this.choreographyTasksMeta[choreographyTask.getId()].center =
				choreographyTask.bounds.height() / 2;

			this.choreographyTasksMeta[choreographyTask.getId()].oldHeight =
				choreographyTask.bounds.height();
			this.choreographyTasksMeta[choreographyTask.getId()].oldBounds =
				choreographyTask.bounds.clone();

			/* Ensure the side of participants while resizing */
			this.choreographyTasksMeta[choreographyTask.getId()].topParticipants = new Array();
			this.choreographyTasksMeta[choreographyTask.getId()].bottomParticipants = new Array();

		}
		return this.choreographyTasksMeta[choreographyTask.getId()];
	},

	/**
	 * Adjust the meta values, if the choreography task is resized.
	 *
	 * @param {Object} choreographyTask
	 * @param {Object} choreographyTaskMeta
	 */
	handleResizingOfChoreographyTask: function(choreographyTask, choreographyTaskMeta) {
		if(choreographyTask.bounds.height() == choreographyTaskMeta.oldHeight) {return;}

		/* Ensure that the choreography task is not too small in height */

		var minimumHeight = choreographyTaskMeta.numOfParticipantsOnTop
							* this.participantSize +
							choreographyTaskMeta.numOfParticipantsExtendedOnTop *
							this.extensionSizeForMarker +
							choreographyTaskMeta.numOfParticipantsOnBottom
							* this.participantSize +
							choreographyTaskMeta.numOfParticipantsExtendedOnBottom *
							this.extensionSizeForMarker
							+ 40;
		if(minimumHeight > choreographyTask.bounds.height()) {
			var ul = choreographyTask.bounds.upperLeft();
			var oldUl = choreographyTaskMeta.oldBounds.upperLeft();
			var lr = choreographyTask.bounds.lowerRight();
			var oldLr = choreographyTaskMeta.oldBounds.lowerRight();

			if(ul.y != oldUl.y) {
				/* Resized on top side */
				choreographyTask.bounds.set(ul.x, lr.y - minimumHeight, lr.x, lr.y);
			} else if(lr.y != oldLr.y) {
				/* Resized on bottom side */
				choreographyTask.bounds.set(ul.x, ul.y, lr.x, ul.y + minimumHeight);
			}
		}

		/* Adjust the y coordinate for the starting position of the bottom participants */
		var yAdjustment = choreographyTaskMeta.oldHeight - choreographyTask.bounds.height();
		choreographyTaskMeta.bottomYStartValue -= yAdjustment;

		/* Signals it was resized */
		return true;
	},

	/**
	 * Handler for layouting event 'layout.bpmn2_0.choreography.task'
	 *
	 * @param {Object} event
	 * 		The layout event
	 */
	handleLayoutChoreographyTask: function(event) {
		if(!this._isLayoutEnabled) {return;}

		var choreographyTask = event.shape;
		var isNew = !this.choreographyTasksMeta[choreographyTask.getId()];
		var choreographyTaskMeta = this.addOrGetChoreographyTaskMeta(choreographyTask);

		var isResized = this.handleResizingOfChoreographyTask(choreographyTask, choreographyTaskMeta);

		var oldCountTop = choreographyTaskMeta.numOfParticipantsOnTop;
		var oldCountBottom = choreographyTaskMeta.numOfParticipantsOnBottom;

		/* ------- Handle participants on top side  ------- */

		if(isResized) {
			/* Do not calculate the position of a paraticipant if it was only a resizing */
			var participants = choreographyTaskMeta.topParticipants;
		} else {
			var participants = this.getParticipants(choreographyTask,true,false);

			if(!participants) {return;}
			this.ensureParticipantsParent(choreographyTask, participants);
		}

		var numOfParticipantsExtended = 0;

		/* Put participants into the right position */
		participants.each(function(participant, i) {

			/* Disable resizing by the user interface */
			participant.isResizable = false;

			participant.setProperty('oryx-corners', "None");
			var isExtended = this.setBoundsOfParticipantDependOnProperties(
													participant,
													i,
													numOfParticipantsExtended,
													choreographyTask.bounds.width(),
													0);

			/* Count extended participants */
			if(isExtended) {numOfParticipantsExtended++;}

//			participant.bounds.set(0, i * this.participantSize,
//								choreographyTask.bounds.width(),
//								this.participantSize +  i * this.participantSize);

			/* The first participants gets rounded corners */
			if(i == 0) {
				participant.setProperty('oryx-corners', "Top");
			}

			this.adjustTopBackground(participant);
		}.bind(this));

		/* Resize choreography task to top side */
		var resizeFactor = participants.length -
									choreographyTaskMeta.numOfParticipantsOnTop;
		var resizeFactorExtended = numOfParticipantsExtended -
							choreographyTaskMeta.numOfParticipantsExtendedOnTop;

		var bounds = choreographyTask.bounds;
		var ul = bounds.upperLeft();
		var lr = bounds.lowerRight();

		if (!isNew)
			bounds.set(ul.x,
					ul.y - resizeFactor * this.participantSize
					- resizeFactorExtended * this.extensionSizeForMarker, lr.x, lr.y);

		/* Set new top and bottom border values */
		choreographyTaskMeta.topYEndValue =
							participants.length * this.participantSize
						+	numOfParticipantsExtended * this.extensionSizeForMarker;

		/* Set new meta value for top participant band */
		choreographyTaskMeta.numOfParticipantsExtendedOnTop = numOfParticipantsExtended;
		choreographyTaskMeta.numOfParticipantsOnTop = participants.length;
		choreographyTaskMeta.topParticipants = participants;

		/* ----- Handle participants on bottom side --------- */
		if(isResized) {
			/* Do not calculate the position of a paraticipant if it was only a resizing */
			var participants = choreographyTaskMeta.bottomParticipants;
		} else {
			var participants = this.getParticipants(choreographyTask,false,true);

			if(!participants) {return;}
			this.ensureParticipantsParent(choreographyTask, participants);
		}

		if (isNew){
			choreographyTaskMeta.bottomYStartValue = (bounds.height() -
				(participants.length != 0 ?
					eval(participants.map(function(p){ return this.participantSize + (this.isExtended(p)?this.extensionSizeForMarker:0) }.bind(this)).join("+")) :
					0));
		} else {
			choreographyTaskMeta.bottomYStartValue +=
				resizeFactor * this.participantSize +
				resizeFactorExtended * this.extensionSizeForMarker;
		}

		var bottomStartYValue = choreographyTaskMeta.bottomYStartValue;
		var numOfParticipantsExtended = 0;

		/* Put participants into the right position */
		participants.each(function(participant, i) {

			/* Disable resizing by the user interface */
			participant.isResizable = false;

			participant.setProperty('oryx-corners', "None");

			var isExtendedParticipant =
				this.setBoundsOfParticipantDependOnProperties(participant,
								i,
								numOfParticipantsExtended,
								choreographyTask.bounds.width(),
								bottomStartYValue);

			/* Count extended participants */
			if(isExtendedParticipant) {numOfParticipantsExtended++;}

//			participant.bounds.set(0, bottomStartYValue +
//														 i * this.participantSize,
//								choreographyTask.bounds.width(),
//								bottomStartYValue +
//								this.participantSize +  i * this.participantSize);

			/* The last participants gets rounded corners */
			if(i == participants.length - 1) {
				participant.setProperty('oryx-corners', "Bottom");
			}

			this.adjustTopBackground(participant);

		}.bind(this));

		/* Resize choreography task to top bottom side */

		var resizeFactor = participants.length -
								choreographyTaskMeta.numOfParticipantsOnBottom;
		var resizeFactorExtended = numOfParticipantsExtended -
						choreographyTaskMeta.numOfParticipantsExtendedOnBottom;

		var bounds = choreographyTask.bounds;
		var ul = bounds.upperLeft();
		var lr = bounds.lowerRight();

		if (!isNew)
		bounds.set( ul.x,
					ul.y,
					lr.x,
					lr.y + resizeFactor * this.participantSize
					+ resizeFactorExtended * this.extensionSizeForMarker);

		/* Store new meta values */
		choreographyTaskMeta.numOfParticipantsExtendedOnBottom = numOfParticipantsExtended;
		choreographyTaskMeta.numOfParticipantsOnBottom = participants.length;
		choreographyTaskMeta.bottomParticipants = participants;

		/* Check if participants has changed */
		var participantsHasChanged = 	oldCountTop !== choreographyTaskMeta.numOfParticipantsOnTop ||
										oldCountBottom !==choreographyTaskMeta.numOfParticipantsOnBottom;

		/* Handle positioning of sub elements */
		this.ensureCenterPositionOfMagnets(choreographyTask, isResized, participantsHasChanged);
		this.adjustTextFieldAndMarkerPosition(choreographyTask);

		choreographyTaskMeta.oldHeight = bounds.height();
		choreographyTaskMeta.oldBounds = bounds.clone();

		choreographyTask.minimumSize = {width: 50, height: 40 + ((choreographyTaskMeta.numOfParticipantsOnBottom+choreographyTaskMeta.numOfParticipantsOnTop)*this.participantSize) + ((choreographyTaskMeta.numOfParticipantsExtendedOnBottom+choreographyTaskMeta.numOfParticipantsExtendedOnTop) * this.extensionSizeForMarker)}
	},

	/**
	 * Return TRUE if the participant is extended (has the attribute muliple instance)
	 * @param {ORYX.Core.Node} participant
	 */
	isExtended: function(participant){
		return (!participant || participant.properties['oryx-multiple_instance'] === "" ?
					false : !!participant.properties['oryx-multiple_instance']);
	},

	/**
	 * Resizes the participant depending on value of the multi-instances
	 * property.
	 *
	 * @param {ORYX.Core.Node} participant
	 * 		The concerning participant
	 * @param {Integer} numParticipantsBefore
	 * 		Number of participants before current
	 * @param {Integer} numParticipantsExtendedBefore
	 *		Number of participants extended in size before current
	 * @param {Float} width
	 * 		The width of the participant
	 * @param {Integer} yOffset
	 * 		Offset for the position of the bottom participants
	 */
	setBoundsOfParticipantDependOnProperties: function(	participant,
														numParticipantsBefore,
														numParticipantsExtendedBefore,
														width,
														yOffset) {
		var extended = this.isExtended(participant);
		var ulY = yOffset +
			numParticipantsBefore * this.participantSize +
			numParticipantsExtendedBefore * this.extensionSizeForMarker;
		var lrY = yOffset + this.participantSize +
			numParticipantsBefore * this.participantSize +
			(extended ? (numParticipantsExtendedBefore + 1) * this.extensionSizeForMarker :
				numParticipantsExtendedBefore * this.extensionSizeForMarker);

		participant.bounds.set(	0,
			ulY,
			width,
			lrY);

		/* Is a multi-instance participant */
		return extended;
	},

	/**
	 * Set the y coordinate for the text field and multiple instance marker
	 * position in order to ensure that the text or marker is not hidden
	 * by a participant.
	 *
	 * @param {ORYX.Core.Node} choreographyTask
	 * 		The choreography task.
	 */
	adjustTextFieldAndMarkerPosition: function(choreographyTask) {
		var choreographyTaskMeta = this.addOrGetChoreographyTaskMeta(choreographyTask);
		var heightDelta = choreographyTask.bounds.height() / choreographyTask._oldBounds.height();

		/* Handle text field position */
		var textField = choreographyTask._labels[choreographyTask.getId() + 'text_name'];
		if(textField) {
			var center = choreographyTaskMeta.topYEndValue +
				(choreographyTaskMeta.bottomYStartValue - choreographyTaskMeta.topYEndValue) / 2;

			/* Consider changed in update cycle */
			if(choreographyTask.isResized && heightDelta) {
				textField.y = center / heightDelta;
			} else {
				textField.y = center;
			}

		}

		/* Handle MI and loop marker position */

		/* Loop marker */
		var loopMarker = choreographyTask._svgShapes.find(function(svgShape) {
			return svgShape.element.id == choreographyTask.getId() + 'loop_path';
		});
		if(loopMarker) {
				loopMarker._isYLocked = true;
				loopMarker.y = choreographyTaskMeta.bottomYStartValue - 7;
		}

		/* MI parallel marker */
		var miMarker = choreographyTask._svgShapes.find(function(svgShape) {
			return svgShape.element.id == choreographyTask.getId() + 'mi_path';
		});
		if(miMarker) {
			miMarker._isYLocked = true;
			miMarker.y = choreographyTaskMeta.bottomYStartValue - 11;
		}

		/* MI sequential marker */
		var miSeqMarker = choreographyTask._svgShapes.find(function(svgShape) {
			return svgShape.element.id == choreographyTask.getId() + 'mi_sequential_path';
		});
		if(miSeqMarker) {
			miSeqMarker._isYLocked = true;
			miSeqMarker.y = choreographyTaskMeta.bottomYStartValue - 11;
		}
	},

	/**
	 * The magnets of choreography activity were placed in the middle of both
	 * participant bands.
	 *
	 * @param {ORYX.Core.Node} choreographyTask
	 * 		The choregraphy task containing the magnets
	 * @param {boolean} isResized
	 * 		Flag indicating a resizing of the task
	 * @param {boolean} participantsHasChanged
	 * 		Flag indicating if a new participants has been added or
	 * 		changed the position (e.g.from top to bottom).
	 *
	 */
	ensureCenterPositionOfMagnets: function(choreographyTask, isResized, participantsHasChanged) {
		var choreographyTaskMeta = this.addOrGetChoreographyTaskMeta(choreographyTask);
		var center = choreographyTaskMeta.topYEndValue +
					(choreographyTaskMeta.bottomYStartValue
								- choreographyTaskMeta.topYEndValue) / 2;

		var yAdjustment = center - choreographyTaskMeta.center;

		var heightDelta = choreographyTask.bounds.height() /
							choreographyTaskMeta.oldBounds.height();
		if(!yAdjustment && !heightDelta) {return;}

		/* Find magnets that should be positioned relativly to the center */
		var magnets = choreographyTask.magnets.findAll(function(magnet) {
			return (!magnet.anchorTop && !magnet.anchorBottom)
		});

		/* Move magnets */
		magnets.each(function(magnet) {
			var x = magnet.bounds.center().x;
			var y = (magnet.bounds.center().y + yAdjustment) / heightDelta
			magnet.bounds.centerMoveTo(x,y);
		});

		/* Also move dockers */
		var absoluteTopYEndValue = choreographyTask.absoluteBounds().upperLeft().y
									+ choreographyTaskMeta.topYEndValue;
		var absoluteBottomYStartValue = choreographyTask.absoluteBounds().upperLeft().y
									+ choreographyTaskMeta.bottomYStartValue;
		var dockers = new Array();

		choreographyTask.incoming.each(function(seqFlow) {
			if(!(seqFlow instanceof ORYX.Core.Edge)) {return;}
			var docker = seqFlow.dockers.last();
			if(absoluteTopYEndValue <= docker.bounds.center().y
				&& docker.bounds.center().y <= absoluteBottomYStartValue ) {
				dockers.push(docker);
			}
		});

		choreographyTask.outgoing.each(function(seqFlow) {
			if(!(seqFlow instanceof ORYX.Core.Edge)) {return;}
			var docker = seqFlow.dockers.first();
			if(absoluteTopYEndValue <= docker.bounds.center().y
				&& docker.bounds.center().y <= absoluteBottomYStartValue ) {
				dockers.push(docker);
			}
		});

		if (participantsHasChanged&&choreographyTask.initialParticipantsAdded){
			dockers.each(function(dockerShape) {
				var ref = dockerShape.referencePoint;
				dockerShape.setReferencePoint({x:ref.x,y:(ref.y + yAdjustment) / heightDelta});
			});
		}

		/* Update center */
		choreographyTaskMeta.center = center;
	},

	/**
	 * Ensure that the parent of the participant is the choreography task.
	 *
	 * @param {Object} shape
	 * 		The choreography task
	 * @param {Object} participants
	 * 		The participants
	 */
	ensureParticipantsParent: function(shape, participants) {
		if(!shape || !participants) {return;}

		participants.each(function(participant) {
			if(participant.parent.getId() == shape.getId()) {return;}

			/* Set ChoreographyTask as Parent */
			participant.parent.remove(participant);
			shape.add(participant);
		});
	},

	/**
	 * Returns the participants of a choreography task ordered by theire position.
	 *
	 * @param {Object} shape
	 * 		The choreography task
	 * @param {Object} onTop
	 * 		Flag to get the participants from the top side of the task.
	 * @param {Object} onBottom
	 * 		Flag to get the participants from the bottom side of the task.
	 * @return {Array} participants;
	 * 		The child participants
	 */
	getParticipants: function(shape, onTop, onBottom) {
		if(shape.getStencil().id() !== "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyTask" &&
			shape.getStencil().id() !== "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographySubprocessCollapsed" &&
			shape.getStencil().id() !== "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographySubprocessExpanded") {
			return null;
		}

		var choreographyTaskMeta = this.addOrGetChoreographyTaskMeta(shape);
		var center = shape.absoluteBounds().upperLeft().y +
			 choreographyTaskMeta.topYEndValue +
			(choreographyTaskMeta.bottomYStartValue - choreographyTaskMeta.topYEndValue) / 2;

		/* Get participants of top side */
		var participantsTop = shape.getChildNodes(true).findAll(function(node) {
			return (onTop &&
					node.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyParticipant" &&
					node.absoluteBounds().center().y <= center &&
					this.isParticipantOfShape(shape, node));
		}.bind(this));

		/* Get participants of bottom side */
		var participantsBottom = shape.getChildNodes(true).findAll(function(node) {
			return (onBottom &&
					node.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyParticipant" &&
					node.absoluteBounds().center().y > center &&
					this.isParticipantOfShape(shape, node));
		}.bind(this));

		var participants = participantsTop.concat(participantsBottom);

		participants = participants.sort(function(a,b) {
			var ay = Math.round(a.absoluteBounds().upperLeft().y);
			var by = Math.round(b.absoluteBounds().upperLeft().y);
			return  ay < by ? -1 : (ay > by ? 1 : 0);
		});

		return participants;
	},

	/**
	 * Checks if the participant belongs to the shape. Used to detect choreography
	 * tasks inside an expanded choreography subprocess.
	 *
	 * @param {ORYX.Core.Node} shape
	 * 		The choreography element
	 *
	 * @param {ORYX.Core.Node} participant
	 * 		The participant node
	 *
	 * @return {boolean}
	 * 		True if the participant is a direct child of the shape and is not
	 * 		contained in aother choreography task or subprocess
	 */
	isParticipantOfShape: function(shape, participant) {
		var participantsParent = participant.parent;

		/* Get a non-participant parent of the participant */
		while(participantsParent.getStencil().id() ===
				"http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyParticipant") {
			participantsParent = participantsParent.parent;
		}

		/* The detected parent should be the shape */

		return participantsParent.getId() === shape.getId();
	},

	adjustTopBackground: function(shape){
		var pos = shape.properties["oryx-corners"];
		var bg = $(shape.getId()+"roundedBgRect");
		if (!bg){ return }

		if(pos==="Top") {
			bg.setAttributeNS(null, "fill", "url(#"+shape.getId()+"background_top) white");
		} else {
			var bgColor = shape.properties["oryx-color"];
			bg.setAttributeNS(null, "fill", bgColor);
		}
	},

	/**
	 * PropertyWindow.PropertyChanged Handler
	 *
	 * It sets the correct color of the elements of a participant depending on
	 * either initiating or returning nature.
	 *
	 * @param {Object} event
	 * 		The property changed event
	 */
	handlePropertyChanged: function(event) {
		var shapes = event.elements;
		var propertyKey = event.key || event.name;
		var propertyValue = event.value;

		var changed = false;
		shapes.each(function(shape) {
			if (shape.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0choreography#ChoreographyParticipant" &&
			propertyKey === "oryx-initiating") {

				if (!propertyValue || propertyValue === "false") {
					shape.setProperty("oryx-color", "#acacac");
				}
				else {
					shape.setProperty("oryx-color", "#ffffff");
				}

				changed = true;
			}
		})

		/* Update visualisation if necessary */
		if(changed) {
			this.facade.getCanvas().update();
		}
	}

};

ORYX.Plugins.Bpmn2_0Choreography = ORYX.Plugins.AbstractPlugin.extend(ORYX.Plugins.Bpmn2_0Choreography);


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/api/servicemanagement/v1/servicemanager.proto

package com.google.api.servicemanagement.v1;

public interface SubmitConfigSourceRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.api.servicemanagement.v1.SubmitConfigSourceRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The name of the service.  See the
   * [overview](https://cloud.google.com/service-infrastructure/docs/overview) for naming requirements.  For
   * example: `example.googleapis.com`.
   *

   *
   * string service_name = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The serviceName.
   */
  java.lang.String getServiceName();
  /**
   *
   *
   *

   * Required. The name of the service.  See the
   * [overview](https://cloud.google.com/service-infrastructure/docs/overview) for naming requirements.  For
   * example: `example.googleapis.com`.
   *

   *
   * string service_name = 1 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The bytes for serviceName.
   */
  com.google.protobuf.ByteString getServiceNameBytes();

  /**
   *
   *
   *

   * Required. The source configuration for the service.
   *

   *
   *
   * .google.api.servicemanagement.v1.ConfigSource config_source = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return Whether the configSource field is set.
   */
  boolean hasConfigSource();
  /**
   *
   *
   *

   * Required. The source configuration for the service.
   *

   *
   *
   * .google.api.servicemanagement.v1.ConfigSource config_source = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The configSource.
   */
  com.google.api.servicemanagement.v1.ConfigSource getConfigSource();
  /**
   *
   *
   *

   * Required. The source configuration for the service.
   *

   *
   *
   * .google.api.servicemanagement.v1.ConfigSource config_source = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   */
  com.google.api.servicemanagement.v1.ConfigSourceOrBuilder getConfigSourceOrBuilder();

  /**
   *
   *
   *

   * Optional. If set, this will result in the generation of a
   * `google.api.Service` configuration based on the `ConfigSource` provided,
   * but the generated config and the sources will NOT be persisted.
   *

   *
   * bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];
   *
   * @return The validateOnly.
   */
  boolean getValidateOnly();
}

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.debugger.engine;

import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.jdi.StackFrameProxyImpl;
import com.intellij.debugger.ui.breakpoints.StepIntoBreakpoint;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiMethod;
import com.intellij.util.containers.ContainerUtil;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import com.sun.jdi.event.LocatableEvent;
import org.jetbrains.annotations.NotNull;

/**
 * @author egor
 */
public class LambdaAsyncMethodFilter extends BasicStepMethodFilter {
  private final int myParamNo;
  private final LambdaMethodFilter myMethodFilter;

  public LambdaAsyncMethodFilter(@NotNull PsiMethod callerMethod, int paramNo, LambdaMethodFilter methodFilter) {
    super(callerMethod, methodFilter.getCallingExpressionLines());
    myParamNo = paramNo;
    myMethodFilter = methodFilter;
  }

  @Override
  public int onReached(SuspendContextImpl context, RequestHint hint) {
    try {
      StackFrameProxyImpl proxy = context.getFrameProxy();
      if (proxy != null) {
        Value lambdaReference = ContainerUtil.getOrElse(proxy.getArgumentValues(), myParamNo, null);
        if (lambdaReference instanceof ObjectReference) {
          final SourcePosition pos = myMethodFilter.getBreakpointPosition();
          if (pos != null) {
            Project project = context.getDebugProcess().getProject();
            long lambdaId = ((ObjectReference)lambdaReference).uniqueID();
            StepIntoBreakpoint breakpoint = new LambdaInstanceBreakpoint(project, lambdaId, pos, myMethodFilter);
            ClassInstanceMethodFilter.setUpStepIntoBreakpoint(context, breakpoint, hint);
            return RequestHint.RESUME;
          }
        }
      }
    }
    catch (EvaluateException ignore) {
    }
    return RequestHint.STOP;
  }

  private static class LambdaInstanceBreakpoint extends StepIntoBreakpoint {
    private final long myLambdaId;

    public LambdaInstanceBreakpoint(@NotNull Project project,
                                    long lambdaId,
                                    @NotNull SourcePosition pos,
                                    @NotNull BreakpointStepMethodFilter filter) {
      super(project, pos, filter);
      myLambdaId = lambdaId;
    }

    @Override
    public boolean evaluateCondition(EvaluationContextImpl context, LocatableEvent event) throws EvaluateException {
      if (!super.evaluateCondition(context, event)) {
        return false;
      }

      if (!DebuggerUtilsEx.isLambda(event.location().method())) {
        return false;
      }

      // lambda reference is available in the parent frame
      ObjectReference lambdaReference = null;
      StackFrameProxyImpl parentFrame = context.getSuspendContext().getThread().frame(1);
      if (parentFrame != null) {
        try {
          lambdaReference = parentFrame.thisObject();
        }
        catch (EvaluateException ignore) {
        }
      }
      return lambdaReference != null && lambdaReference.uniqueID() == myLambdaId;
    }
  }
}


text:
require 'test_helper'

class OpenportalTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, Openportal
  end
end


text:
(function () {
    'use strict';

    angular
      .module('app.shell')
      .directive('skNavLink', skNavLink);

    skNavLink.$inject = ['$filter', '$templateRequest', '$compile', '$rootScope', 'baseUrl'];

    function skNavLink($filter, $templateRequest, $compile, $rootScope, baseUrl) {
        var directive = {
            restrict: 'E',
            scope: {
                navLink: '='
            },
            replace: true,
            link: link
        };
        return directive;

        function link(scope, element, attrs) {
            $templateRequest(baseUrl + 'shell/skNavLink.html').then(function (result) {
                scope.navLinks = scope.$parent.navLinks || scope.$parent.$parent.navLinks;
                scope.hasChildren = $filter('filter')(scope.navLinks, {
                    parent: scope.navLink.name
                }).length > 0;

                var template = angular.element(result);

                if (!scope.hasChildren) {
                    template.children(".child-nav-links").remove();
                }

                var el = $compile(template)(scope);
                element.replaceWith(el);
            });

            $rootScope.$on('$routeChangeSuccess', function (event, next, current) {
                if (!scope.navLink.parent && next.$$route) {
                    scope.navLink.isActive = scope.navLink.name === next.$$route.showNav
                                            || scope.navLink.name === next.$$route.parent;
                }
            });
        }
    }
})();


text:
import {Connection} from "../connection/Connection";
import {EntityMetadata} from "../metadata/EntityMetadata";
import {ObjectLiteral} from "../common/ObjectLiteral";
import {QueryRunnerProvider} from "../query-runner/QueryRunnerProvider";
import {Subject} from "../persistence/Subject";
import {RelationMetadata} from "../metadata/RelationMetadata";
import {ColumnMetadata} from "../metadata/ColumnMetadata";
import {QueryBuilder} from "../query-builder/QueryBuilder";

/**
 * Repository for more specific operations.
 */
export class SpecificRepository<Entity extends ObjectLiteral> {

    // -------------------------------------------------------------------------
    // Protected Properties
    // -------------------------------------------------------------------------

    protected queryRunnerProvider: QueryRunnerProvider;

    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------

    constructor(protected connection: Connection,
                protected metadata: EntityMetadata,
                queryRunnerProvider?: QueryRunnerProvider) {

        if (queryRunnerProvider) {
            this.queryRunnerProvider = queryRunnerProvider;
        } else {
            this.queryRunnerProvider = new QueryRunnerProvider(connection.driver);
        }
    }

    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------

    /**
     * Sets given relatedEntityId to the value of the relation of the entity with entityId id.
     * Should be used when you want quickly and efficiently set a relation (for many-to-one and one-to-many) to some entity.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async setRelation(relationName: string, entityId: any, relatedEntityId: any): Promise<void>;

    /**
     * Sets given relatedEntityId to the value of the relation of the entity with entityId id.
     * Should be used when you want quickly and efficiently set a relation (for many-to-one and one-to-many) to some entity.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async setRelation(relationName: ((t: Entity) => string|any), entityId: any, relatedEntityId: any): Promise<void>;

    /**
     * Sets given relatedEntityId to the value of the relation of the entity with entityId id.
     * Should be used when you want quickly and efficiently set a relation (for many-to-one and one-to-many) to some entity.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async setRelation(relationName: string|((t: Entity) => string|any), entityId: any, relatedEntityId: any): Promise<void> {
        const propertyName = this.metadata.computePropertyName(relationName);
        if (!this.metadata.hasRelationWithPropertyName(propertyName))
            throw new Error(`Relation ${propertyName} was not found in the ${this.metadata.name} entity.`);

        const relation = this.metadata.findRelationWithPropertyName(propertyName);
        // if (relation.isManyToMany || relation.isOneToMany || relation.isOneToOneNotOwner)
        //     throw new Error(`Only many-to-one and one-to-one with join column are supported for this operation. ${this.metadata.name}#${propertyName} relation type is ${relation.relationType}`);
        if (relation.isManyToMany)
            throw new Error(`Many-to-many relation is not supported for this operation. Use #addToRelation method for many-to-many relations.`);

        let table: string, values: any = {}, conditions: any = {};
        if (relation.isOwning) {
            table = relation.entityMetadata.table.name;
            values[relation.name] = relatedEntityId;
            conditions[relation.joinColumn.referencedColumn.name] = entityId;
        } else {
            table = relation.inverseEntityMetadata.table.name;
            values[relation.inverseRelation.name] = relatedEntityId;
            conditions[relation.inverseRelation.joinColumn.referencedColumn.name] = entityId;
        }

        const queryRunner = await this.queryRunnerProvider.provide();
        await queryRunner.update(table, values, conditions);
        await this.queryRunnerProvider.release(queryRunner);
    }

    /**
     * Sets given relatedEntityId to the value of the relation of the entity with entityId id.
     * Should be used when you want quickly and efficiently set a relation (for many-to-one and one-to-many) to some entity.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async setInverseRelation(relationName: string, relatedEntityId: any, entityId: any): Promise<void>;

    /**
     * Sets given relatedEntityId to the value of the relation of the entity with entityId id.
     * Should be used when you want quickly and efficiently set a relation (for many-to-one and one-to-many) to some entity.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async setInverseRelation(relationName: ((t: Entity) => string|any), relatedEntityId: any, entityId: any): Promise<void>;

    /**
     * Sets given relatedEntityId to the value of the relation of the entity with entityId id.
     * Should be used when you want quickly and efficiently set a relation (for many-to-one and one-to-many) to some entity.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async setInverseRelation(relationName: string|((t: Entity) => string|any), relatedEntityId: any, entityId: any): Promise<void> {
        const propertyName = this.metadata.computePropertyName(relationName);
        if (!this.metadata.hasRelationWithPropertyName(propertyName))
            throw new Error(`Relation ${propertyName} was not found in the ${this.metadata.name} entity.`);

        const relation = this.metadata.findRelationWithPropertyName(propertyName);
        // if (relation.isManyToMany || relation.isOneToMany || relation.isOneToOneNotOwner)
        //     throw new Error(`Only many-to-one and one-to-one with join column are supported for this operation. ${this.metadata.name}#${propertyName} relation type is ${relation.relationType}`);
        if (relation.isManyToMany)
            throw new Error(`Many-to-many relation is not supported for this operation. Use #addToRelation method for many-to-many relations.`);

        let table: string, values: any = {}, conditions: any = {};
        if (relation.isOwning) {
            table = relation.inverseEntityMetadata.table.name;
            values[relation.inverseRelation.name] = relatedEntityId;
            conditions[relation.inverseRelation.joinColumn.referencedColumn.name] = entityId;
        } else {
            table = relation.entityMetadata.table.name;
            values[relation.name] = relatedEntityId;
            conditions[relation.joinColumn.referencedColumn.name] = entityId;
        }

        const queryRunner = await this.queryRunnerProvider.provide();
        await queryRunner.update(table, values, conditions);
        await this.queryRunnerProvider.release(queryRunner);
    }

    /**
     * Adds a new relation between two entities into relation's many-to-many table.
     * Should be used when you want quickly and efficiently add a relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addToRelation(relationName: string, entityId: any, relatedEntityIds: any[]): Promise<void>;

    /**
     * Adds a new relation between two entities into relation's many-to-many table.
     * Should be used when you want quickly and efficiently add a relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addToRelation(relationName: ((t: Entity) => string|any), entityId: any, relatedEntityIds: any[]): Promise<void>;

    /**
     * Adds a new relation between two entities into relation's many-to-many table.
     * Should be used when you want quickly and efficiently add a relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addToRelation(relationName: string|((t: Entity) => string|any), entityId: any, relatedEntityIds: any[]): Promise<void> {
        const propertyName = this.metadata.computePropertyName(relationName);
        if (!this.metadata.hasRelationWithPropertyName(propertyName))
            throw new Error(`Relation ${propertyName} was not found in the ${this.metadata.name} entity.`);

        const relation = this.metadata.findRelationWithPropertyName(propertyName);
        if (!relation.isManyToMany)
            throw new Error(`Only many-to-many relation supported for this operation. However ${this.metadata.name}#${propertyName} relation type is ${relation.relationType}`);

        const queryRunner = await this.queryRunnerProvider.provide();
        const insertPromises = relatedEntityIds.map(relatedEntityId => {
            const values: any = {};
            if (relation.isOwning) {
                values[relation.junctionEntityMetadata.columns[0].name] = entityId;
                values[relation.junctionEntityMetadata.columns[1].name] = relatedEntityId;
            } else {
                values[relation.junctionEntityMetadata.columns[1].name] = entityId;
                values[relation.junctionEntityMetadata.columns[0].name] = relatedEntityId;
            }

            return queryRunner.insert(relation.junctionEntityMetadata.table.name, values);
        });
        await Promise.all(insertPromises);
        await this.queryRunnerProvider.release(queryRunner);
    }

    /**
     * Adds a new relation between two entities into relation's many-to-many table from inverse side of the given relation.
     * Should be used when you want quickly and efficiently add a relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addToInverseRelation(relationName: string, relatedEntityId: any, entityIds: any[]): Promise<void>;

    /**
     * Adds a new relation between two entities into relation's many-to-many table from inverse side of the given relation.
     * Should be used when you want quickly and efficiently add a relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addToInverseRelation(relationName: ((t: Entity) => string|any), relatedEntityId: any, entityIds: any[]): Promise<void>;

    /**
     * Adds a new relation between two entities into relation's many-to-many table from inverse side of the given relation.
     * Should be used when you want quickly and efficiently add a relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addToInverseRelation(relationName: string|((t: Entity) => string|any), relatedEntityId: any, entityIds: any[]): Promise<void> {
        const propertyName = this.metadata.computePropertyName(relationName);
        if (!this.metadata.hasRelationWithPropertyName(propertyName))
            throw new Error(`Relation ${propertyName} was not found in the ${this.metadata.name} entity.`);

        const relation = this.metadata.findRelationWithPropertyName(propertyName);
        if (!relation.isManyToMany)
            throw new Error(`Only many-to-many relation supported for this operation. However ${this.metadata.name}#${propertyName} relation type is ${relation.relationType}`);

        const queryRunner = await this.queryRunnerProvider.provide();
        try {
            const insertPromises = entityIds.map(entityId => {
                const values: any = {};
                if (relation.isOwning) {
                    values[relation.junctionEntityMetadata.columns[0].name] = entityId;
                    values[relation.junctionEntityMetadata.columns[1].name] = relatedEntityId;
                } else {
                    values[relation.junctionEntityMetadata.columns[1].name] = entityId;
                    values[relation.junctionEntityMetadata.columns[0].name] = relatedEntityId;
                }

                return queryRunner.insert(relation.junctionEntityMetadata.table.name, values);
            });
            await Promise.all(insertPromises);

        } finally {
            await this.queryRunnerProvider.release(queryRunner);
        }
    }

    /**
     * Removes a relation between two entities from relation's many-to-many table.
     * Should be used when you want quickly and efficiently remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async removeFromRelation(relationName: string, entityId: any, relatedEntityIds: any[]): Promise<void>;

    /**
     * Removes a relation between two entities from relation's many-to-many table.
     * Should be used when you want quickly and efficiently remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async removeFromRelation(relationName: ((t: Entity) => string|any), entityId: any, relatedEntityIds: any[]): Promise<void>;

    /**
     * Removes a relation between two entities from relation's many-to-many table.
     * Should be used when you want quickly and efficiently remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async removeFromRelation(relationName: string|((t: Entity) => string|any), entityId: any, relatedEntityIds: any[]): Promise<void> {
        const propertyName = this.metadata.computePropertyName(relationName);
        if (!this.metadata.hasRelationWithPropertyName(propertyName))
            throw new Error(`Relation ${propertyName} was not found in the ${this.metadata.name} entity.`);

        const relation = this.metadata.findRelationWithPropertyName(propertyName);
        if (!relation.isManyToMany)
            throw new Error(`Only many-to-many relation supported for this operation. However ${this.metadata.name}#${propertyName} relation type is ${relation.relationType}`);

        // check if given relation entity ids is empty - then nothing to do here (otherwise next code will remove all ids)
        if (!relatedEntityIds || !relatedEntityIds.length)
            return Promise.resolve();

        const qb = new QueryBuilder(this.connection, this.queryRunnerProvider)
            .delete()
            .fromTable(relation.junctionEntityMetadata.table.name, "junctionEntity");

        const firstColumnName = relation.isOwning ? relation.junctionEntityMetadata.columns[0].name : relation.junctionEntityMetadata.columns[1].name;
        const secondColumnName = relation.isOwning ? relation.junctionEntityMetadata.columns[1].name : relation.junctionEntityMetadata.columns[0].name;

        relatedEntityIds.forEach((relatedEntityId, index) => {
            qb.orWhere(`(${firstColumnName}=:entityId AND ${secondColumnName}=:relatedEntity_${index})`)
                .setParameter("relatedEntity_" + index, relatedEntityId);
        });

        await qb
            .setParameter("entityId", entityId)
            .execute();
    }

    /**
     * Removes a relation between two entities from relation's many-to-many table.
     * Should be used when you want quickly and efficiently remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async removeFromInverseRelation(relationName: string, relatedEntityId: any, entityIds: any[]): Promise<void>;

    /**
     * Removes a relation between two entities from relation's many-to-many table.
     * Should be used when you want quickly and efficiently remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async removeFromInverseRelation(relationName: ((t: Entity) => string|any), relatedEntityId: any, entityIds: any[]): Promise<void>;

    /**
     * Removes a relation between two entities from relation's many-to-many table.
     * Should be used when you want quickly and efficiently remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async removeFromInverseRelation(relationName: string|((t: Entity) => string|any), relatedEntityId: any, entityIds: any[]): Promise<void> {
        const propertyName = this.metadata.computePropertyName(relationName);
        if (!this.metadata.hasRelationWithPropertyName(propertyName))
            throw new Error(`Relation ${propertyName} was not found in the ${this.metadata.name} entity.`);

        const relation = this.metadata.findRelationWithPropertyName(propertyName);
        if (!relation.isManyToMany)
            throw new Error(`Only many-to-many relation supported for this operation. However ${this.metadata.name}#${propertyName} relation type is ${relation.relationType}`);

        // check if given entity ids is empty - then nothing to do here (otherwise next code will remove all ids)
        if (!entityIds || !entityIds.length)
            return Promise.resolve();

        const qb = new QueryBuilder(this.connection, this.queryRunnerProvider)
            .delete()
            .from(relation.junctionEntityMetadata.table.name, "junctionEntity");

        const firstColumnName = relation.isOwning ? relation.junctionEntityMetadata.columns[1].name : relation.junctionEntityMetadata.columns[0].name;
        const secondColumnName = relation.isOwning ? relation.junctionEntityMetadata.columns[0].name : relation.junctionEntityMetadata.columns[1].name;

        entityIds.forEach((entityId, index) => {
            qb.orWhere(`(${firstColumnName}=:relatedEntityId AND ${secondColumnName}=:entity_${index})`)
              .setParameter("entity_" + index, entityId);
        });

        await qb.setParameter("relatedEntityId", relatedEntityId).execute();
    }

    /**
     * Performs both #addToRelation and #removeFromRelation operations.
     * Should be used when you want quickly and efficiently and and remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addAndRemoveFromRelation(relation: string, entityId: any, addRelatedEntityIds: any[], removeRelatedEntityIds: any[]): Promise<void>;

    /**
     * Performs both #addToRelation and #removeFromRelation operations.
     * Should be used when you want quickly and efficiently and and remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addAndRemoveFromRelation(relation: ((t: Entity) => string|any), entityId: any, addRelatedEntityIds: any[], removeRelatedEntityIds: any[]): Promise<void>;

    /**
     * Performs both #addToRelation and #removeFromRelation operations.
     * Should be used when you want quickly and efficiently and and remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addAndRemoveFromRelation(relation: string|((t: Entity) => string|any), entityId: any, addRelatedEntityIds: any[], removeRelatedEntityIds: any[]): Promise<void> {
        await Promise.all([
            this.addToRelation(relation as any, entityId, addRelatedEntityIds),
            this.removeFromRelation(relation as any, entityId, removeRelatedEntityIds)
        ]);
    }

    /**
     * Performs both #addToRelation and #removeFromRelation operations.
     * Should be used when you want quickly and efficiently and and remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addAndRemoveFromInverseRelation(relation: string, relatedEntityId: any, addEntityIds: any[], removeEntityIds: any[]): Promise<void>;

    /**
     * Performs both #addToRelation and #removeFromRelation operations.
     * Should be used when you want quickly and efficiently and and remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addAndRemoveFromInverseRelation(relation: ((t: Entity) => string|any), relatedEntityId: any, addEntityIds: any[], removeEntityIds: any[]): Promise<void>;

    /**
     * Performs both #addToRelation and #removeFromRelation operations.
     * Should be used when you want quickly and efficiently and and remove a many-to-many relation between two entities.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async addAndRemoveFromInverseRelation(relation: string|((t: Entity) => string|any), relatedEntityId: any, addEntityIds: any[], removeEntityIds: any[]): Promise<void> {
        await Promise.all([
            this.addToInverseRelation(relation as any, relatedEntityId, addEntityIds),
            this.removeFromInverseRelation(relation as any, relatedEntityId, removeEntityIds)
        ]);
    }

    /**
     * Removes entity with the given id.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async removeById(id: any): Promise<void> {
        const alias = this.metadata.table.name;
        const parameters: ObjectLiteral = {};
        let condition = "";

        if (this.metadata.hasMultiplePrimaryKeys) {
            condition = this.metadata.primaryColumns.map(primaryColumn => {
                parameters[primaryColumn.propertyName] = id[primaryColumn.propertyName];
                return alias + "." + primaryColumn.propertyName + "=:" + primaryColumn.propertyName;
            }).join(" AND ");

        } else {
            condition = alias + "." + this.metadata.firstPrimaryColumn.propertyName + "=:id";
            parameters["id"] = id;
        }

        await new QueryBuilder(this.connection, this.queryRunnerProvider)
            .delete()
            .from(this.metadata.target, alias)
            .where(condition, parameters)
            .execute();
    }

    /**
     * Removes all entities with the given ids.
     * Note that event listeners and event subscribers won't work (and will not send any events) when using this operation.
     */
    async removeByIds(ids: any[]): Promise<void> {
        const alias = this.metadata.table.name;
        const parameters: ObjectLiteral = {};
        let condition = "";

        if (this.metadata.hasMultiplePrimaryKeys) {
            condition = ids.map((id, idIndex) => {
                this.metadata.primaryColumns.map(primaryColumn => {
                    parameters[primaryColumn.propertyName + "_" + idIndex] = id[primaryColumn.propertyName];
                    return alias + "." + primaryColumn.propertyName + "=:" + primaryColumn.propertyName + "_" + idIndex;
                }).join(" AND ");
            }).join(" OR ");
        } else {
            condition = alias + "." + this.metadata.firstPrimaryColumn.propertyName + " IN (:ids)";
            parameters["ids"] = ids;
        }

        await new QueryBuilder(this.connection, this.queryRunnerProvider)
            .delete()
            .from(this.metadata.target, alias)
            .where(condition, parameters)
            .execute();
    }

    /**
     * Finds all relation ids in the given entities.
     */
    async findRelationIds(relationOrName: RelationMetadata|string|((...args: any[]) => any), entityOrEntities: Entity[]|Entity|any|any[], inIds?: any[], notInIds?: any[]): Promise<any[]> {

        const relation = this.convertMixedRelationToMetadata(relationOrName);
        if (!(entityOrEntities instanceof Array)) entityOrEntities = [entityOrEntities];

        const entityReferencedColumn = relation.isOwning ? relation.joinTable.referencedColumn : relation.inverseRelation.joinTable.inverseReferencedColumn;
        const ownerEntityColumn = relation.isOwning ? relation.junctionEntityMetadata.columns[0] : relation.junctionEntityMetadata.columns[1];
        const inverseEntityColumn = relation.isOwning ? relation.junctionEntityMetadata.columns[1] : relation.junctionEntityMetadata.columns[0];

        let entityIds = this.convertEntityOrEntitiesToIdOrIds(entityReferencedColumn, entityOrEntities);
        if (!(entityIds instanceof Array)) entityIds = [entityIds];

        // filter out empty entity ids
        entityIds = (entityIds as any[]).filter(entityId => entityId !== null && entityId !== undefined);

        // if no entity ids at the end, then we don't need to load anything
        if ((entityIds as any[]).length === 0)
            return [];

        // create shortcuts for better readability
        const escapeAlias = (alias: string) => this.connection.driver.escapeAliasName(alias);
        const escapeColumn = (column: string) => this.connection.driver.escapeColumnName(column);

        const ids: any[] = [];
        const promises = (entityIds as any[]).map((entityId: any) => {
            const qb = new QueryBuilder(this.connection, this.queryRunnerProvider)
                .select(escapeAlias("junction") + "." + escapeColumn(inverseEntityColumn.name) + " AS id")
                .fromTable(relation.junctionEntityMetadata.table.name, "junction")
                .andWhere(escapeAlias("junction") + "." + escapeColumn(ownerEntityColumn.name) + "=:entityId", {entityId: entityId});

            if (inIds && inIds.length > 0)
                qb.andWhere(escapeAlias("junction") + "." + escapeColumn(inverseEntityColumn.name) + " IN (:inIds)", {inIds: inIds});

            if (notInIds && notInIds.length > 0)
                qb.andWhere(escapeAlias("junction") + "." + escapeColumn(inverseEntityColumn.name) + " NOT IN (:notInIds)", {notInIds: notInIds});

            return qb.getRawMany()
                .then((results: { id: any }[]) => {
                    results.forEach(result => ids.push(result.id)); // todo: prepare result?
                });
        });

        await Promise.all(promises);
        return ids;
    }

    // -------------------------------------------------------------------------
    // Protected Methods
    // -------------------------------------------------------------------------

    /**
     * Converts entity or entities to id or ids map.
     */
    protected convertEntityOrEntitiesToIdOrIds(column: ColumnMetadata, entityOrEntities: Entity[]|Entity|any|any[]): any|any[] {
        if (entityOrEntities instanceof Array) {
            return entityOrEntities.map(entity => this.convertEntityOrEntitiesToIdOrIds(column, entity));

        } else {
            if (entityOrEntities instanceof Object) {
                return entityOrEntities[column.propertyName];
            } else {
                return entityOrEntities;
            }
        }
    }

    /**
     * Converts relation name, relation name in function into RelationMetadata.
     */
    protected convertMixedRelationToMetadata(relationOrName: RelationMetadata|string|((...args: any[]) => any)): RelationMetadata {
        if (relationOrName instanceof RelationMetadata)
            return relationOrName;

        const relationName = relationOrName instanceof Function ? relationOrName(this.metadata.createPropertiesMap()) : relationOrName;
        return this.metadata.findRelationWithPropertyName(relationName);
    }

    /**
     * Extracts unique objects from given entity and all its downside relations.
     */
    protected extractObjectsById(entity: any, metadata: EntityMetadata, entityWithIds: Subject[] = []): Promise<Subject[]> {
        const promises = metadata.relations.map(relation => {
            const relMetadata = relation.inverseEntityMetadata;

            const value = relation.isLazy ? entity["__" + relation.propertyName + "__"] : entity[relation.propertyName];
            if (!value)
                return undefined;

            if (value instanceof Array) {
                const subPromises = value.map((subEntity: any) => {
                    return this.extractObjectsById(subEntity, relMetadata, entityWithIds);
                });
                return Promise.all(subPromises);

            } else {
                return this.extractObjectsById(value, relMetadata, entityWithIds);
            }
        });

        return Promise.all<any>(promises.filter(result => !!result)).then(() => {
            if (!entityWithIds.find(entityWithId => entityWithId.entity === entity)) {
                const entityWithId = new Subject(metadata, entity);
                entityWithIds.push(entityWithId);
            }

            return entityWithIds;
        });
    }

}


text:
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/**
 * @module ol/interaction/DoubleClickZoom
 */
import Interaction, { zoomByDelta } from './Interaction.js';
import MapBrowserEventType from '../MapBrowserEventType.js';
/**
 * @typedef {Object} Options
 * @property {number} [duration=250] Animation duration in milliseconds.
 * @property {number} [delta=1] The zoom delta applied on each double click.
 */
/**
 * @classdesc
 * Allows the user to zoom by double-clicking on the map.
 * @api
 */
var DoubleClickZoom = /** @class */ (function (_super) {
    __extends(DoubleClickZoom, _super);
    /**
     * @param {Options} [opt_options] Options.
     */
    function DoubleClickZoom(opt_options) {
        var _this = _super.call(this) || this;
        var options = opt_options ? opt_options : {};
        /**
         * @private
         * @type {number}
         */
        _this.delta_ = options.delta ? options.delta : 1;
        /**
         * @private
         * @type {number}
         */
        _this.duration_ = options.duration !== undefined ? options.duration : 250;
        return _this;
    }
    /**
     * Handles the {@link module:ol/MapBrowserEvent map browser event} (if it was a
     * doubleclick) and eventually zooms the map.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     */
    DoubleClickZoom.prototype.handleEvent = function (mapBrowserEvent) {
        var stopEvent = false;
        if (mapBrowserEvent.type == MapBrowserEventType.DBLCLICK) {
            var browserEvent = /** @type {MouseEvent} */ (mapBrowserEvent.originalEvent);
            var map = mapBrowserEvent.map;
            var anchor = mapBrowserEvent.coordinate;
            var delta = browserEvent.shiftKey ? -this.delta_ : this.delta_;
            var view = map.getView();
            zoomByDelta(view, delta, anchor, this.duration_);
            browserEvent.preventDefault();
            stopEvent = true;
        }
        return !stopEvent;
    };
    return DoubleClickZoom;
}(Interaction));
export default DoubleClickZoom;
//# sourceMappingURL=DoubleClickZoom.js.map


text:
import proto  # type: ignore

__protobuf__ = proto.module(
    package="google.cloud.aiplatform.v1beta1.schema.predict.prediction",
    manifest={
        "TimeSeriesForecastingPredictionResult",
    },
)

class TimeSeriesForecastingPredictionResult(proto.Message):
    r"""Prediction output format for Time Series Forecasting.

    Attributes:
        value (float):
            The regression value.
    """

    value = proto.Field(
        proto.FLOAT,
        number=1,
    )

__all__ = tuple(sorted(__protobuf__.manifest))


text:
package egovframework.com.uss.olp.opm.web;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springmodules.validation.commons.DefaultBeanValidator;

import egovframework.com.cmm.ComDefaultCodeVO;
import egovframework.com.cmm.ComDefaultVO;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.annotation.IncludedInfo;
import egovframework.com.cmm.service.EgovCmmUseService;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.uss.olp.opm.service.EgovOnlinePollManageService;
import egovframework.com.uss.olp.opm.service.OnlinePollItem;
import egovframework.com.uss.olp.opm.service.OnlinePollManage;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

/**
 * 온라인POLL관리를 처리하는 Controller Class 구현
 * @author 공통서비스 장동한
 * @since 2009.07.03
 * @version 1.0
 * @see <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자           수정내용
 *  -------    --------    ---------------------------
 *   2009.07.03  장동한          최초 생성
 *   2011.8.26	정진오			IncludedInfo annotation 추가
 *
 * </pre>
 */

@Controller
public class EgovOnlinePollManageController {

    protected Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private DefaultBeanValidator beanValidator;

    /** EgovMessageSource */
    @Resource(name = "egovMessageSource")
    EgovMessageSource egovMessageSource;

    /** egovOnlinePollService */
    @Resource(name = "egovOnlinePollManageService")
    private EgovOnlinePollManageService egovOnlinePollManageService;

    /** EgovPropertyService */
    @Resource(name = "propertiesService")
    protected EgovPropertyService propertiesService;

    /** Egov Common Code Service */
    @Resource(name="EgovCmmUseService")
    private EgovCmmUseService cmmUseService;

    /**
     * 온라인POLL관리 목록을 조회한다.
     * @param searchVO
     * @param commandMap
     * @param onlinePollManage
     * @param model
     * @return "egovframework/com/uss/olp/opm/EgovOnlinePollList"
     * @throws Exception
     */
    @IncludedInfo(name="온라인poll관리", order = 660 ,gid = 50)
    @RequestMapping(value = "/uss/olp/opm/listOnlinePollManage.do")
    public String egovOnlinePollManageList(
            @ModelAttribute("searchVO") ComDefaultVO searchVO,
            Map commandMap,
            OnlinePollManage onlinePollManage, ModelMap model)
            throws Exception {

        String sSearchMode = commandMap.get("searchMode") == null ? "" : (String) commandMap.get("searchMode");

        /** EgovPropertyService.sample */
        searchVO.setPageUnit(propertiesService.getInt("pageUnit"));
        searchVO.setPageSize(propertiesService.getInt("pageSize"));

        /** pageing */
        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(searchVO.getPageIndex());
        paginationInfo.setRecordCountPerPage(searchVO.getPageUnit());
        paginationInfo.setPageSize(searchVO.getPageSize());

        searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
        searchVO.setLastIndex(paginationInfo.getLastRecordIndex());
        searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

        List reusltList = egovOnlinePollManageService.selectOnlinePollManageList(searchVO);
        model.addAttribute("resultList", reusltList);

        model.addAttribute("searchKeyword", commandMap.get("searchKeyword") == null ? "" : (String) commandMap.get("searchKeyword"));
        model.addAttribute("searchCondition", commandMap.get("searchCondition") == null ? "" : (String) commandMap.get("searchCondition"));

        int totCnt = (Integer) egovOnlinePollManageService.selectOnlinePollManageListCnt(searchVO);
        paginationInfo.setTotalRecordCount(totCnt);
        model.addAttribute("paginationInfo", paginationInfo);

        return "egovframework/com/uss/olp/opm/EgovOnlinePollManageList";
    }

    /**
     * 온라인POLL관리 목록을 상세조회 조회한다.
     * @param searchVO
     * @param onlinePollVO
     * @param commandMap
     * @param model
     * @return
     *         "/uss/olp/opm/EgovOnlinePollDetail"
     * @throws Exception
     */
    @RequestMapping(value = "/uss/olp/opm/detailOnlinePollManage.do")
    public String egovOnlinePollManageDetail(
            @ModelAttribute("searchVO") ComDefaultVO searchVO,
            OnlinePollManage onlinePollManage,
            Map commandMap,
            ModelMap model) throws Exception {

        String sLocationUrl = "egovframework/com/uss/olp/opm/EgovOnlinePollManageDetail";

        String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd");

        //게시물 삭제
        if (sCmd.equals("del")) {
            egovOnlinePollManageService.deleteOnlinePollManage(onlinePollManage);
            sLocationUrl = "redirect:/uss/olp/opm/listOnlinePollManage.do";
        } else {

            model.addAttribute("onlinePollManage", (OnlinePollManage)egovOnlinePollManageService.selectOnlinePollManageDetail(onlinePollManage));
        }

        //POLL종류 설정
        ComDefaultCodeVO voComCode = new ComDefaultCodeVO();
        voComCode = new ComDefaultCodeVO();
        voComCode.setCodeId("COM039");
        List listComCode = cmmUseService.selectCmmCodeDetail(voComCode);
        model.addAttribute("pollKindCodeList", listComCode );

        return sLocationUrl;
    }

    /**
     * 온라인POLL관리를 수정한다.
     * @param searchVO
     * @param commandMap
     * @param onlinePollManage
     * @param bindingResult
     * @param model
     * @return
     *         "/uss/olp/opm/EgovOnlinePollUpdt"
     * @throws Exception
     */
    @RequestMapping(value = "/uss/olp/opm/updtOnlinePollManage.do")
    public String egovOnlinePollManageModify(
            @ModelAttribute("searchVO") ComDefaultVO searchVO,
            Map commandMap,
            OnlinePollManage onlinePollManage,
            BindingResult bindingResult,
            ModelMap model) throws Exception {

        // 0. Spring Security 사용자권한 처리
        Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
        if (!isAuthenticated) {
            model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
            return "egovframework/com/uat/uia/EgovLoginUsr";
        }

        // 로그인 객체 선언
        LoginVO loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();

        String sLocationUrl = "egovframework/com/uss/olp/opm/EgovOnlinePollManageUpdt";

        String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd");

        if (sCmd.equals("save")) {
            //서버  validate 체크
            beanValidator.validate(onlinePollManage, bindingResult);
            if(bindingResult.hasErrors()){
                return sLocationUrl;
            }
            //아이디 설정
            onlinePollManage.setFrstRegisterId((String)loginVO.getUniqId());
            onlinePollManage.setLastUpdusrId((String)loginVO.getUniqId());

            egovOnlinePollManageService.updateOnlinePollManage(onlinePollManage);

            sLocationUrl = "redirect:/uss/olp/opm/listOnlinePollManage.do";
        } else {

            //게시물 정보 설정
            OnlinePollManage onlinePollManageVO = (OnlinePollManage)egovOnlinePollManageService.selectOnlinePollManageDetail(onlinePollManage);
            model.addAttribute("onlinePollManage", onlinePollManageVO);
        }

        //POLL종류 Select박스 설정
        ComDefaultCodeVO voComCode = new ComDefaultCodeVO();
        voComCode = new ComDefaultCodeVO();
        voComCode.setCodeId("COM039");
        List listComCode = cmmUseService.selectCmmCodeDetail(voComCode);
        model.addAttribute("pollKindCodeList", listComCode );

        return sLocationUrl;
    }

    /**
     * 온라인POLL관리를 등록한다.
     * @param searchVO
     * @param commandMap
     * @param onlinePollManage
     * @param bindingResult
     * @param model
     * @return
     *         "/uss/olp/opm/EgovOnlinePollRegist"
     * @throws Exception
     */
    @RequestMapping(value = "/uss/olp/opm/registOnlinePollManage.do")
    public String egovOnlinePollManageRegist(
            @ModelAttribute("searchVO") ComDefaultVO searchVO,
            Map commandMap,
            @ModelAttribute("onlinePollManage") OnlinePollManage onlinePollManage,
            BindingResult bindingResult, ModelMap model) throws Exception {
        // 0. Spring Security 사용자권한 처리
        Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
        if (!isAuthenticated) {
            model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
            return "egovframework/com/uat/uia/EgovLoginUsr";
        }

        // 로그인 객체 선언
        LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

        String sLocationUrl = "egovframework/com/uss/olp/opm/EgovOnlinePollManageRegist";

        String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd");
        log.info("cmd =>" + sCmd);

        if (sCmd.equals("save")) {
            //서버  validate 체크
            beanValidator.validate(onlinePollManage, bindingResult);
            if(bindingResult.hasErrors()){
                return sLocationUrl;
            }
            //아이디 설정
            onlinePollManage.setFrstRegisterId((String)loginVO.getUniqId());
            onlinePollManage.setLastUpdusrId((String)loginVO.getUniqId());

            egovOnlinePollManageService.insertOnlinePollManage(onlinePollManage);

            sLocationUrl = "redirect:/uss/olp/opm/listOnlinePollManage.do";
        }

        //POLL종류 Select박스 설정
        ComDefaultCodeVO voComCode = new ComDefaultCodeVO();
        voComCode = new ComDefaultCodeVO();
        voComCode.setCodeId("COM039");
        List listComCode = cmmUseService.selectCmmCodeDetail(voComCode);
        model.addAttribute("pollKindCodeList", listComCode );

        return sLocationUrl;
    }

    /**
     * 온라인POLL항목을조회한다.
     * @param searchVO
     * @param commandMap
     * @param onlinePollItem
     * @param bindingResult
     * @param model
     * @return
     *         "/uss/olp/opm/EgovOnlinePollRegist"
     * @throws Exception
     */
    @RequestMapping(value = "/uss/olp/opm/listOnlinePollItem.do")
    public String egovOnlinePollItemList(
            @ModelAttribute("searchVO") ComDefaultVO searchVO, Map commandMap,
            @ModelAttribute("onlinePollItem") OnlinePollItem onlinePollItem,
            ModelMap model)
            throws Exception {

        List reusltList = egovOnlinePollManageService.selectOnlinePollItemList(onlinePollItem);
        model.addAttribute("resultList", reusltList);

        return "egovframework/com/uss/olp/opm/EgovOnlinePollItemList";
    }

    /**
     * 온라인POLL항목을 등록한다.
     * @param searchVO
     * @param commandMap
     * @param olinePollItem
     * @param bindingResult
     * @param model
     * @return
     *         "/uss/olp/opm/EgovOnlinePollRegist"
     * @throws Exception
     */
    @RequestMapping(value = "/uss/olp/opm/registOnlinePollItem.do")
    public String egovOnlinePollItemRegist(
            @ModelAttribute("searchVO") ComDefaultVO searchVO,
            Map commandMap,
            OnlinePollItem onlinePollItem,
            BindingResult bindingResult, ModelMap model) throws Exception {

        // 0. Spring Security 사용자권한 처리
        Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
        if (!isAuthenticated) {
            model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
            return "egovframework/com/uat/uia/EgovLoginUsr";
        }

        // 로그인 객체 선언
        LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

        //아이디 설정
        onlinePollItem.setFrstRegisterId((String)loginVO.getUniqId());
        onlinePollItem.setLastUpdusrId((String)loginVO.getUniqId());

        egovOnlinePollManageService.insertOnlinePollItem(onlinePollItem);

        return "forward:/uss/olp/opm/listOnlinePollItem.do";
    }

    /**
     * 온라인POLL항목을 수정한다.
     * @param searchVO
     * @param commandMap
     * @param olinePollItem
     * @param bindingResult
     * @param model
     * @return
     *         "/uss/olp/opm/EgovOnlinePollRegist"
     * @throws Exception
     */
    @RequestMapping(value = "/uss/olp/opm/updtOnlinePollItem.do")
    public String egovOnlinePollItemModify(
            @ModelAttribute("searchVO") ComDefaultVO searchVO,
            Map commandMap,
            OnlinePollItem onlinePollItem,
            BindingResult bindingResult, ModelMap model) throws Exception {

        // 0. Spring Security 사용자권한 처리
        Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
        if (!isAuthenticated) {
            model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
            return "egovframework/com/uat/uia/EgovLoginUsr";
        }

        // 로그인 객체 선언
        LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

        //아이디 설정
        onlinePollItem.setFrstRegisterId((String)loginVO.getUniqId());
        onlinePollItem.setLastUpdusrId((String)loginVO.getUniqId());

        egovOnlinePollManageService.updateOnlinePollItem(onlinePollItem);

        return "forward:/uss/olp/opm/listOnlinePollItem.do";
    }

    /**
     * 온라인POLL항목을 삭제한다.
     * @param searchVO
     * @param commandMap
     * @param olinePollItem
     * @param bindingResult
     * @param model
     * @return
     *         "/uss/olp/opm/EgovOnlinePollRegist"
     * @throws Exception
     */
    @RequestMapping(value = "/uss/olp/opm/delOnlinePollItem.do")
    public String egovOnlinePollItemDelete(
            @ModelAttribute("searchVO") ComDefaultVO searchVO,
            Map commandMap,
            OnlinePollItem onlinePollItem,
            BindingResult bindingResult, ModelMap model) throws Exception {

        // 0. Spring Security 사용자권한 처리
        Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
        if (!isAuthenticated) {
            model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
            return "egovframework/com/uat/uia/EgovLoginUsr";
        }

        egovOnlinePollManageService.deleteOnlinePollItem(onlinePollItem);

        return "forward:/uss/olp/opm/listOnlinePollItem.do";
    }

}


text:
module Magento
  class Inventory < Base
    def api_path
      "product_stock"
    end

    def list(*args)
      results = commit("list", *args)
      Array(results).map do |result|
        self.class.new(connection, result)
      end
    end

    # product_stock.update
    # Allows you to update the required product stock data
    #
    # Return: int
    #
    # Arguments:
    #
    # mixed productId - product ID or Sku
    # hash stockItemData - array of attributes values
    def update(*args)
      commit("update", *args)
    end

    def update_many(args)
      multi_commit("update", args)
    end
  end
end


text:
layout: page-fullwidth
title: "ThingLabs by Devices"
subheadline: "By Device"
teaser: "Select your lab path by the devie you have - Arduino, RedBoard, Photon, or Raspberry Pi 2 with Windiws 10 IoT Core."
show_meta: true
comments: false
header: no
breadcrumb: true
categories: [arduino, photon, redboard, rpi2, iot-labs, maker-101]
author: doug_seven
permalink: /device/
---

### Table of Contents
*  Auto generated table of contents
{:toc}

## Arduino
Arduino is an open-source prototyping platform based on easy-to-use hardware and software. Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn it into an output - activating a motor, turning on an LED, publishing something online. You can tell your board what to do by sending a set of instructions to the microcontroller on the board.

As an open-source solution, several vendors have produces Arduino and Arduino-compatible boards, including Smart Projects, AdaFruit and SparkFun. Some of the most commonly used Arduino boards are referenced here and can be used for the labs on ThingLabs. In general we treat them all the same (as Arduino boards), with exceptions only when there is a unique characteristic, such as the Wi-Fi and Linux capabilities of the Arduino Yún.

### Arduino Uno
The Uno is a microcontroller board based on the ATmega328P. It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz quartz crystal, a USB connection, a power jack, an ICSP header and a reset button. It contains everything needed to support the microcontroller.

For technical specs, see [the official Arduino specs](https://www.arduino.cc/en/Main/ArduinoBoardUno).

[Go to Adruino Labs =>][arduino]

### Arduino Yún
The Arduino Yún is a microcontroller board based on the ATmega32u4 and the Atheros AR9331. The Atheros processor supports a Linux distribution based on OpenWrt named OpenWrt-Yun. The board has built-in Ethernet and WiFi support, a USB-A port, micro-SD card slot, 20 digital input/output pins (of which 7 can be used as PWM outputs and 12 as analog inputs), a 16 MHz crystal oscillator, a micro USB connection, an ICSP header, and a 3 reset buttons.

For technical specs, see [the official Arduino specs](https://www.arduino.cc/en/Main/ArduinoBoardYun).

[Go to Adruino Labs =>][arduino]

### SparkFun RedBoard
At SparkFun, they use many Arduinos and they're always looking for the simplest, most stable one. Each board is a bit different and no one board has everything they want, so they decided to make their own version that combines all their favorite features. The SparkFun RedBoard combines the simplicity of the Arduino Uno's Optiboot bootloader (which is used in the Pro series), the stability of the FTDI, and the R3 shield compatibility of the latest Arduino Uno R3. The RedBoard has all of the hardware peripherals you need: 14 Digital I/O pins with 6 PWM pins, 6 Analog Inputs, UART, SPI and external interrupts. SparkFun also broke out the SDA, SCL and IOREF pins that showed up on the UNO R3, so the RedBoard will be compatible with future shields. This version adds an SMD ISP header for use with shields.

For technical specs, see [the official SparkFun specs](https://www.sparkfun.com/products/12757)

[Go to Adruino Labs =>][arduino]

## Particle Photon
Particle is a prototype-to-production platform for developing an Internet of Things product. The Photon is a $19 development kit for creating Wi-Fi connected products. It's based on Broadcom's WICED architecture, and combines a powerful STM32 ARM Cortex M3 microcontroller and a Broadcom Wi-Fi chip (the same one that's in Nest Protect, LIFX, and Amazon Dash).

For technical specs, see [the official Particle Photon specs](https://www.particle.io/prototype#photon)

[Go to Particle Photon Labs =>][photon]

## RaspBerry Pi
The Raspberry Pi (aka RPi) is a series of credit card–sized single-board computers developed in the United Kingdom by the _Raspberry Pi Foundation_ with the intention of promoting the teaching of basic computer science in schools and developing countries.

### Raspberry Pi 2
The RPi2 is the second generation RPi. It replaced the original RPi1 in February 2015. It has a 900MHz quad-core ARM Cortex-A7 CPU, 1GB RAM, 4 USB ports, 40 GPIO pins, full HDMI port, Ethernet port, combined 3.5mm audio jack and composite video, camera interface (CSI), display interface (DSI), micro SD card slot, and VideoCore IV 3D graphics core.

Because it has an ARMv7 processor, it can run the full range of ARM GNU/Linux distributions, including Snappy Ubuntu Core, as well as Microsoft Windows 10 IoT Core. The RPi2 has an identical form factor to the previous (RPi1) and has complete compatibility with RPi1.

For technical specs, see [the official Raspberry Pi 2 specs](https://www.raspberrypi.org/products/raspberry-pi-2-model-b/)

#### Windows 10 IoT Core
You can build IoT projects with the RPi2 running Windows 10 IoT Core and using the .NET Framework and C#.

[Go to RPi2 Windows IoT Labs =>][rpi2]

#### Raspian
Coming soon!

### Raspberry Pi Zero
The Raspberry Pi Zero is a small, five-dollar computer (smaller than the RPi2). A tiny Raspberry Pi that's affordable enough for any project! The RPiZero has a 1Ghz Single-core CPU, 512MB RAM, mini HDMI and USB On-The-Go ports, micro USB power, HAT-compatible 40-pin header, composite video and reset headers.

For technical specs, see [the official Raspberry Pi Zero specs](https://www.raspberrypi.org/products/pi-zero/)

Coming soon!

## SparkFun Thing (ESP8266)
The SparkFun ESP8266 Thing is a breakout and development board for the ESP8266 WiFi SoC – a leading platform for Internet of Things (IoT) or WiFi-related projects. The SparkFun ESP8266 Thing is a relatively simple board. The pins are broken out to two parallel, breadboard-compatible rows. USB and LiPo connectors at the top of the board provide power – controlled by the nearby ON/OFF switch. LEDs towards the inside of the board indicate power, charge, and status of the IC. The ESP8266's maximum voltage is 3.6V, so the Thing has an onboard 3.3V regulator to deliver a safe, consistent voltage to the IC. That means the ESP8266's I/O pins also run at 3.3V, you'll need to level shift any 5V signals running into the IC. A 3.3V FTDI Basic is required to program the SparkFun ESP8266 Thing, but other serial converters with 3.3V I/O levels should work just fine as well. The converter does need a DTR line in addition to the RX and TX pins.

For technical specs, see [the official SparkFun Thing specs](https://www.sparkfun.com/products/13231)

Coming soon!

## Intel Edison
Designed for expert makers, entrepreneurs, and some industrial IoT applications, the Intel® Edison compute module provides ease-of-development for a range of prototyping projects or commercial ventures when performance matters. High performance, dual-core CPU and single core micro-controller supports complex data collection in a low power package, integrated Wi-Fi certified in 68 countries, Bluetooth® 4.0 support, 1GB DDR and 4GB flash memory simplifies configuration and increases scalability, 40 multiplexed GPIO interfaces with expansion board options for total project design. flexibility

For technical specs, see [the official Intel Edison specs](http://www.intel.com/content/www/us/en/do-it-yourself/edison.html)

Coming soon!

[arduino]: /device/arduino
[photon]: /device/photon
[rpi2]: /device/rpi2


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Balance_Sheet_Controll extends CI_Controller {
public function __construct() {
        parent::__construct();
        $admin_id = $this->session->userdata('current_user_id');
        if ($admin_id == NULL) {
            redirect('admin_control','refresh');
        }
    }
    public function show_balance_sheet() {
        $data = array();
        $data['title'] = 'Balance Sheet';
        $data['title1'] = 'Balance Sheet';
        $data['maincontent'] = $this->load->view('admin/account_balance_sheet', '', TRUE);
        $this->load->view('home', $data);
    }
     public function balance_sheet_reports() {
        $data = array();
        $data['title'] = 'Balance Sheet Report';
        $data['title1'] = 'Balance Sheet Report';
        $data['maincontent'] = $this->load->view('admin/balance_sheet_reports', '', TRUE);
        $this->load->view('home', $data);
    }
    public function trial_balance() {
        $data = array();
        $data['title'] = 'Trial Balance';
        $data['title1'] = 'Trial Balance';
        $data['maincontent'] = $this->load->view('admin/trial_balance', '', TRUE);
        $this->load->view('home', $data);
    }
     public function show_trial_balance() {
        $data = array();
        $data['title'] = 'Trial Balance';
        $data['title1'] = 'Trial Balance';
        $data['maincontent'] = $this->load->view('admin/show_trial_balance', '', TRUE);
        $this->load->view('home', $data);
    }
}