text:
package com.mxgraph.layout;

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import com.mxgraph.model.mxGraphModel;
import com.mxgraph.model.mxIGraphModel;
import com.mxgraph.util.mxRectangle;
import com.mxgraph.view.mxGraph;
import com.mxgraph.view.mxGraphView;

/**
 * An implementation of a simulated annealing layout, based on "Drawing Graphs
 * Nicely Using Simulated Annealing" by Davidson and Harel (1996). This
 * paper describes these criteria as being favourable in a graph layout: (1)
 * distributing nodes evenly, (2) making edge-lengths uniform, (3)
 * minimizing cross-crossings, and (4) keeping nodes from coming too close
 * to edges. These criteria are translated into energy cost functions in the
 * layout. Nodes or edges breaking these criteria create a larger cost function
 * , the total cost they contribute related to the extent that they break it.
 * The idea of the algorithm is to minimise the total system energy. Factors
 * are assigned to each of the criteria describing how important that
 * criteria is. Higher factors mean that those criteria are deemed to be
 * relatively preferable in the final layout. Most of  the criteria conflict
 * with the others to some extent and so the setting of the factors determines
 * the general look of the resulting graph.
 *

 * In addition to the four aesthetic criteria the concept of a border line
 * which induces an energy cost to nodes in proximity to the graph bounds is
 * introduced to attempt to restrain the graph. All of the 5 factors can be
 * switched on or off using the isOptimize... variables.
 *

 * Simulated Annealing is a force-directed layout and is one of the more
 * expensive, but generally effective layouts of this type. Layouts like
 * the spring layout only really factor in edge length and inter-node
 * distance being the lowest CPU intensive for the most aesthetic gain. The
 * additional factors are more expensive but can have very attractive results.
 *

 * The main loop of the algorithm consist of processing the nodes in a
 * deterministic order. During the processing of each node a circle of radius
 * moveRadius is made around the node and split into
 * triesPerCell equal segments. Each point between neighbour
 * segments is determined and the new energy of the system if the node were
 * moved to that position calculated. Only the necessary nodes and edges are
 * processed new energy values resulting in quadratic performance, O(VE),
 * whereas calculating the total system energy would be cubic. The default
 * implementation only checks 8 points around the radius of the circle, as
 * opposed to the suggested 30 in the paper. Doubling the number of points
 * double the CPU load and 8 works almost as well as 30.
 *

 * The moveRadius replaces the temperature as the influencing
 * factor in the way the graph settles in later iterations. If the user does
 * not set the initial move radius it is set to half the maximum dimension
 * of the graph. Thus, in 2 iterations a node may traverse the entire graph,
 * and it is more sensible to find minima this way that uphill moves, which
 * are little more than an expensive 'tilt' method. The factor by which
 * the radius is multiplied by after each iteration is important, lowering
 * it improves performance but raising it towards 1.0 can improve the
 * resulting graph aesthetics. When the radius hits the minimum move radius
 * defined, the layout terminates. The minimum move radius should be set
 * a value where the move distance is too minor to be of interest.
 *

 * Also, the idea of a fine tuning phase is used, as described in the paper.
 * This involves only calculating the edge to node distance energy cost
 * at the end of the algorithm since it is an expensive calculation and
 * it really an 'optimizating' function. fineTuningRadius
 * defines the radius value that, when reached, causes the edge to node
 * distance to be calculated.
 *

 * There are other special cases that are processed after each iteration.
 * unchangedEnergyRoundTermination defines the number of
 * iterations, after which the layout terminates. If nothing is being moved
 * it is assumed a good layout has been found. In addition to this if
 * no nodes are moved during an iteration the move radius is halved, presuming
 * that a finer granularity is required.
 *
 */
public class mxOrganicLayout extends mxGraphLayout
{

	/**
	 * Whether or not the distance between edge and nodes will be calculated
	 * as an energy cost function. This function is CPU intensive and is best
	 * only used in the fine tuning phase.
	 */
	protected boolean isOptimizeEdgeDistance = true;

	/**
	 * Whether or not edges crosses will be calculated as an energy cost
	 * function. This function is CPU intensive, though if some iterations
	 * without it are required, it is best to have a few cycles at the start
	 * of the algorithm using it, then use it intermittantly through the rest
	 * of the layout.
	 */
	protected boolean isOptimizeEdgeCrossing = true;

	/**
	 * Whether or not edge lengths will be calculated as an energy cost
	 * function. This function not CPU intensive.
	 */
	protected boolean isOptimizeEdgeLength = true;

	/**
	 * Whether or not nodes will contribute an energy cost as they approach
	 * the bound of the graph. The cost increases to a limit close to the
	 * border and stays constant outside the bounds of the graph. This function
	 * is not CPU intensive
	 */
	protected boolean isOptimizeBorderLine = true;

	/**
	 * Whether or not node distribute will contribute an energy cost where
	 * nodes are close together. The function is moderately CPU intensive.
	 */
	protected boolean isOptimizeNodeDistribution = true;

	/**
	 * when {@link #moveRadius}reaches this value, the algorithm is terminated
	 */
	protected double minMoveRadius = 2.0;

	/**
	 * The current radius around each node where the next position energy
	 * values will be calculated for a possible move
	 */
	protected double moveRadius;

	/**
	 * The initial value of moveRadius. If this is set to zero
	 * the layout will automatically determine a suitable value.
	 */
	protected double initialMoveRadius = 0.0;

	/**
	 * The factor by which the moveRadius is multiplied by after
	 * every iteration. A value of 0.75 is a good balance between performance
	 * and aesthetics. Increasing the value provides more chances to find
	 * minimum energy positions and decreasing it causes the minimum radius
	 * termination condition to occur more quickly.
	 */
	protected double radiusScaleFactor = 0.75;

	/**
	 * The average amount of area allocated per node. If  bounds
	 * is not set this value mutiplied by the number of nodes to find
	 * the total graph area. The graph is assumed square.
	 */
	protected double averageNodeArea = 160000;

	/**
	 * The radius below which fine tuning of the layout should start
	 * This involves allowing the distance between nodes and edges to be
	 * taken into account in the total energy calculation. If this is set to
	 * zero, the layout will automatically determine a suitable value
	 */
	protected double fineTuningRadius = 40.0;

	/**
	 * Limit to the number of iterations that may take place. This is only
	 * reached if one of the termination conditions does not occur first.
	 */
	protected int maxIterations = 1000;

	/**
	 * Cost factor applied to energy calculations involving the distance
	 * nodes and edges. Increasing this value tends to cause nodes to move away
	 * from edges, at the partial cost of other graph aesthetics.
	 * isOptimizeEdgeDistance must be true for edge to nodes
	 * distances to be taken into account.
	 */
	protected double edgeDistanceCostFactor = 3000;

	/**
	 * Cost factor applied to energy calculations involving edges that cross
	 * over one another. Increasing this value tends to result in fewer edge
	 * crossings, at the partial cost of other graph aesthetics.
	 * isOptimizeEdgeCrossing must be true for edge crossings
	 * to be taken into account.
	 */
	protected double edgeCrossingCostFactor = 6000;

	/**
	 * Cost factor applied to energy calculations involving the general node
	 * distribution of the graph. Increasing this value tends to result in
	 * a better distribution of nodes across the available space, at the
	 * partial cost of other graph aesthetics.
	 * isOptimizeNodeDistribution must be true for this general
	 * distribution to be applied.
	 */
	protected double nodeDistributionCostFactor = 30000;

	/**
	 * Cost factor applied to energy calculations for node promixity to the
	 * notional border of the graph. Increasing this value results in
	 * nodes tending towards the centre of the drawing space, at the
	 * partial cost of other graph aesthetics.
	 * isOptimizeBorderLine must be true for border
	 * repulsion to be applied.
	 */
	protected double borderLineCostFactor = 5;

	/**
	 * Cost factor applied to energy calculations for the edge lengths.
	 * Increasing this value results in the layout attempting to shorten all
	 * edges to the minimum edge length, at the partial cost of other graph
	 * aesthetics.
	 * isOptimizeEdgeLength must be true for edge length
	 * shortening to be applied.
	 */
	protected double edgeLengthCostFactor = 0.02;

	/**
	 * The x coordinate of the final graph
	 */
	protected double boundsX = 0.0;

	/**
	 * The y coordinate of the final graph
	 */
	protected double boundsY = 0.0;

	/**
	 * The width coordinate of the final graph
	 */
	protected double boundsWidth = 0.0;

	/**
	 * The height coordinate of the final graph
	 */
	protected double boundsHeight = 0.0;

	/**
	 * current iteration number of the layout
	 */
	protected int iteration;

	/**
	 * determines, in how many segments the circle around cells is divided, to
	 * find a new position for the cell. Doubling this value doubles the CPU
	 * load. Increasing it beyond 16 might mean a change to the
	 * performRound method might further improve accuracy for a
	 * small performance hit. The change is described in the method comment.
	 */
	protected int triesPerCell = 8;

	/**
	 * prevents from dividing with zero and from creating excessive energy
	 * values
	 */
	protected double minDistanceLimit = 2;

	/**
	 * cached version of minDistanceLimit squared
	 */
	protected double minDistanceLimitSquared;

	/**
	 * distance limit beyond which energy costs due to object repulsive is
	 * not calculated as it would be too insignificant
	 */
	protected double maxDistanceLimit = 100;

	/**
	 * cached version of maxDistanceLimit squared
	 */
	protected double maxDistanceLimitSquared;

	/**
	 * Keeps track of how many consecutive round have passed without any energy
	 * changes
	 */
	protected int unchangedEnergyRoundCount;

	/**
	 * The number of round of no node moves taking placed that the layout
	 * terminates
	 */
	protected int unchangedEnergyRoundTermination = 5;

	/**
	 * Whether or not to use approximate node dimensions or not. Set to true
	 * the radius squared of the smaller dimension is used. Set to false the
	 * radiusSquared variable of the CellWrapper contains the width squared
	 * and heightSquared is used in the obvious manner.
	 */
	protected boolean approxNodeDimensions = true;

	/**
	 * Internal models collection of nodes ( vertices ) to be laid out
	 */
	protected CellWrapper[] v;

	/**
	 * Internal models collection of edges to be laid out
	 */
	protected CellWrapper[] e;

	/**
	 * Array of the x portion of the normalised test vectors that
	 * are tested for a lower energy around each vertex. The vector
	 * of the combined x and y normals are multipled by the current
	 * radius to obtain test points for each vector in the array.
	 */
	protected double[] xNormTry;

	/**
	 * Array of the y portion of the normalised test vectors that
	 * are tested for a lower energy around each vertex. The vector
	 * of the combined x and y normals are multipled by the current
	 * radius to obtain test points for each vector in the array.
	 */
	protected double[] yNormTry;

	/**
	 * Whether or not fine tuning is on. The determines whether or not
	 * node to edge distances are calculated in the total system energy.
	 * This cost function , besides detecting line intersection, is a
	 * performance intensive component of this algorithm and best left
	 * to optimization phase. isFineTuning is switched to
	 * true if and when the fineTuningRadius
	 * radius is reached. Switching this variable to true
	 * before the algorithm runs mean the node to edge cost function
	 * is always calculated.
	 */
	protected boolean isFineTuning = true;

	/**
	 *  Specifies if the STYLE_NOEDGESTYLE flag should be set on edges that are
	 * modified by the result. Default is true.
	 */
	protected boolean disableEdgeStyle = true;

	/**
	 * Specifies if all edge points of traversed edges should be removed.
	 * Default is true.
	 */
	protected boolean resetEdges = false;

	/**
	 * Constructor for mxOrganicLayout.
	 */
	public mxOrganicLayout(mxGraph graph)
	{
		super(graph);
	}

	/**
	 * Constructor for mxOrganicLayout.
	 */
	public mxOrganicLayout(mxGraph graph, Rectangle2D bounds)
	{
		super(graph);
		boundsX = bounds.getX();
		boundsY = bounds.getY();
		boundsWidth = bounds.getWidth();
		boundsHeight = bounds.getHeight();
	}

	/**
	 * Returns true if the given vertex has no connected edges.
	 *
	 * @param vertex Object that represents the vertex to be tested.
	 * @return Returns true if the vertex should be ignored.
	 */
	public boolean isVertexIgnored(Object vertex)
	{
		return false;
	}

	/**
	 * Implements <mxGraphLayout.execute>.
	 */
	public void execute(Object parent)
	{
		mxIGraphModel model = graph.getModel();
		mxGraphView view = graph.getView();
		Object[] vertices = graph.getChildVertices(parent);
		HashSet<Object> vertexSet = new HashSet<Object>(Arrays.asList(vertices));

		HashSet<Object> validEdges = new HashSet<Object>();

		// Remove edges that do not have both source and target terminals visible
		for (int i = 0; i < vertices.length; i++)
		{
			Object[] edges = mxGraphModel.getEdges(model, vertices[i], false, true, false);

			for (int j = 0; j < edges.length; j++)
			{
				// Only deal with sources. To be valid in the layout, each edge must be attached
				// at both source and target to a vertex in the layout. Doing this avoids processing
				// each edge twice.
				if (view.getVisibleTerminal(edges[j], true) == vertices[i] && vertexSet.contains(view.getVisibleTerminal(edges[j], false)))
				{
					validEdges.add(edges[j]);
				}
			}

		}

		Object[] edges = validEdges.toArray();

		// If the bounds dimensions have not been set see if the average area
		// per node has been
		mxRectangle totalBounds = null;
		mxRectangle bounds = null;

		// Form internal model of nodes
		Map<Object, Integer> vertexMap = new Hashtable<Object, Integer>();
		v = new CellWrapper[vertices.length];
		for (int i = 0; i < vertices.length; i++)
		{
			v[i] = new CellWrapper(vertices[i]);
			vertexMap.put(vertices[i], new Integer(i));
			bounds = getVertexBounds(vertices[i]);

			if (totalBounds == null)
			{
				totalBounds = (mxRectangle) bounds.clone();
			}
			else
			{
				totalBounds.add(bounds);
			}

			// Set the X,Y value of the internal version of the cell to
			// the center point of the vertex for better positioning
			double width = bounds.getWidth();
			double height = bounds.getHeight();
			v[i].x = bounds.getX() + width / 2.0;
			v[i].y = bounds.getY() + height / 2.0;
			if (approxNodeDimensions)
			{
				v[i].radiusSquared = Math.min(width, height);
				v[i].radiusSquared *= v[i].radiusSquared;
			}
			else
			{
				v[i].radiusSquared = width * width;
				v[i].heightSquared = height * height;
			}
		}

		if (averageNodeArea == 0.0)
		{
			if (boundsWidth == 0.0 && totalBounds != null)
			{
				// Just use current bounds of graph
				boundsX = totalBounds.getX();
				boundsY = totalBounds.getY();
				boundsWidth = totalBounds.getWidth();
				boundsHeight = totalBounds.getHeight();
			}
		}
		else
		{
			// find the center point of the current graph
			// based the new graph bounds on the average node area set
			double newArea = averageNodeArea * vertices.length;
			double squareLength = Math.sqrt(newArea);
			if (bounds != null)
			{
				double centreX = totalBounds.getX() + totalBounds.getWidth() / 2.0;
				double centreY = totalBounds.getY() + totalBounds.getHeight() / 2.0;
				boundsX = centreX - squareLength / 2.0;
				boundsY = centreY - squareLength / 2.0;
			}
			else
			{
				boundsX = 0;
				boundsY = 0;
			}
			boundsWidth = squareLength;
			boundsHeight = squareLength;
			// Ensure x and y are 0 or positive
			if (boundsX < 0.0 || boundsY < 0.0)
			{
				double maxNegativeAxis = Math.min(boundsX, boundsY);
				double axisOffset = -maxNegativeAxis;
				boundsX += axisOffset;
				boundsY += axisOffset;
			}
		}

		// If the initial move radius has not been set find a suitable value.
		// A good value is half the maximum dimension of the final graph area
		if (initialMoveRadius == 0.0)
		{
			initialMoveRadius = Math.max(boundsWidth, boundsHeight) / 2.0;
		}

		moveRadius = initialMoveRadius;

		minDistanceLimitSquared = minDistanceLimit * minDistanceLimit;
		maxDistanceLimitSquared = maxDistanceLimit * maxDistanceLimit;

		unchangedEnergyRoundCount = 0;

		// Form internal model of edges
		e = new CellWrapper[edges.length];

		for (int i = 0; i < e.length; i++)
		{
			e[i] = new CellWrapper(edges[i]);

			Object sourceCell = model.getTerminal(edges[i], true);
			Object targetCell = model.getTerminal(edges[i], false);
			Integer source = null;
			Integer target = null;
			// Check if either end of the edge is not connected
			if (sourceCell != null)
			{
				source = vertexMap.get(sourceCell);
			}
			if (targetCell != null)
			{
				target = vertexMap.get(targetCell);
			}
			if (source != null)
			{
				e[i].source = source.intValue();
			}
			else
			{
				// source end is not connected
				e[i].source = -1;
			}
			if (target != null)
			{
				e[i].target = target.intValue();
			}
			else
			{
				// target end is not connected
				e[i].target = -1;
			}
		}

		// Set up internal nodes with information about whether edges
		// are connected to them or not
		for (int i = 0; i < v.length; i++)
		{
			v[i].relevantEdges = getRelevantEdges(i);
			v[i].connectedEdges = getConnectedEdges(i);
		}

		// Setup the normal vectors for the test points to move each vertex to
		xNormTry = new double[triesPerCell];
		yNormTry = new double[triesPerCell];

		for (int i = 0; i < triesPerCell; i++)
		{
			double angle = i
					* ((2.0 * Math.PI) / triesPerCell);
			xNormTry[i] = Math.cos(angle);
			yNormTry[i] = Math.sin(angle);
		}

		int childCount = model.getChildCount(parent);

		for (int i = 0; i < childCount; i++)
		{
			Object cell = model.getChildAt(parent, i);

			if (!isEdgeIgnored(cell))
			{
				if (isResetEdges())
				{
					graph.resetEdge(cell);
				}

				if (isDisableEdgeStyle())
				{
					setEdgeStyleEnabled(cell, false);
				}
			}
		}

		// The main layout loop
		for (iteration = 0; iteration < maxIterations; iteration++)
		{
			performRound();
		}

		// Obtain the final positions
		double[][] result = new double[v.length][2];
		for (int i = 0; i < v.length; i++)
		{
			vertices[i] = v[i].cell;
			bounds = getVertexBounds(vertices[i]);

			result[i][0] = v[i].x - bounds.getWidth() / 2;
			result[i][1] = v[i].y - bounds.getHeight() / 2;
		}

		model.beginUpdate();
		try
		{
			for (int i = 0; i < vertices.length; i++)
			{
				setVertexLocation(vertices[i], result[i][0], result[i][1]);
			}
		}
		finally
		{
			model.endUpdate();
		}
	}

	/**
	 * The main round of the algorithm. Firstly, a permutation of nodes
	 * is created and worked through in that random order. Then, for each node
	 * a number of point of a circle of radius moveRadius are
	 * selected and the total energy of the system calculated if that node
	 * were moved to that new position. If a lower energy position is found
	 * this is accepted and the algorithm moves onto the next node. There
	 * may be a slightly lower energy value yet to be found, but forcing
	 * the loop to check all possible positions adds nearly the current
	 * processing time again, and for little benefit. Another possible
	 * strategy would be to take account of the fact that the energy values
	 * around the circle decrease for half the loop and increase for the
	 * other, as a general rule. If part of the decrease were seen, then
	 * when the energy of a node increased, the previous node position was
	 * almost always the lowest energy position. This adds about two loop
	 * iterations to the inner loop and only makes sense with 16 tries or more.
	 */
	protected void performRound()
	{
		// sequential order cells are computed (every round the same order)

		// boolean to keep track of whether any moves were made in this round
		boolean energyHasChanged = false;
		for (int i = 0; i < v.length; i++)
		{
			int index = i;

			// Obtain the energies for the node is its current position
			// TODO The energy could be stored from the last iteration
			// and used again, rather than re-calculate
			double oldNodeDistribution = getNodeDistribution(index);
			double oldEdgeDistance = getEdgeDistanceFromNode(index);
			oldEdgeDistance += getEdgeDistanceAffectedNodes(index);
			double oldEdgeCrossing = getEdgeCrossingAffectedEdges(index);
			double oldBorderLine = getBorderline(index);
			double oldEdgeLength = getEdgeLengthAffectedEdges(index);
			double oldAdditionFactors = getAdditionFactorsEnergy(index);

			for (int j = 0; j < triesPerCell; j++)
			{
				double movex = moveRadius * xNormTry[j];
				double movey = moveRadius * yNormTry[j];

				// applying new move
				double oldx = v[index].x;
				double oldy = v[index].y;
				v[index].x = v[index].x + movex;
				v[index].y = v[index].y + movey;

				// calculate the energy delta from this move
				double energyDelta = calcEnergyDelta(index,
						oldNodeDistribution, oldEdgeDistance, oldEdgeCrossing,
						oldBorderLine, oldEdgeLength, oldAdditionFactors);

				if (energyDelta < 0)
				{
					// energy of moved node is lower, finish tries for this
					// node
					energyHasChanged = true;
					break; // exits loop
				}
				else
				{
					// Revert node coordinates
					v[index].x = oldx;
					v[index].y = oldy;
				}
			}
		}
		// Check if we've hit the limit number of unchanged rounds that cause
		// a termination condition
		if (energyHasChanged)
		{
			unchangedEnergyRoundCount = 0;
		}
		else
		{
			unchangedEnergyRoundCount++;
			// Half the move radius in case assuming it's set too high for
			// what might be an optimisation case
			moveRadius /= 2.0;
		}
		if (unchangedEnergyRoundCount >= unchangedEnergyRoundTermination)
		{
			iteration = maxIterations;
		}

		// decrement radius in controlled manner
		double newMoveRadius = moveRadius * radiusScaleFactor;
		// Don't waste time on tiny decrements, if the final pixel resolution
		// is 50 then there's no point doing 55,54.1, 53.2 etc
		if (moveRadius - newMoveRadius < minMoveRadius)
		{
			newMoveRadius = moveRadius - minMoveRadius;
		}
		// If the temperature reaches its minimum temperature then finish
		if (newMoveRadius <= minMoveRadius)
		{
			iteration = maxIterations;
		}
		// Switch on fine tuning below the specified temperature
		if (newMoveRadius < fineTuningRadius)
		{
			isFineTuning = true;
		}

		moveRadius = newMoveRadius;

	}

	/**
	 * Calculates the change in energy for the specified node. The new energy is
	 * calculated from the cost function methods and the old energy values for
	 * each cost function are passed in as parameters
	 *
	 * @param index
	 *            The index of the node in the vertices array
	 * @param oldNodeDistribution
	 *            The previous node distribution energy cost of this node
	 * @param oldEdgeDistance
	 *            The previous edge distance energy cost of this node
	 * @param oldEdgeCrossing
	 *            The previous edge crossing energy cost for edges connected to
	 *            this node
	 * @param oldBorderLine
	 *            The previous border line energy cost for this node
	 * @param oldEdgeLength
	 *            The previous edge length energy cost for edges connected to
	 *            this node
	 * @param oldAdditionalFactorsEnergy
	 *            The previous energy cost for additional factors from
	 *            sub-classes
	 *
	 * @return the delta of the new energy cost to the old energy cost
	 *
	 */
	protected double calcEnergyDelta(int index, double oldNodeDistribution,
			double oldEdgeDistance, double oldEdgeCrossing,
			double oldBorderLine, double oldEdgeLength,
			double oldAdditionalFactorsEnergy)
	{
		double energyDelta = 0.0;
		energyDelta += getNodeDistribution(index) * 2.0;
		energyDelta -= oldNodeDistribution * 2.0;

		energyDelta += getBorderline(index);
		energyDelta -= oldBorderLine;

		energyDelta += getEdgeDistanceFromNode(index);
		energyDelta += getEdgeDistanceAffectedNodes(index);
		energyDelta -= oldEdgeDistance;

		energyDelta -= oldEdgeLength;
		energyDelta += getEdgeLengthAffectedEdges(index);

		energyDelta -= oldEdgeCrossing;
		energyDelta += getEdgeCrossingAffectedEdges(index);

		energyDelta -= oldAdditionalFactorsEnergy;
		energyDelta += getAdditionFactorsEnergy(index);

		return energyDelta;
	}

	/**
	 * Calculates the energy cost of the specified node relative to all other
	 * nodes. Basically produces a higher energy the closer nodes are together.
	 *
	 * @param i the index of the node in the array v
	 * @return the total node distribution energy of the specified node
	 */
	protected double getNodeDistribution(int i)
	{
		double energy = 0.0;

		// This check is placed outside of the inner loop for speed, even
		// though the code then has to be duplicated
		if (isOptimizeNodeDistribution == true)
		{
			if (approxNodeDimensions)
			{
				for (int j = 0; j < v.length; j++)
				{
					if (i != j)
					{
						double vx = v[i].x - v[j].x;
						double vy = v[i].y - v[j].y;
						double distanceSquared = vx * vx + vy * vy;
						distanceSquared -= v[i].radiusSquared;
						distanceSquared -= v[j].radiusSquared;

						// prevents from dividing with Zero.
						if (distanceSquared < minDistanceLimitSquared)
						{
							distanceSquared = minDistanceLimitSquared;
						}

						energy += nodeDistributionCostFactor / distanceSquared;
					}
				}
			}
			else
			{
				for (int j = 0; j < v.length; j++)
				{
					if (i != j)
					{
						double vx = v[i].x - v[j].x;
						double vy = v[i].y - v[j].y;
						double distanceSquared = vx * vx + vy * vy;
						distanceSquared -= v[i].radiusSquared;
						distanceSquared -= v[j].radiusSquared;
						// If the height separation indicates overlap, subtract
						// the widths from the distance. Same for width overlap
						// TODO						if ()

						// prevents from dividing with Zero.
						if (distanceSquared < minDistanceLimitSquared)
						{
							distanceSquared = minDistanceLimitSquared;
						}

						energy += nodeDistributionCostFactor / distanceSquared;
					}
				}
			}
		}
		return energy;
	}

	/**
	 * This method calculates the energy of the distance of the specified
	 * node to the notional border of the graph. The energy increases up to
	 * a limited maximum close to the border and stays at that maximum
	 * up to and over the border.
	 *
	 * @param i the index of the node in the array v
	 * @return the total border line energy of the specified node
	 */
	protected double getBorderline(int i)
	{
		double energy = 0.0;
		if (isOptimizeBorderLine)
		{
			// Avoid very small distances and convert negative distance (i.e
			// outside the border to small positive ones )
			double l = v[i].x - boundsX;
			if (l < minDistanceLimit)
				l = minDistanceLimit;
			double t = v[i].y - boundsY;
			if (t < minDistanceLimit)
				t = minDistanceLimit;
			double r = boundsX + boundsWidth - v[i].x;
			if (r < minDistanceLimit)
				r = minDistanceLimit;
			double b = boundsY + boundsHeight - v[i].y;
			if (b < minDistanceLimit)
				b = minDistanceLimit;
			energy += borderLineCostFactor
					* ((1000000.0 / (t * t)) + (1000000.0 / (l * l))
							+ (1000000.0 / (b * b)) + (1000000.0 / (r * r)));
		}
		return energy;
	}

	/**
	 * Obtains the energy cost function for the specified node being moved.
	 * This involves calling getEdgeLength for all
	 * edges connected to the specified node
	 * @param node
	 * 				the node whose connected edges cost functions are to be
	 * 				calculated
	 * @return the total edge length energy of the connected edges
	 */
	protected double getEdgeLengthAffectedEdges(int node)
	{
		double energy = 0.0;
		for (int i = 0; i < v[node].connectedEdges.length; i++)
		{
			energy += getEdgeLength(v[node].connectedEdges[i]);
		}
		return energy;
	}

	/**
	 * This method calculates the energy due to the length of the specified
	 * edge. The energy is proportional to the length of the edge, making
	 * shorter edges preferable in the layout.
	 *
	 * @param i the index of the edge in the array e
	 * @return the total edge length energy of the specified edge
	 */
	protected double getEdgeLength(int i)
	{
		if (isOptimizeEdgeLength)
		{
			double edgeLength = Point2D.distance(v[e[i].source].x,
					v[e[i].source].y, v[e[i].target].x, v[e[i].target].y);
			return (edgeLengthCostFactor * edgeLength * edgeLength);
		}
		else
		{
			return 0.0;
		}
	}

	/**
	 * Obtains the energy cost function for the specified node being moved.
	 * This involves calling getEdgeCrossing for all
	 * edges connected to the specified node
	 * @param node
	 * 				the node whose connected edges cost functions are to be
	 * 				calculated
	 * @return the total edge crossing energy of the connected edges
	 */
	protected double getEdgeCrossingAffectedEdges(int node)
	{
		double energy = 0.0;
		for (int i = 0; i < v[node].connectedEdges.length; i++)
		{
			energy += getEdgeCrossing(v[node].connectedEdges[i]);
		}

		return energy;
	}

	/**
	 * This method calculates the energy of the distance from the specified
	 * edge crossing any other edges. Each crossing add a constant factor
	 * to the total energy
	 *
	 * @param i the index of the edge in the array e
	 * @return the total edge crossing energy of the specified edge
	 */
	protected double getEdgeCrossing(int i)
	{
		// TODO Could have a cost function per edge
		int n = 0; // counts energy of edgecrossings through edge i

		// max and min variable for minimum bounding rectangles overlapping
		// checks
		double minjX, minjY, miniX, miniY, maxjX, maxjY, maxiX, maxiY;

		if (isOptimizeEdgeCrossing)
		{
			double iP1X = v[e[i].source].x;
			double iP1Y = v[e[i].source].y;
			double iP2X = v[e[i].target].x;
			double iP2Y = v[e[i].target].y;

			for (int j = 0; j < e.length; j++)
			{
				double jP1X = v[e[j].source].x;
				double jP1Y = v[e[j].source].y;
				double jP2X = v[e[j].target].x;
				double jP2Y = v[e[j].target].y;
				if (j != i)
				{
					// First check is to see if the minimum bounding rectangles
					// of the edges overlap at all. Since the layout tries
					// to separate nodes and shorten edges, the majority do not
					// overlap and this is a cheap way to avoid most of the
					// processing
					// Some long code to avoid a Math.max call...
					if (iP1X < iP2X)
					{
						miniX = iP1X;
						maxiX = iP2X;
					}
					else
					{
						miniX = iP2X;
						maxiX = iP1X;
					}
					if (jP1X < jP2X)
					{
						minjX = jP1X;
						maxjX = jP2X;
					}
					else
					{
						minjX = jP2X;
						maxjX = jP1X;
					}
					if (maxiX < minjX || miniX > maxjX)
					{
						continue;
					}

					if (iP1Y < iP2Y)
					{
						miniY = iP1Y;
						maxiY = iP2Y;
					}
					else
					{
						miniY = iP2Y;
						maxiY = iP1Y;
					}
					if (jP1Y < jP2Y)
					{
						minjY = jP1Y;
						maxjY = jP2Y;
					}
					else
					{
						minjY = jP2Y;
						maxjY = jP1Y;
					}
					if (maxiY < minjY || miniY > maxjY)
					{
						continue;
					}

					// Ignore if any end points are coincident
					if (((iP1X != jP1X) && (iP1Y != jP1Y))
							&& ((iP1X != jP2X) && (iP1Y != jP2Y))
							&& ((iP2X != jP1X) && (iP2Y != jP1Y))
							&& ((iP2X != jP2X) && (iP2Y != jP2Y)))
					{
						// Values of zero returned from Line2D.relativeCCW are
						// ignored because the point being exactly on the line
						// is very rare for double and we've already checked if
						// any end point share the same vertex. Should zero
						// ever be returned, it would be the vertex connected
						// to the edge that's actually on the edge and this is
						// dealt with by the node to edge distance cost
						// function. The worst case is that the vertex is
						// pushed off the edge faster than it would be
						// otherwise. Because of ignoring the zero this code
						// below can behave like only a 1 or -1 will be
						// returned. See Lines2D.linesIntersects().
						boolean intersects = ((Line2D.relativeCCW(iP1X, iP1Y,
								iP2X, iP2Y, jP1X, jP1Y) != Line2D.relativeCCW(
								iP1X, iP1Y, iP2X, iP2Y, jP2X, jP2Y)) && (Line2D
								.relativeCCW(jP1X, jP1Y, jP2X, jP2Y, iP1X, iP1Y) != Line2D
								.relativeCCW(jP1X, jP1Y, jP2X, jP2Y, iP2X, iP2Y)));

						if (intersects)
						{
							n++;
						}
					}
				}
			}
		}
		return edgeCrossingCostFactor * n;
	}

	/**
	 * This method calculates the energy of the distance between Cells and
	 * Edges. This version of the edge distance cost calculates the energy
	 * cost from a specified node. The distance cost to all
	 * unconnected edges is calculated and the total returned.
	 *
	 * @param i the index of the node in the array v
	 * @return the total edge distance energy of the node
	 */
	protected double getEdgeDistanceFromNode(int i)
	{
		double energy = 0.0;
		// This function is only performed during fine tuning for performance
		if (isOptimizeEdgeDistance && isFineTuning)
		{
			int[] edges = v[i].relevantEdges;
			for (int j = 0; j < edges.length; j++)
			{
				// Note that the distance value is squared
				double distSquare = Line2D.ptSegDistSq(v[e[edges[j]].source].x,
						v[e[edges[j]].source].y, v[e[edges[j]].target].x,
						v[e[edges[j]].target].y, v[i].x, v[i].y);

				distSquare -= v[i].radiusSquared;

				// prevents from dividing with Zero. No Math.abs() call
				// for performance
				if (distSquare < minDistanceLimitSquared)
				{
					distSquare = minDistanceLimitSquared;
				}

				// Only bother with the divide if the node and edge are
				// fairly close together
				if (distSquare < maxDistanceLimitSquared)
				{
					energy += edgeDistanceCostFactor / distSquare;
				}
			}
		}
		return energy;
	}

	/**
	 * Obtains the energy cost function for the specified node being moved.
	 * This involves calling getEdgeDistanceFromEdge for all
	 * edges connected to the specified node
	 * @param node
	 * 				the node whose connected edges cost functions are to be
	 * 				calculated
	 * @return the total edge distance energy of the connected edges
	 */
	protected double getEdgeDistanceAffectedNodes(int node)
	{
		double energy = 0.0;
		for (int i = 0; i < (v[node].connectedEdges.length); i++)
		{
			energy += getEdgeDistanceFromEdge(v[node].connectedEdges[i]);
		}

		return energy;
	}

	/**
	 * This method calculates the energy of the distance between Cells and
	 * Edges. This version of the edge distance cost calculates the energy
	 * cost from a specified edge. The distance cost to all
	 * unconnected nodes is calculated and the total returned.
	 *
	 * @param i the index of the edge in the array e
	 * @return the total edge distance energy of the edge
	 */
	protected double getEdgeDistanceFromEdge(int i)
	{
		double energy = 0.0;
		// This function is only performed during fine tuning for performance
		if (isOptimizeEdgeDistance && isFineTuning)
		{
			for (int j = 0; j < v.length; j++)
			{
				// Don't calculate for connected nodes
				if (e[i].source != j && e[i].target != j)
				{
					double distSquare = Line2D.ptSegDistSq(v[e[i].source].x,
							v[e[i].source].y, v[e[i].target].x,
							v[e[i].target].y, v[j].x, v[j].y);

					distSquare -= v[j].radiusSquared;

					// prevents from dividing with Zero. No Math.abs() call
					// for performance
					if (distSquare < minDistanceLimitSquared)
						distSquare = minDistanceLimitSquared;

					// Only bother with the divide if the node and edge are
					// fairly close together
					if (distSquare < maxDistanceLimitSquared)
					{
						energy += edgeDistanceCostFactor / distSquare;
					}
				}
			}
		}
		return energy;
	}

	/**
	 * Hook method to adding additional energy factors into the layout.
	 * Calculates the energy just for the specified node.
	 * @param i the nodes whose energy is being calculated
	 * @return the energy of this node caused by the additional factors
	 */
	protected double getAdditionFactorsEnergy(int i)
	{
		return 0.0;
	}

	/**
	 * Returns all Edges that are not connected to the specified cell
	 *
	 * @param cellIndex
	 *            the cell index to which the edges are not connected
	 * @return Array of all interesting Edges
	 */
	protected int[] getRelevantEdges(int cellIndex)
	{
		ArrayList<Integer> relevantEdgeList = new ArrayList<Integer>(e.length);

		for (int i = 0; i < e.length; i++)
		{
			if (e[i].source != cellIndex && e[i].target != cellIndex)
			{
				// Add non-connected edges
				relevantEdgeList.add(new Integer(i));
			}
		}

		int[] relevantEdgeArray = new int[relevantEdgeList.size()];
		Iterator<Integer> iter = relevantEdgeList.iterator();

		//Reform the list into an array but replace Integer values with ints
		for (int i = 0; i < relevantEdgeArray.length; i++)
		{
			if (iter.hasNext())
			{
				relevantEdgeArray[i] = iter.next().intValue();
			}
		}

		return relevantEdgeArray;
	}

	/**
	 * Returns all Edges that are connected with the specified cell
	 *
	 * @param cellIndex
	 *            the cell index to which the edges are connected
	 * @return Array of all connected Edges
	 */
	protected int[] getConnectedEdges(int cellIndex)
	{
		ArrayList<Integer> connectedEdgeList = new ArrayList<Integer>(e.length);

		for (int i = 0; i < e.length; i++)
		{
			if (e[i].source == cellIndex || e[i].target == cellIndex)
			{
				// Add connected edges to list by their index number
				connectedEdgeList.add(new Integer(i));
			}
		}

		int[] connectedEdgeArray = new int[connectedEdgeList.size()];
		Iterator<Integer> iter = connectedEdgeList.iterator();

		// Reform the list into an array but replace Integer values with ints
		for (int i = 0; i < connectedEdgeArray.length; i++)
		{
			if (iter.hasNext())
			{
				connectedEdgeArray[i] = iter.next().intValue();
				;
			}
		}

		return connectedEdgeArray;
	}

	/**
	 * Returns Organic, the name of this algorithm.
	 */
	public String toString()
	{
		return "Organic";
	}

	/**
	 * Internal representation of a node or edge that holds cached information
	 * to enable the layout to perform more quickly and to simplify the code
	 */
	public class CellWrapper
	{

		/**
		 * The actual graph cell this wrapper represents
		 */
		protected Object cell;

		/**
		 * All edge that repel this cell, only used for nodes. This array
		 * is equivalent to all edges unconnected to this node
		 */
		protected int[] relevantEdges = null;

		/**
		 * the index of all connected edges in the e array
		 * to this node. This is only used for nodes.
		 */
		protected int[] connectedEdges = null;

		/**
		 * The x-coordinate position of this cell, nodes only
		 */
		protected double x;

		/**
		 * The y-coordinate position of this cell, nodes only
		 */
		protected double y;

		/**
		 * The approximate radius squared of this cell, nodes only. If
		 * approxNodeDimensions is true on the layout this value holds the
		 * width of the node squared
		 */
		protected double radiusSquared;

		/**
		 * The height of the node squared, only used if approxNodeDimensions
		 * is set to true.
		 */
		protected double heightSquared;

		/**
		 * The index of the node attached to this edge as source, edges only
		 */
		protected int source;

		/**
		 * The index of the node attached to this edge as target, edges only
		 */
		protected int target;

		/**
		 * Constructs a new CellWrapper
		 * @param cell the graph cell this wrapper represents
		 */
		public CellWrapper(Object cell)
		{
			this.cell = cell;
		}

		/**
		 * @return the relevantEdges
		 */
		public int[] getRelevantEdges()
		{
			return relevantEdges;
		}

		/**
		 * @param relevantEdges the relevantEdges to set
		 */
		public void setRelevantEdges(int[] relevantEdges)
		{
			this.relevantEdges = relevantEdges;
		}

		/**
		 * @return the connectedEdges
		 */
		public int[] getConnectedEdges()
		{
			return connectedEdges;
		}

		/**
		 * @param connectedEdges the connectedEdges to set
		 */
		public void setConnectedEdges(int[] connectedEdges)
		{
			this.connectedEdges = connectedEdges;
		}

		/**
		 * @return the x
		 */
		public double getX()
		{
			return x;
		}

		/**
		 * @param x the x to set
		 */
		public void setX(double x)
		{
			this.x = x;
		}

		/**
		 * @return the y
		 */
		public double getY()
		{
			return y;
		}

		/**
		 * @param y the y to set
		 */
		public void setY(double y)
		{
			this.y = y;
		}

		/**
		 * @return the radiusSquared
		 */
		public double getRadiusSquared()
		{
			return radiusSquared;
		}

		/**
		 * @param radiusSquared the radiusSquared to set
		 */
		public void setRadiusSquared(double radiusSquared)
		{
			this.radiusSquared = radiusSquared;
		}

		/**
		 * @return the heightSquared
		 */
		public double getHeightSquared()
		{
			return heightSquared;
		}

		/**
		 * @param heightSquared the heightSquared to set
		 */
		public void setHeightSquared(double heightSquared)
		{
			this.heightSquared = heightSquared;
		}

		/**
		 * @return the source
		 */
		public int getSource()
		{
			return source;
		}

		/**
		 * @param source the source to set
		 */
		public void setSource(int source)
		{
			this.source = source;
		}

		/**
		 * @return the target
		 */
		public int getTarget()
		{
			return target;
		}

		/**
		 * @param target the target to set
		 */
		public void setTarget(int target)
		{
			this.target = target;
		}

		/**
		 * @return the cell
		 */
		public Object getCell()
		{
			return cell;
		}
	}

	/**
	 * @return Returns the averageNodeArea.
	 */
	public double getAverageNodeArea()
	{
		return averageNodeArea;
	}

	/**
	 * @param averageNodeArea The averageNodeArea to set.
	 */
	public void setAverageNodeArea(double averageNodeArea)
	{
		this.averageNodeArea = averageNodeArea;
	}

	/**
	 * @return Returns the borderLineCostFactor.
	 */
	public double getBorderLineCostFactor()
	{
		return borderLineCostFactor;
	}

	/**
	 * @param borderLineCostFactor The borderLineCostFactor to set.
	 */
	public void setBorderLineCostFactor(double borderLineCostFactor)
	{
		this.borderLineCostFactor = borderLineCostFactor;
	}

	/**
	 * @return Returns the edgeCrossingCostFactor.
	 */
	public double getEdgeCrossingCostFactor()
	{
		return edgeCrossingCostFactor;
	}

	/**
	 * @param edgeCrossingCostFactor The edgeCrossingCostFactor to set.
	 */
	public void setEdgeCrossingCostFactor(double edgeCrossingCostFactor)
	{
		this.edgeCrossingCostFactor = edgeCrossingCostFactor;
	}

	/**
	 * @return Returns the edgeDistanceCostFactor.
	 */
	public double getEdgeDistanceCostFactor()
	{
		return edgeDistanceCostFactor;
	}

	/**
	 * @param edgeDistanceCostFactor The edgeDistanceCostFactor to set.
	 */
	public void setEdgeDistanceCostFactor(double edgeDistanceCostFactor)
	{
		this.edgeDistanceCostFactor = edgeDistanceCostFactor;
	}

	/**
	 * @return Returns the edgeLengthCostFactor.
	 */
	public double getEdgeLengthCostFactor()
	{
		return edgeLengthCostFactor;
	}

	/**
	 * @param edgeLengthCostFactor The edgeLengthCostFactor to set.
	 */
	public void setEdgeLengthCostFactor(double edgeLengthCostFactor)
	{
		this.edgeLengthCostFactor = edgeLengthCostFactor;
	}

	/**
	 * @return Returns the fineTuningRadius.
	 */
	public double getFineTuningRadius()
	{
		return fineTuningRadius;
	}

	/**
	 * @param fineTuningRadius The fineTuningRadius to set.
	 */
	public void setFineTuningRadius(double fineTuningRadius)
	{
		this.fineTuningRadius = fineTuningRadius;
	}

	/**
	 * @return Returns the initialMoveRadius.
	 */
	public double getInitialMoveRadius()
	{
		return initialMoveRadius;
	}

	/**
	 * @param initialMoveRadius The initialMoveRadius to set.
	 */
	public void setInitialMoveRadius(double initialMoveRadius)
	{
		this.initialMoveRadius = initialMoveRadius;
	}

	/**
	 * @return Returns the isFineTuning.
	 */
	public boolean isFineTuning()
	{
		return isFineTuning;
	}

	/**
	 * @param isFineTuning The isFineTuning to set.
	 */
	public void setFineTuning(boolean isFineTuning)
	{
		this.isFineTuning = isFineTuning;
	}

	/**
	 * @return Returns the isOptimizeBorderLine.
	 */
	public boolean isOptimizeBorderLine()
	{
		return isOptimizeBorderLine;
	}

	/**
	 * @param isOptimizeBorderLine The isOptimizeBorderLine to set.
	 */
	public void setOptimizeBorderLine(boolean isOptimizeBorderLine)
	{
		this.isOptimizeBorderLine = isOptimizeBorderLine;
	}

	/**
	 * @return Returns the isOptimizeEdgeCrossing.
	 */
	public boolean isOptimizeEdgeCrossing()
	{
		return isOptimizeEdgeCrossing;
	}

	/**
	 * @param isOptimizeEdgeCrossing The isOptimizeEdgeCrossing to set.
	 */
	public void setOptimizeEdgeCrossing(boolean isOptimizeEdgeCrossing)
	{
		this.isOptimizeEdgeCrossing = isOptimizeEdgeCrossing;
	}

	/**
	 * @return Returns the isOptimizeEdgeDistance.
	 */
	public boolean isOptimizeEdgeDistance()
	{
		return isOptimizeEdgeDistance;
	}

	/**
	 * @param isOptimizeEdgeDistance The isOptimizeEdgeDistance to set.
	 */
	public void setOptimizeEdgeDistance(boolean isOptimizeEdgeDistance)
	{
		this.isOptimizeEdgeDistance = isOptimizeEdgeDistance;
	}

	/**
	 * @return Returns the isOptimizeEdgeLength.
	 */
	public boolean isOptimizeEdgeLength()
	{
		return isOptimizeEdgeLength;
	}

	/**
	 * @param isOptimizeEdgeLength The isOptimizeEdgeLength to set.
	 */
	public void setOptimizeEdgeLength(boolean isOptimizeEdgeLength)
	{
		this.isOptimizeEdgeLength = isOptimizeEdgeLength;
	}

	/**
	 * @return Returns the isOptimizeNodeDistribution.
	 */
	public boolean isOptimizeNodeDistribution()
	{
		return isOptimizeNodeDistribution;
	}

	/**
	 * @param isOptimizeNodeDistribution The isOptimizeNodeDistribution to set.
	 */
	public void setOptimizeNodeDistribution(boolean isOptimizeNodeDistribution)
	{
		this.isOptimizeNodeDistribution = isOptimizeNodeDistribution;
	}

	/**
	 * @return Returns the maxIterations.
	 */
	public int getMaxIterations()
	{
		return maxIterations;
	}

	/**
	 * @param maxIterations The maxIterations to set.
	 */
	public void setMaxIterations(int maxIterations)
	{
		this.maxIterations = maxIterations;
	}

	/**
	 * @return Returns the minDistanceLimit.
	 */
	public double getMinDistanceLimit()
	{
		return minDistanceLimit;
	}

	/**
	 * @param minDistanceLimit The minDistanceLimit to set.
	 */
	public void setMinDistanceLimit(double minDistanceLimit)
	{
		this.minDistanceLimit = minDistanceLimit;
	}

	/**
	 * @return Returns the minMoveRadius.
	 */
	public double getMinMoveRadius()
	{
		return minMoveRadius;
	}

	/**
	 * @param minMoveRadius The minMoveRadius to set.
	 */
	public void setMinMoveRadius(double minMoveRadius)
	{
		this.minMoveRadius = minMoveRadius;
	}

	/**
	 * @return Returns the nodeDistributionCostFactor.
	 */
	public double getNodeDistributionCostFactor()
	{
		return nodeDistributionCostFactor;
	}

	/**
	 * @param nodeDistributionCostFactor The nodeDistributionCostFactor to set.
	 */
	public void setNodeDistributionCostFactor(double nodeDistributionCostFactor)
	{
		this.nodeDistributionCostFactor = nodeDistributionCostFactor;
	}

	/**
	 * @return Returns the radiusScaleFactor.
	 */
	public double getRadiusScaleFactor()
	{
		return radiusScaleFactor;
	}

	/**
	 * @param radiusScaleFactor The radiusScaleFactor to set.
	 */
	public void setRadiusScaleFactor(double radiusScaleFactor)
	{
		this.radiusScaleFactor = radiusScaleFactor;
	}

	/**
	 * @return Returns the triesPerCell.
	 */
	public int getTriesPerCell()
	{
		return triesPerCell;
	}

	/**
	 * @param triesPerCell The triesPerCell to set.
	 */
	public void setTriesPerCell(int triesPerCell)
	{
		this.triesPerCell = triesPerCell;
	}

	/**
	 * @return Returns the unchangedEnergyRoundTermination.
	 */
	public int getUnchangedEnergyRoundTermination()
	{
		return unchangedEnergyRoundTermination;
	}

	/**
	 * @param unchangedEnergyRoundTermination The unchangedEnergyRoundTermination to set.
	 */
	public void setUnchangedEnergyRoundTermination(
			int unchangedEnergyRoundTermination)
	{
		this.unchangedEnergyRoundTermination = unchangedEnergyRoundTermination;
	}

	/**
	 * @return Returns the maxDistanceLimit.
	 */
	public double getMaxDistanceLimit()
	{
		return maxDistanceLimit;
	}

	/**
	 * @param maxDistanceLimit The maxDistanceLimit to set.
	 */
	public void setMaxDistanceLimit(double maxDistanceLimit)
	{
		this.maxDistanceLimit = maxDistanceLimit;
	}

	/**
	 * @return the approxNodeDimensions
	 */
	public boolean isApproxNodeDimensions()
	{
		return approxNodeDimensions;
	}

	/**
	 * @param approxNodeDimensions the approxNodeDimensions to set
	 */
	public void setApproxNodeDimensions(boolean approxNodeDimensions)
	{
		this.approxNodeDimensions = approxNodeDimensions;
	}

	/**
	 * @return the disableEdgeStyle
	 */
	public boolean isDisableEdgeStyle()
	{
		return disableEdgeStyle;
	}

	/**
	 * @param disableEdgeStyle the disableEdgeStyle to set
	 */
	public void setDisableEdgeStyle(boolean disableEdgeStyle)
	{
		this.disableEdgeStyle = disableEdgeStyle;
	}

	/**
	 * @return the resetEdges
	 */
	public boolean isResetEdges()
	{
		return resetEdges;
	}

	/**
	 * @param resetEdges the resetEdges to set
	 */
	public void setResetEdges(boolean resetEdges)
	{
		this.resetEdges = resetEdges;
	}
}


text:
using System;

namespace SchoolSystem.MVP.Home.Views.EventArguments
{
    public class AddNewsEventargs : EventArgs
    {
        public string Username { get; set; }

        public string Content { get; set; }

        public DateTime CreatedOn { get; set; }

        public bool IsImportant { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2016 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- Used for the text of a borderless colored button. -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="?android:attr/textColorSecondary" android:alpha="?android:attr/disabledAlpha"/>
    <item android:color="?attr/colorAccent"/>
</selector><!-- From: file:/D:/GooglePlacesApiTutorial-master/RXBLE/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/24.0.0/res/color-v23/abc_btn_colored_borderless_text_material.xml -->


text:
// Generated by LiveScript 1.4.0

(function(){
  Polymer({
    'is': 'cs-system-admin-users-general',
    behaviors: [cs.Polymer.behaviors.Language('system_admin_users_general_'), cs.Polymer.behaviors.admin.System.settings],
    properties: {
      registration_with_confirmation: {
        computed: '_registration_with_confirmation(settings.allow_user_registration, settings.require_registration_confirmation)',
        type: Boolean
      },
      settings_api_url: 'api/System/admin/users/general'
    },
    _registration_with_confirmation: function(allow_user_registration, require_registration_confirmation){
      return allow_user_registration == 1 && require_registration_confirmation == 1;
    }
  });
}).call(this);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Message Setup

View Results

Help

								<input type="button" style="float:right; margin-right:4px;position:relative; top: 50px; width:90px; height:60px" value="Load Grid" onclick="i2b2.ExampComm.createTemplateGrid()" />

Select a communicator object and populate its input data below, and then click the "View Results" tab for the resulting XML messages sent and recieved.

<input class="addComm" type="button" value="Add" style="width:46px" onclick="i2b2.ExampComm.addCommObj()"><select id="ExampComm-objList" onchange="i2b2.ExampComm.loadCalls(this.value)"></select>
Communicator Object:

<select id="ExampComm-funcList"></select>
</>Function Call:

								<textarea>template value</textarea>

qwerqwe_asdf

(Escaped)

You must first setup a Communicator-based AJAX call.
Please return to the "Message Setup" tab.

PDO Request

PDO Response

Example #5 - Communicator Test Tool

Introduction

								This plugin demonstrates provides an interface to interact with Cell Communicator objects based on the web client's standardized i2b2 communicator objects.
								The this plugin will search all loaded plugins and core modules within the web client looking for a standard Cell Communicator object at the namespace i2b2.PLUGINCODE.ajax.

Instructions

								Navigate to the "Specify Data" tab. Then, drag and drop an i2b2 object such as a search term or previous query onto the input box. Finally, click the "View Results" tab for information about that object.

About Us

								This plugin was created by Nick Benik and Griffin Weber, MD, PhD.

Terms of Use

								This example plugin is distributed with the i2b2 web client framework and may be used free of charge.


text:
<?xml version="1.0" encoding="UTF-8"?>		<grammar>
			<name>Extracted</name>
			<meta><src>Atlantic</src><tol0>wget</tol0><tol1>ecore2bgf</tol1></meta><source>
				<author>Julien Baudry</author>
				<file>WebApplications_ConceptualModel.ecore</file>
				<date>2006/07/10</date>
				<readme/>
				<link>
					<uri>http://www.emn.fr/z-info/atlanmod/index.php/Ecore</uri>
					<name>Atlantic</name>
				</link>
				<link>
					<mu>topics/grammars/metamodels/WebApplications_ConceptualModel/WebApplications_ConceptualModel.ecore</mu>
					<name>GitHub</name>
				</link>
			</source>
<extraction><ecore/></extraction>		</grammar>


text:
module Language where

-- This example comes straight from the happy documentation

data Exp
      = Let String Exp Exp
      | Exp1 Exp1
      deriving Show

data Exp1
      = Plus Exp1 Term
      | Minus Exp1 Term
      | Term Term
      deriving Show

data Term
      = Times Term Factor
      | Div Term Factor
      | Factor Factor
      deriving Show

data Factor
      = Int Int
      | Var String
      | Brack Exp
      deriving Show

eval :: [(String,Int)] -> Exp -> Int
eval p (Let var e1 e2) = eval ((var, eval p e1): p) e2
eval p (Exp1 e)        = evalExp1 p e
  where
  evalExp1 p' (Plus  e' t) = evalExp1 p' e' + evalTerm p' t
  evalExp1 p' (Minus e' t) = evalExp1 p' e' + evalTerm p' t
  evalExp1 p' (Term  t)    = evalTerm p' t

  evalTerm p' (Times t f) = evalTerm p' t * evalFactor p' f
  evalTerm p' (Div   t f) = evalTerm p' t `div` evalFactor p' f
  evalTerm p' (Factor f)  = evalFactor p' f

  evalFactor _  (Int i)    = i
  evalFactor p' (Var s)    = case lookup s p' of
                             Nothing -> error "free variable"
                             Just i  -> i
  evalFactor p' (Brack e') = eval p' e'


text:
import path from 'path';
import cp from 'child_process';
import watch from './lib/watch';

/**
 * Launches Node.js/Express web server in a separate (forked) process.
 */
function serve() {
  return new Promise((resolve, reject) => {
    function start() {
      const server = cp.spawn('node', [path.join(__dirname, '../build/server.js')], {
        env: Object.assign({ NODE_ENV: 'development' }, process.env),
        silent: false,
      });

      server.stdout.on('data', data => {
        const message = data.toString();
        if (message.match(' running ')) {
          console.log(message.trim());
          resolve();
        } else {
          console.log(message);
        }
      });

      server.stderr.once('data', data => {
        reject(data.toString());
      });

      server.on('error', err => reject(err));
      process.on('exit', () => server.kill('SIGTERM'));
      return server;
    }

    let server = start();

    if (global.WATCH) {
      watch('build/server.js').then(watcher => {
        watcher.on('changed', () => {
          server.kill('SIGTERM');
          server = start();
        });
      });
    }
  });
}

export default serve;


text:
#ifndef CORE_EVENTS_GENERATORS_UTIL_REACTOBJECT_H
#define CORE_EVENTS_GENERATORS_UTIL_REACTOBJECT_H

#include <initializer_list>
#include <memory>

#include "ZBE/core/entities/AvatarEntity.h"

#include "ZBE/core/system/system.h"

namespace zbe {

/** \brief Object against which to react.
 */
template <typename R>
class ReactObject {
  public:
    /** \brief destructor
     */
    virtual ~ReactObject() {}

    /** \brief Executes the corresponding parts of the actuators.
     * \param reactor The reactive part of the actuator.
     */
		virtual void act(R* reactor) = 0;
};

/** \brief Object against which to react. Common code. All implementations should inherit this class ZBEAPI instead of ReactObject.
 */
template <typename R, typename ...Bases>
class ReactObjectCommon : public ReactObject<R> {
  public:

    /** \brief parametrized constructor
     * \param rObject Container of entity avatars
     */
  	ReactObjectCommon(std::shared_ptr<WeakAvatarEntityContainer<Bases...> > rObject) : rObject(rObject) {}

    /** \brief destructor
     */
    virtual ~ReactObjectCommon() {}

    /** \brief Executes the corresponding parts of the actuators.
     * \param reactor The reactive part of the actuator.
     */
    void act(R* reactor) {

      // This code is using a c ++11 syntax trick to call a method for each template parameter.
      // The list of initializers is being used to allow braces usage.
      // Comma operator is being used to pass a value to the braces.
      // Explanation:
      // This is an initializer list with a single element, a zero. (useless at the moment)
      // std::initializer_list<int>{(0)}
      // What if we want to expand that "(0)" for each template parameter?
      // this does not work, cause 0 is not a parameter pack.
      // std::initializer_list<int>{(0)...}
      // neither does this, cause each element in Bases is a type, not a value.
      // std::initializer_list<int>{(Bases)...}
      // the expresion
      // reactor->act(std::shared_ptr<WeakAvatarEntityContainer<Bases> >(rObject))
      // returns void, so we can not pass this to the initializer list either
      // How can we make that expresion return a value?
      // Using a comma operator: (expression1, expression2)
      // both expressions are evaluated, but only the value of expression2 is returned.
      // so, the next statement creates an initializer_list full of zeroes (one for each type in Bases) that will be ignored by the compiler.
      // In adition, it calls "reactor->act(...)" with each type in Bases. This is what we want.
      // gg eazy!
      std::initializer_list<int>{ (reactor->act(std::shared_ptr<WeakAvatarEntityContainer<Bases> >(rObject)), 0)... };
      reactor->act();
    }

  private:
    std::shared_ptr<WeakAvatarEntityContainer<Bases...> > rObject;
};

/** \brief Object against which to react. Common code. Implementers should use this class ZBEAPI instead of ReactObject.
 */
template <typename R>
class ReactObjectCommon<R> : public ReactObject<R> {
  public:

    /** \brief parametrized constructor
     * \param Container of entity avatars
     */
    ReactObjectCommon(std::shared_ptr<WeakAvatarEntityContainer<void> >) {}

    /** \brief empty constructor
     */
    ReactObjectCommon() {}

    /** \brief Virtual destructor
     */
  	virtual ~ReactObjectCommon() {}

    /** \brief Executes the corresponding parts of the actuators.
     * \param reactor The reactive part of the actuator.
     */
    void act(R* reactor) {
      reactor->act();
    }
};

}  // namespace zbe

#endif  // CORE_EVENTS_GENERATORS_UTIL_REACTOBJECT_H


text:
class Chef
  class Provider
    class MysqlChefGem < Chef::Provider::LWRPBase
      use_inline_resources if defined?(use_inline_resources)

      def whyrun_supported?
        true
      end

      action :install do
        # We're going to need compilers to build the gem's native
        # extentions.
        recipe_eval do
          run_context.include_recipe 'build-essential::default'
        end

        directory "#{Chef::Config[:file_cache_path]}/connector" do
          action :create
        end

        remote_file ::File.basename(new_resource.connectors_url) do
          path "#{Chef::Config[:file_cache_path]}/mysql-connector.tar.gz"
          source new_resource.connectors_url
          checksum new_resource.connectors_checksum
          notifies :run, 'bash[unpack connector]', :immediately
          action :create
        end

        bash 'unpack connector' do
          code <<-EOF
          tar xzf #{Chef::Config[:file_cache_path]}/mysql-connector.tar.gz \
          -C #{Chef::Config[:file_cache_path]}/connector \
          --strip-components 1
          EOF
          action :nothing
        end

        gem_package 'mysql' do
          gem_binary RbConfig::CONFIG['bindir'] + '/gem'
          version new_resource.gem_version
          options "-- --with-mysql-dir=#{Chef::Config[:file_cache_path]}/connector"
          action :install
        end
      end

      action :remove do
        gem_package 'mysql' do
          gem_binary RbConfig::CONFIG['bindir'] + '/gem'
          action :remove
        end
      end
    end
  end
end


text:
using System;
using Xunit;
using Should;

namespace AutoMapper.UnitTests
{
	namespace DynamicMapping
	{
		public class When_mapping_two_non_configured_types : AutoMapperSpecBase
		{
			private Destination _resultWithGenerics;
			private Destination _resultWithoutGenerics;

			public class Source
			{
				public int Value { get; set; }
			}

			public class Destination
			{
				public int Value { get; set; }
			}

			protected override void Because_of()
			{
				_resultWithGenerics = Mapper.DynamicMap<Source, Destination>(new Source {Value = 5});
				_resultWithoutGenerics = (Destination) Mapper.DynamicMap(new Source {Value = 5}, typeof(Source), typeof(Destination));
			}

			[Fact]
			public void Should_dynamically_map_the_two_types()
			{
				_resultWithGenerics.Value.ShouldEqual(5);
				_resultWithoutGenerics.Value.ShouldEqual(5);
			}
		}

        public class When_mapping_two_non_configured_types_with_nesting : NonValidatingSpecBase
        {
            private Destination _resultWithGenerics;

            public class Source
            {
                public int Value { get; set; }
                public ChildSource Child { get; set; }
            }

            public class ChildSource
            {
                public string Value2 { get; set; }
            }

            public class Destination
            {
                public int Value { get; set; }
                public ChildDestination Child { get; set; }
            }

            public class ChildDestination
            {
                public string Value2 { get; set; }
            }

            protected override void Because_of()
            {
                var source = new Source
                {
                    Value = 5,
                    Child = new ChildSource
                    {
                        Value2 = "foo"
                    }
                };
                _resultWithGenerics = Mapper.DynamicMap<Source, Destination>(source);
            }

            [Fact]
            public void Should_dynamically_map_the_two_types()
            {
                _resultWithGenerics.Value.ShouldEqual(5);
            }

            [Fact]
            public void Should_dynamically_map_the_children()
            {
                _resultWithGenerics.Child.Value2.ShouldEqual("foo");
            }
        }

		public class When_mapping_two_non_configured_types_that_do_not_match : NonValidatingSpecBase
		{
			public class Source
			{
				public int Value { get; set; }
			}

			public class Destination
			{
				public int Valuefff { get; set; }
			}

			[Fact]
			public void Should_ignore_any_members_that_do_not_match()
			{
				var destination = Mapper.DynamicMap<Source, Destination>(new Source {Value = 5});

				destination.Valuefff.ShouldEqual(0);
			}

			[Fact]
			public void Should_not_throw_any_configuration_errors()
			{
				typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Mapper.DynamicMap<Source, Destination>(new Source { Value = 5 }));
			}
		}

		public class When_mapping_to_an_existing_destination_object : NonValidatingSpecBase
		{
			private Destination _destination;

			public class Source
			{
				public int Value { get; set; }
				public int Value2 { get; set; }
			}

			public class Destination
			{
				public int Valuefff { get; set; }
				public int Value2 { get; set; }
			}

			protected override void Because_of()
			{
				_destination = new Destination { Valuefff = 7};
				Mapper.DynamicMap(new Source { Value = 5, Value2 = 3}, _destination);
			}

			[Fact]
			public void Should_preserve_existing_values()
			{
				_destination.Valuefff.ShouldEqual(7);
			}

			[Fact]
			public void Should_map_new_values()
			{
				_destination.Value2.ShouldEqual(3);
			}
		}

#if !SILVERLIGHT && !NETFX_CORE
		public class When_mapping_from_an_anonymous_type_to_an_interface : SpecBase
		{
			private IDestination _result;

			public interface IDestination
			{
				int Value { get; set; }
			}

			protected override void Because_of()
			{
				_result = Mapper.DynamicMap<IDestination>(new {value = 5});
			}

			[Fact]
			public void Should_allow_dynamic_mapping()
			{
				_result.Value.ShouldEqual(5);
			}
		}
#endif
	}
}


text:
'use strict';

describe('AndNode', () => {
  let Node = require('../../src/Tree/Node.js');
  let AndNode = require('../../src/Tree/AndNode.js');
  let ExpectedCallNode = require('../../src/Tree/ExpectedCallNode.js');
  let Mock = require('../../src/Mock.js');
  let ExpectedCall = require('../../src/ExpectedCall.js');

  it('should be named AND + expectedCalls', () => {
    expect(new AndNode({
      name: 'foo'
    }).name).toEqual('AND {{ foo }}');
  });

  it('should have an expectedCall', () => {
    expect(new AndNode({
      name: 'foo'
    }).expectedCalls[0].name).toEqual('foo');
  });

  describe('merge', () => {
    it('should merge with another AndNode', () => {
      let a = new AndNode({
        name: 'a'
      });

      let b = new AndNode({
        name: 'b'
      });

      a.merge(b);

      expect(a.expectedCalls.length).toEqual(2);

      expect(a.expectedCalls[0].name).toEqual('a');
      expect(a.expectedCalls[1].name).toEqual('b');
    });

    it('should merge with an ExpectedCallNode', () => {
      let a = new AndNode({
        name: 'a'
      });

      let b = new ExpectedCallNode({
        name: 'b'
      });

      a.merge(b);

      expect(a.expectedCalls.length).toEqual(2);

      expect(a.expectedCalls[0].name).toEqual('a');
      expect(a.expectedCalls[1].name).toEqual('b');
    });

    it('should throw an error if node is invalid type', () => {
      let a = new AndNode({
        name: 'a'
      });

      let b = new Node('node');

      expect(() => a.merge(b))
        .toThrowError('Unexpected type for node, expected AndNode or ExpectedCallNode');
    });
  });

  describe('match', () => {
    it('should return undefined if all the calls are completed', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(mock._class, [], true, false));
      let b = new AndNode(new ExpectedCall(mock._class, [], true, false));

      a.merge(b);

      for(let expectedCall of a.expectedCalls) {
        expectedCall.execute([]);
      }

      expect(a.match(mock._class, [])).toBeUndefined();
    });

    it('should return undefined if no expected calls match', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(new Mock('a')._class, [], true, true));
      let b = new AndNode(new ExpectedCall(mock._class, [0], true, true));

      a.merge(b);

      expect(a.match(mock, [1])).toBeUndefined();
    });

    it('should return an expected call if the expected call matches', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(mock._class, [], true, true));

      expect(a.match(mock._class, [])).not.toBeUndefined();
    });
  });

  describe('partialMatch', () => {
    it('should return false if all the calls are completed', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(mock._class, [], true, false));
      let b = new AndNode(new ExpectedCall(mock._class, [], true, false));

      a.merge(b);

      for(let expectedCall of a.expectedCalls) {
        expectedCall.execute([]);
      }

      expect(a.partialMatch(mock, [])).toBe(false);
    });

    it('should return false if no expected calls match', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(new Mock('a')._class, [], true, true));
      let b = new AndNode(new ExpectedCall(new Mock('b')._class, [], true, true));

      a.merge(b);

      expect(a.partialMatch(mock, [])).toBe(false);
    });

    it('should return an expected call if the expected call matches', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(mock._class, [], true, true));

      expect(a.partialMatch(mock._class, [])).toBe(true);
    });
  });

  describe('onlyOptionalRemain', () => {
    it('should return true if all calls are complete', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(mock._class, [], true, false));
      let b = new AndNode(new ExpectedCall(mock._class, [], true, false));

      a.merge(b);

      for(let expectedCall of a.expectedCalls) {
        expectedCall.execute([]);
      }

      expect(a.onlyOptionalRemain()).toBe(true);
    });

    it('should return false if any incomplete calls are required', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(mock._class, [], true, false));
      let b = new AndNode(new ExpectedCall(mock._class, [], true, false));

      a.merge(b);

      a.expectedCalls[0].execute([]);

      expect(a.onlyOptionalRemain()).toBe(false);
    });

    it('should return true if all incomplete calls are optional', () => {
      let mock = new Mock('mock');
      let a = new AndNode(new ExpectedCall(mock._class, [], true, false));
      let b = new AndNode(new ExpectedCall(mock._class, [], false, false));

      a.merge(b);

      a.expectedCalls[0].execute([]);

      expect(a.onlyOptionalRemain()).toBe(true);
    });
  });

  describe('toString()', () => {
    it('should include expectedCalls', () => {
      let a = new AndNode({
        name: 'a'
      });

      let b = new AndNode({
        name: 'b'
      });

      expect(a.toString()).toEqual('{ AND {{ a }} }');

      a.merge(b);

      expect(a.toString()).toEqual('{ AND {{ a, b }} }');
    });

    it('should include the child if it exists', () => {
      let a = new AndNode({
        name: 'a'
      });

      let b = new AndNode({
        name: 'b'
      });

      a.child = b;

      expect(a.toString()).toEqual('{ AND {{ a }} [{ AND {{ b }} }] }');
    });
  });
});


text:
layout: post
title: Get your own Facebook style navigation bar with HMScrollNavigationBar
---

Have you ever seen a navigation bar in your Facebook app? Maybe you've wondered how to do it? Now, with our simple library, you can have the same feature in your own app!

## Example

![ScrollGif](/images/scroll.gif)

## How it work ?

It's really quite simple - our navigationBarAnimator is a property in the UIViewController. This is a object of HMNavigationBarAnimator type which implements UIScrollViewDelegate protocol.

When you run a setup function providing your UIScrollView element and UIView (your custom view which will be your navigation bar) as parameters, a navigationBarManager starts acting as a delegate of UIScrollView. When scroll is detected, we start calculation of the height at which your navigation bar and UIScrollView should now be and then, if needed, we start an animate function from UIView.

The navigation bar hides immediately when you scroll down and shows with delay when you scroll up, just like a Facebook navigation bar.

The code has been written in Swift 3.0.

Here is a link to our repo (https://github.com/HandcraftedMobile/HMScrollNavigationBar)

Posted by: Piotr Sękara, https://github.com/piotr-sekara


text:
using System;
using System.Collections.Generic;

using MsgPack.Serialization.CollectionSerializers;
using MsgPack.Serialization.Polymorphic;

namespace MsgPack.Serialization.DefaultSerializers
{
	internal sealed class AbstractReadOnlyDictionaryMessagePackSerializer<TDictionary, TKey, TValue> : ReadOnlyDictionaryMessagePackSerializer<TDictionary, TKey, TValue>
		where TDictionary : IReadOnlyDictionary<TKey, TValue>
	{
		private readonly ICollectionInstanceFactory _concreteCollectionInstanceFactory;
		private readonly IPolymorphicDeserializer _polymorphicDeserializer;
		private readonly IMessagePackSingleObjectSerializer _concreteDeserializer;

		public AbstractReadOnlyDictionaryMessagePackSerializer(
			SerializationContext ownerContext,
			Type targetType,
			PolymorphismSchema schema
		)
			: base( ownerContext, schema )
		{
			IMessagePackSingleObjectSerializer serializer;
			AbstractCollectionSerializerHelper.GetConcreteSerializer(
				ownerContext,
				schema,
				typeof( TDictionary ),
				targetType,
				typeof( DictionaryMessagePackSerializer<,,> ),
				out this._concreteCollectionInstanceFactory,
				out serializer
			);
			this._polymorphicDeserializer = serializer as IPolymorphicDeserializer;
			this._concreteDeserializer = serializer;
		}

		internal override TDictionary InternalUnpackFromCore( Unpacker unpacker )
		{
			if ( this._polymorphicDeserializer != null )
			{
				// This boxing is OK because TCollection should be reference type because TCollection is abstract class or interface.
				return
					( TDictionary )this._polymorphicDeserializer.PolymorphicUnpackFrom( unpacker );
			}
			else if ( this._concreteDeserializer != null )
			{
				return ( TDictionary )this._concreteDeserializer.UnpackFrom( unpacker );
			}
			else
			{
				return base.InternalUnpackFromCore( unpacker );
			}
		}

		protected override TDictionary CreateInstance( int initialCapacity )
		{
			// This boxing is OK because TCollection should be reference type because TCollection is abstract class or interface.
			return
				( TDictionary )this._concreteCollectionInstanceFactory.CreateInstance( initialCapacity );
		}
	}
}


text:
package org.kuali.rice.kew.rule.bo;

import org.apache.commons.lang.StringUtils;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.extension.ExtensionDefinition;
import org.kuali.rice.kew.api.extension.ExtensionDefinitionContract;
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase;
import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Model bean defining a rule attribute.  Includes the classname of the attribute
 * class, as well as it's name and other information.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
@Entity
@Table(name="KREW_RULE_ATTR_T")
public class RuleAttribute extends PersistableBusinessObjectBase implements ExtensionDefinitionContract {

	private static final long serialVersionUID = 1027673603158346349L;

	@Id
    @PortableSequenceGenerator(name="KREW_RTE_TMPL_S")
	@GeneratedValue(generator="KREW_RTE_TMPL_S")
	@Column(name="RULE_ATTR_ID")
	private String id;
    @Column(name="NM")
	private String name;
    @Column(name="LBL")
	private String label;
    @Column(name="RULE_ATTR_TYP_CD")
	private String type;
    @Column(name="CLS_NM")
	private String resourceDescriptor;
    @Column(name="DESC_TXT")
	private String description;
    @Lob
	@Basic(fetch=FetchType.LAZY)
	@Column(name="XML")
	private String xmlConfigData;

    @Column(name="APPL_ID")
	private String applicationId;

    @OneToMany(fetch=FetchType.EAGER,cascade={CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE},
           targetEntity=RuleTemplateAttributeBo.class, mappedBy="ruleAttribute")
	private List ruleTemplateAttributes;
    @Transient
    private List validValues;

    // required to be lookupable
    @Transient
    private String returnUrl;

    public RuleAttribute() {
        ruleTemplateAttributes = new ArrayList();
        validValues = new ArrayList();
    }

    public List getValidValues() {
        return validValues;
    }
    public void setValidValues(List ruleAttributeValidValues) {
        this.validValues = ruleAttributeValidValues;
    }
    public List getRuleTemplateAttributes() {
        return ruleTemplateAttributes;
    }
    public void setRuleTemplateAttributes(List ruleTemplateAttributes) {
        this.ruleTemplateAttributes = ruleTemplateAttributes;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getLabel() {
        return label;
    }
    public void setLabel(String label) {
        this.label = label;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @return Returns the resourceDescriptor.
     */
    public String getResourceDescriptor() {
      return resourceDescriptor;
    }
    /**
     * @param resourceDescriptor The className to set.
     */
    public void setResourceDescriptor(String resourceDescriptor) {
      this.resourceDescriptor = resourceDescriptor;
    }

    public String getRuleAttributeActionsUrl() {
        return "report";
    }

    public String getReturnUrl() {
        return returnUrl;
    }
    public void setReturnUrl(String returnUrl) {
        this.returnUrl = returnUrl;
    }

	public String getXmlConfigData() {
		return xmlConfigData;
	}

    @Override
    public Map<String, String> getConfiguration() {
        Map<String, String> config = new HashMap<String, String>();
        if (StringUtils.isNotBlank(getXmlConfigData())) {
            config.put(KewApiConstants.ATTRIBUTE_XML_CONFIG_DATA, getXmlConfigData());
        }
        return config;
    }

	public void setXmlConfigData(String xmlConfigData) {
		this.xmlConfigData = xmlConfigData;
	}

    @Override
	public String getApplicationId() {
		return applicationId;
	}

	public void setApplicationId(String applicationId) {
		this.applicationId = applicationId;
	}

    public boolean isWorkflowAttribute() {
        return isWorkflowAttribute(getType());
    }

    public static boolean isWorkflowAttribute(String type) {
        return KewApiConstants.RULE_ATTRIBUTE_TYPE.equals(type) ||
            KewApiConstants.RULE_XML_ATTRIBUTE_TYPE.equals(type);
    }

    public static ExtensionDefinition to(RuleAttribute ruleAttribute) {
        if (ruleAttribute == null) {
            return null;
        }
        return ExtensionDefinition.Builder.create(ruleAttribute).build();
    }

    public static RuleAttribute from(ExtensionDefinition im) {
        if (im == null) {
            return null;
        }
        RuleAttribute bo = new RuleAttribute();
        bo.setApplicationId(im.getApplicationId());
        bo.setDescription(im.getDescription());
        bo.setResourceDescriptor(im.getResourceDescriptor());
        bo.setId(im.getId());
        bo.setLabel(im.getLabel());
        bo.setType(im.getType());
        bo.setVersionNumber(im.getVersionNumber());
        bo.setXmlConfigData(im.getConfiguration().get(KewApiConstants.ATTRIBUTE_XML_CONFIG_DATA));

        return bo;
    }
}


text:
package pl.java.scalatech.service;

import javax.jws.WebService;

import pl.java.scalatech.domain.Customer;

@WebService
public interface CustomerService {

    Customer findById(Long i);

}


text:
using System.Configuration;
using static System.Int32;

namespace Jobs.WindowsService.Configuration
{
    public class JobsServiceConfigurationSection : ConfigurationSection
    {
        #region properties

        [ConfigurationProperty("description")]
        public string Description => this["description"] as string;

        [ConfigurationProperty("displayname")]
        public string DisplayName => this["displayname"] as string;

        [ConfigurationProperty("log")]
        public Log Log => this["log"] as Log;

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name => this["name"] as string;

        [ConfigurationProperty("secondsinterval", DefaultValue = "10")]
        public int SecondsInterval
        {
            get
            {
                int secondsInterval;
                return TryParse(this["secondsinterval"] as string, out secondsInterval)
                           ? secondsInterval
                           : 10;
            }
        }

        #endregion

        #region methods

        public static JobsServiceConfigurationSection GetSection(string section) => ConfigurationManager.GetSection(section) as JobsServiceConfigurationSection;

        #endregion
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Chordecystia C.B. Foster

### Remarks
null


text:
class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.string :name
      t.boolean :archive
      t.references :user, index: true

      t.timestamps
    end
  end
end


text:
from django.core.exceptions import ImproperlyConfigured
from django.forms import ModelForm
from django.http import HttpResponseRedirect
from django.views.generic.base import ContextMixin, View

try:
    from crispy_forms.helper import FormHelper
except ImportError:
    pass

__all__ = (
    "FormsMixin",
    "ModelFormsMixin",
    "FormSetMixin",
    "FormsView",
    "BSFormSetMixin",
)

class FormsMixin(ContextMixin):
    """
    A mixin that provides a way to show and handle any number of form in a request.
    """

    initial = {}
    form_classes = None  # the main form should named as form
    success_url = None

    def get_initial(self, form_class_key):
        return self.initial.get(form_class_key, {}).copy()

    def get_form_classes(self):
        """
        Returns the form classes to use in this view
        """
        if not self.form_classes:
            raise ImproperlyConfigured("Provide form_classes.")
        return self.form_classes

    def after_create_form(self, form_class_key, form):
        return form

    def create_form(self, form_class_key, form_class):
        form = form_class(**self.get_form_kwargs(form_class_key, form_class))
        self.after_create_form(form_class_key, form)
        return form

    def create_forms(self, **form_classes):
        """
        Returns an instance of the forms to be used in this view.
        forms can be access by self.forms
        """
        forms = {}
        self.forms = forms
        for form_class_key, form_class in form_classes.items():
            forms[form_class_key] = self.create_form(
                form_class_key, form_class
            )
        return forms

    def get_form_kwargs(self, form_class_key, form_class):
        """
        Returns the keyword arguments for instantiating the form.
        """
        kwargs = {"initial": self.get_initial(form_class_key)}
        if form_class_key != "form":
            kwargs["prefix"] = form_class_key
        if self.request.method in ("POST", "PUT"):
            kwargs.update(
                {
                    "data": self.request.POST,
                    "files": self.request.FILES,
                }
            )
        return kwargs

    def get_success_url(self):
        """
        Returns the supplied success URL.
        """
        if self.success_url:
            # Forcing possible reverse_lazy evaluation
            url = self.success_url
        else:
            raise ImproperlyConfigured(
                "No URL to redirect to. Provide a success_url."
            )
        return url

    def forms_valid(self, **forms):
        """
        If the forms are valid, redirect to the supplied URL.
        """
        return HttpResponseRedirect(self.get_success_url())

    def forms_invalid(self, **forms):
        """
        If the forms are invalid, re-render the context data with the
        data-filled form and errors.
        """
        return self.render_to_response(self.get_context_data(**forms))

class ModelFormsMixin:
    def get_form_kwargs(self, form_class_key, form_class):
        kwargs = super().get_form_kwargs(form_class_key, form_class)
        # not (ModelForm or ModelFormSet)
        formset_form_class = getattr(form_class, "form", str)
        if not issubclass(form_class, ModelForm) and not issubclass(
            formset_form_class, ModelForm
        ):
            return kwargs
        instance = getattr(self, "object", None)
        # if have main form, try to get instance from main form
        # other form may have ForeignKey to main object
        form = self.forms.get("form")
        if form and getattr(form, "instance", None):
            instance = getattr(form, "instance", None)
        kwargs["instance"] = instance
        return kwargs

def is_formset(form):
    # form class
    if getattr(form, "__name__", "").endswith("FormSet"):
        return True
    # form instance
    return type(form).__name__.endswith("FormSet")

class FormSetMixin:
    def get_context_data(self, **kwargs):
        kwargs = super().get_context_data(**kwargs)
        formset_list = []
        for form in self.forms.values():
            if is_formset(form):
                formset_list.append(form)
        kwargs["formset_list"] = formset_list
        return kwargs

    def after_create_formset(self, form_class_key, formset):
        formset.title = "Items"

    def after_create_form(self, form_class_key, form):
        super().after_create_form(form_class_key, form)
        if is_formset(form):
            self.after_create_formset(form_class_key, form)
        return form

    def get_formset_kwargs(self, form_class_key, form_class):
        return {}

    def get_form_kwargs(self, form_class_key, form_class):
        kwargs = super().get_form_kwargs(form_class_key, form_class)
        if is_formset(form_class):
            return kwargs
        ext_kwargs = self.get_formset_kwargs(form_class_key, form_class)
        kwargs.update(ext_kwargs)
        return kwargs

class FormsView(FormSetMixin, ModelFormsMixin, FormsMixin, View):
    """
    A mixin that renders any number of forms on GET and processes it on POST.
    """

    def get(self, request, *args, **kwargs):
        """
        Handles GET requests and instantiates a blank version of the forms.
        """
        form_classes = self.get_form_classes()
        forms = self.create_forms(**form_classes)
        return self.render_to_response(self.get_context_data(**forms))

    def post(self, request, *args, **kwargs):
        """
        Handles POST requests, instantiating a form instance with the passed
        POST variables and then checked for validity.
        """
        form_classes = self.get_form_classes()
        forms = self.create_forms(**form_classes)
        if all([forms[form].is_valid() for form in forms]):
            return self.forms_valid(**forms)
        else:
            return self.forms_invalid(**forms)

    # PUT is a valid HTTP verb for creating (with a known URL) or editing an
    # object, note that browsers only support POST for now.
    def put(self, *args, **kwargs):
        return self.post(*args, **kwargs)

class BSFormSetMixin:
    """
    Crispy & Bootstrap for formset
    """

    def after_create_formset(self, form_class_key, formset):
        super().after_create_formset(form_class_key, formset)
        helper = FormHelper()
        helper.template = "lbadminlte/bootstrap3/table_inline_formset.html"
        formset.helper = helper
        return formset


text:
#ifndef F264DEC_API_H
#define F264DEC_API_H

#ifdef __cplusplus
extern "C" {
#endif

typedef enum dec_status
{

	DEC_ERROR =	-1,
	DEC_SUCCESS	,
	DEC_NEED_MORE_BITS,
	DEC_NO_PICTURE,
	DEC_BUF_OVERFLOW
}DEC_STATUS;

typedef void* F264_DEC;

typedef struct f264_frame
{
	int		iPicFlag;		//0: Frame, 1: Filed
	int		iKeyFlag;		//0: Not key frame, 1:Key frame
	int		iWidth;			//The width of output picture in pixel
	int		iHeight;		//The height of output picture in pixel
	int		iStrideY;		//Luma plane stride in pixel
	int		iStrideUV;		//Chroma plane stride in pixel

	unsigned char *pY;		//Y plane base address of the picture
	unsigned char *pU;		//U plane base address of the picture
	unsigned char *pV;		//V plane base address of the picture
}F264_FRAME;

/*********************************************************************
* Function Name  : F264DecLibVer
* Description    : display f264 decoder lib version
* Parameters     : none
* Return Type    : none
*********************************************************************/
void F264DecLibVer();

/*********************************************************************
* Function Name  : F264Dec_Init
* Description    : init h264 decoder module, should be called before
*				   any operation, and only be called once!
* Parameters     : none
* Return Type    : F264DEC_SUCCESS, success
*                  otherwise, error
*********************************************************************/
int F264DecInit();

/*********************************************************************
* Function Name  : F264Dec_Open
* Description    : open a decoder handle for decoding stream
* Parameters     : none
* Return Type    : handle, success
*                  NULL, error
*********************************************************************/
F264_DEC F264DecOpen();

/*********************************************************************
* Function Name  : F264Dec_DecodeFrame
* Description    : decode input stream
* Parameters     : hHandle, decoder handle
*                : pBuf, point to input data if you have
*                : uBufLen, input data length
*                : pFrame, point to frame info return from decoder
*                : iFlag, set to 1 if no more data, otherwise set to 0
* Return Type    : F264DEC_SUCCESS, one frame has been decode
*                : F264DEC_NEED_MORE_BITS, need more data to decode
*				 : F264DEC_NO_PICTURE, no more data in decoder input buffer
*				 : F264DEC_BUF_OVERFLOW, decoder buffer can't hold too much input data
*                : otherwise, error
*********************************************************************/
int F264DecFrame(F264_DEC hHandle,unsigned char *pBuf,unsigned int uBufLen,F264_FRAME *pFrame,int iFlag);

/*********************************************************************
* Function Name  : F264Dec_Close
* Description    : close decoder
* Parameters     : hHandle, decoder handle
* Return Type    : F264DEC_SUCCESS, success
*                  otherwise, error
*********************************************************************/
int F264DecClose(F264_DEC hHandle);

/*********************************************************************
* Function Name  : F264Dec_Release
* Description    : close h264 decoder module
* Parameters     : none
* Return Type    : don't care
*********************************************************************/
int F264DecRelease();

#ifdef __cplusplus
}
#endif

#endif //API_H


text:
require "spec_helper"
require "cli"

RSpec.describe AdminCLI do

  subject(:admin_cli) { described_class.new }

  let(:admin) { FactoryBot.create :admin }
  let(:username) { "username" }
  let(:password) { "password" }
  let(:email) { "user@example.com" }
  let(:admin_params) do
    {
      path:    "/admin-api/v1/admins",
      method:  :post,
      payload: {
        admin: {
          username: username,
          email:    email,
          password: password
        }
      }

    }
  end

  before { allow(BrainAdminApi).to receive(:request).and_return [OpenStruct.new(code: 201), nil] }

  describe "#create" do
    context "when no admin user exists" do
      it "does not ask for any password" do
        allow(CLI).to receive :ask_admin_credentials
        allow(CLI).to receive(:ask_new_password).and_return password
        admin_cli.create username, email
        expect(CLI).not_to have_received :ask_admin_credentials
      end

      it "creates a first admin user" do
        allow(CLI).to receive(:ask_new_password).and_return password
        admin_cli.create username, email
        expect(BrainAdminApi).to have_received(:request).with admin_params
      end
    end

    context "when an admin user exists" do
      before { admin }

      it "asks for admin credentials" do
        allow(CLI).to receive :ask_admin_credentials
        allow(CLI).to receive(:ask_new_password).and_return password
        admin_cli.create username, email
        expect(CLI).to have_received :ask_admin_credentials
      end
    end

    context "when a password is provided" do
      it "does not ask for a new password" do
        allow(CLI).to receive :ask_new_password
        admin_cli.create username, email, password
        expect(CLI).not_to have_received :ask_new_password
      end
    end
  end

end


text:
@interface GroupSetUpNameViewController()<UITextFieldDelegate>

@property (nonatomic ,strong) UITextField *textFild;
@end

@implementation GroupSetUpNameViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad{
    [super viewDidLoad];

    [self setTitleViewWithStr:self.titleStr];

    [self layoutUI];

    [self leftBarButtonItem:[UIImage imageNamed:@"BackArrow"] withClickBtnAction:^{
        [self.navigationController popViewControllerAnimated:YES];
        if (self.changeContentBlock) {
            self.changeContentBlock(_textFild.text);
        }
    }];

}

- (void)layoutUI{

    _textFild = [[UITextField alloc]init];
    _textFild.text = self.content;
    _textFild.background = [UIImage imageNamed:@"enter_frame_bg"];
    _textFild.font = [UIFont systemFontOfSize:15];
    _textFild.textColor = AllBulbTitleColor;
    [self.view addSubview:_textFild];

    [_textFild mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(51);
        make.top.mas_equalTo(15);
        make.width.mas_equalTo(self.view.mas_width);

    }];

    UILabel *line = [[UILabel alloc]init];
    line.backgroundColor = AllBulbLineColor;
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textFild.mas_bottom).offset(1);
        make.width.mas_equalTo(_textFild.mas_width);
        make.height.mas_equalTo(1);
    }];

}
@end


text:
namespace RouteExtreme.Services.Contracts
{
    using System.Linq;
    using Models;

    public interface IUserService
    {
        void Create(User user, string password);

        IQueryable<User> GetAll();

        IQueryable<User> GetById(string id);

        IQueryable<User> GetByUsername(string username);

        void UpdateUser(User updatedUser);

        void Delete(string id);

        void MarkAsDeleted(User user);
    }
}


text:
int buildParseTree(FILE *, struct parsenode *);
int shouldReduce(struct parseStack, token *);
// int isTokenInPredictSet(struct parsenode, token);


text:
file(REMOVE_RECURSE
  "CMakeFiles/Tutorial.dir/tutorial.cxx.o"
  "Tutorial.pdb"
  "Tutorial"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/Tutorial.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
using System.Collections.Generic;
using System.Linq;
using OAuthStack.Common.ServiceModel;
using OAuthStack.Common.Services;

namespace OAuthStack.FakeServices {
    /// <summary>A fake in-memory implementation of a user database.</summary>
    public class FakeUserStore : IUserStore {
        private static List<User> users = new List<User>();
        static FakeUserStore() {
            users.Add(new User { Username = "evh", Password = "eddie5150", Forenames = "Eddie", Surname = "Van Halen", Email = "eddie@van-halen.com" });
            users.Add(new User { Username = "satch", Password = "surfer101", Forenames = "Joe", Surname = "Satriani", Email = "joe@satch.com" });
            users.Add(new User { Username = "knopfler", Password = "5ultans", Forenames = "Mark", Surname = "Knopfler", Email = "mark@money4nothing.com" });
            users.Add(new User { Username = "matt_b", Password = "Hy5teria", Forenames = "Matt", Surname = "Bellamy", Email = "matt@muse.mu" });
        }
        public User GetUser(string username) {
            return (users.FirstOrDefault(user => user.Username == username));
        }
    }
}