create a circular doubly linked list from polygon points in the specified winding order
969085
function linkedList (data, start, end, dim, clockwise) {
  var sum = 0,
    i, j, last

  // calculate original winding order of a polygon ring
  for (i = start, j = end - dim; i < end; i += dim) {
    sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1])
    j = i
  }

  // link points into circular doubly-linked list in the specified winding order
  if (clockwise === (sum > 0)) {
    for (i = start; i < end; i += dim) {
      last = insertNode(i, last)
    }
  } else {
    for (i = end - dim; i >= start; i -= dim) {
      last = insertNode(i, last)
    }
  }

  return last
}
849359
def polygonize_full
      cuts = FFI::MemoryPointer.new(:pointer)
      dangles = FFI::MemoryPointer.new(:pointer)
      invalid_rings = FFI::MemoryPointer.new(:pointer)

      rings = cast_geometry_ptr(FFIGeos.GEOSPolygonize_full_r(Geos.current_handle_pointer, ptr, cuts, dangles, invalid_rings), srid_copy: srid)

      cuts = cast_geometry_ptr(cuts.read_pointer, srid_copy: srid)
      dangles = cast_geometry_ptr(dangles.read_pointer, srid_copy: srid)
      invalid_rings = cast_geometry_ptr(invalid_rings.read_pointer, srid_copy: srid)

      {
        rings: rings.to_a,
        cuts: cuts.to_a,
        dangles: dangles.to_a,
        invalid_rings: invalid_rings.to_a
      }
    end
872343
def polygon_list(self):
        ''''''
        done = set()
        ret = []
        while len(done) != self.count():
            p = self.polygon(done)
            if len(p) > 0:
                ret.append(p)
        return ret
196734
def generate_cylindrical_points(start, end, start_radius, end_radius,
                                linspace_count=_LINSPACE_COUNT):
    '''
    '''
    v = end - start
    length = norm(v)
    v = v / length
    n1, n2 = _get_normals(v)

    # pylint: disable=unbalanced-tuple-unpacking
    l, theta = np.meshgrid(np.linspace(0, length, linspace_count),
                           np.linspace(0, 2 * np.pi, linspace_count))

    radii = np.linspace(start_radius, end_radius, linspace_count)
    rsin = np.multiply(radii, np.sin(theta))
    rcos = np.multiply(radii, np.cos(theta))

    return np.array([start[i] +
                     v[i] * l +
                     n1[i] * rsin + n2[i] * rcos
                     for i in range(3)])
955940
function ( contour, indices ) {

		var n = contour.length;

		if ( n < 3 ) return null;

		var result = [],
			verts = [],
			vertIndices = [];

		/* we want a counter-clockwise polygon in verts */

		var u, v, w;

		if ( area( contour ) > 0.0 ) {

			for ( v = 0; v < n; v ++ ) verts[ v ] = v;

		} else {

			for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;

		}

		var nv = n;

		/*  remove nv - 2 vertices, creating 1 triangle every time */

		var count = 2 * nv;   /* error detection */

		for ( v = nv - 1; nv > 2; ) {

			/* if we loop, it is probably a non-simple polygon */

			if ( ( count -- ) <= 0 ) {

				//** Triangulate: ERROR - probable bad polygon!

				//throw ( "Warning, unable to triangulate polygon!" );
				//return null;
				// Sometimes warning is fine, especially polygons are triangulated in reverse.
				console.log( 'Warning, unable to triangulate polygon!' );

				if ( indices ) return vertIndices;
				return result;

			}

			/* three consecutive vertices in current polygon, <u,v,w> */

			u = v; 	 	if ( nv <= u ) u = 0;     /* previous */
			v = u + 1;  if ( nv <= v ) v = 0;     /* new v    */
			w = v + 1;  if ( nv <= w ) w = 0;     /* next     */

			if ( snip( contour, u, v, w, nv, verts ) ) {

				var a, b, c, s, t;

				/* true names of the vertices */

				a = verts[ u ];
				b = verts[ v ];
				c = verts[ w ];

				/* output Triangle */

				result.push( [ contour[ a ],
					contour[ b ],
					contour[ c ] ] );


				vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );

				/* remove v from the remaining polygon */

				for ( s = v, t = v + 1; t < nv; s++, t++ ) {

					verts[ s ] = verts[ t ];

				}

				nv --;

				/* reset error detection counter */

				count = 2 * nv;

			}

		}

		if ( indices ) return vertIndices;
		return result;

	}
235522
function toSfntCoutours(svgPath) {
  var resContours = [];
  var resContour = [];

  svgPath.iterate(function (segment, index, x, y) {

    //start new contour
    if (index === 0 || segment[0] === 'M') {
      resContour = [];
      resContours.push(resContour);
    }

    var name = segment[0];

    if (name === 'Q') {
      //add control point of quad spline, it is not on curve
      resContour.push({ x: segment[1], y: segment[2], onCurve: false });
    }

    // add on-curve point
    if (name === 'H') {
      // vertical line has Y coordinate only, X remains the same
      resContour.push({ x: segment[1], y: y, onCurve: true });
    } else if (name === 'V') {
      // horizontal line has X coordinate only, Y remains the same
      resContour.push({ x: x, y: segment[1], onCurve: true });
    } else if (name !== 'Z') {
      // for all commands (except H and V) X and Y are placed in the end of the segment
      resContour.push({ x: segment[segment.length - 2], y: segment[segment.length - 1], onCurve: true });
    }

  });
  return resContours;
}
737044
def tangent_loop
	    edges.map {|e| e.direction }.tap do |tangents|
		# Generating a bisector for each vertex requires an edge on both sides of each vertex.
		# Obviously, the first and last vertices each have only a single adjacent edge, unless the
		# Polyline happens to be closed (like a Polygon). When not closed, duplicate the
		# first and last direction vectors to fake the adjacent edges. This causes the first and last
		# edges to have bisectors that are perpendicular to themselves.
		if closed?
		    # Prepend the last direction vector so that the last edge can be used to find the bisector for the first vertex
		    tangents.unshift tangents.last
		else
		    # Duplicate the first and last direction vectors to compensate for not having edges adjacent to the first and last vertices
		    tangents.unshift(tangents.first)
		    tangents.push(tangents.last)
		end
	    end
	end
488642
function topologicalSort(graph) {
    var processed = [],
        unprocessed = [],
        queue = [];

    /**
     *
     * @param arr
     * @param callback
     * @this {Object}
     */
    function each(arr, callback) {
        var i = void 0;

        // if Array, then process as array
        if (arr instanceof Array) {
            for (i = 0; i < arr.length; i++) {
                callback.call(arr[i], i);
            }
        }

        // if object, iterate over property/keys
        else {
                for (i in arr) {
                    if (arr.hasOwnProperty(i)) {
                        callback.call(arr[i], i);
                    }
                }
            }
    }

    function processStartingPoint(node) {
        if (node === undefined) {
            throw 'You have a cycle!!';
        }
        each(node.edges, function () {
            node.sortImportance--;
        });
        processed.push(node);
    }

    var populateIndegreesAndUnprocessed = function populateIndegreesAndUnprocessed() {
        each(graph.nodes, function () {
            var self = this;
            unprocessed.push(this);
            if (!Object.prototype.hasOwnProperty.call(self, 'sortImportance')) {
                self.sortImportance = 0;
            }

            each(self.edges, function () {
                self.sortImportance++;
            });
        });
    };

    populateIndegreesAndUnprocessed();

    while (unprocessed.length > 0) {
        for (var i = 0; i < unprocessed.length; i++) {
            var node = unprocessed[i];
            if (node.sortImportance === 0) {
                queue.push(node);
                unprocessed.splice(i, 1); // Remove this node, its all done.
                i--; // decrement i since we just removed that index from the iterated list;
            } else {
                node.sortImportance--;
            }
        }

        if (queue.length > 0) {
            processStartingPoint(queue.shift());
        }
    }

    return processed;
}
213715
function (listItemContainers, node) {
        var isOrdered = node.nodeName === 'OL';
        var startIndex = parseInt(node.getAttribute('start'), 10) || 1; // only applicable to ordered lists
        var blocks = (listItemContainers || []).map((listItemContainer, listItemIndex) => {
            var listItemElems = unwrap(listItemContainer);
            var firstListItemElem = listItemElems[0];
            if (firstListItemElem && isTextBlock(firstListItemElem)) {
                let firstListItemPrefix = isOrdered ? `${startIndex + listItemIndex}. ` : `- `;
                firstListItemElem.text = firstListItemPrefix + firstListItemElem.text;
            }
            return listItemElems;
        }).reduce((prevBlocks, listItemBlocks) => {
            return prevBlocks.concat(listItemBlocks);
        }, []);
        return wrap(blocks);
    }
1237145
private void generateOrderedDepGraph() {
		TopologicalOrderIterator<Predicate, DefaultEdge> iter =
				new TopologicalOrderIterator<Predicate, DefaultEdge>(predicateDependencyGraph);
		
		while (iter.hasNext()){
			Predicate pred = iter.next();
			predicatesInBottomUp.add(pred);
		}
		Collections.reverse(predicatesInBottomUp);
	}
866757
private static List<JoinNode> generateInnerJoinOrdersForTree(JoinNode subTree) {
        // Get a list of the leaf nodes(tables) to permute them
        List<JoinNode> tableNodes = subTree.generateLeafNodesJoinOrder();
        List<List<JoinNode>> joinOrders = PermutationGenerator.generatePurmutations(tableNodes);
        List<JoinNode> newTrees = new ArrayList<>();
        for (List<JoinNode> joinOrder: joinOrders) {
            newTrees.add(JoinNode.reconstructJoinTreeFromTableNodes(joinOrder, JoinType.INNER));
        }
        //Collect all the join/where conditions to reassign them later
        AbstractExpression combinedWhereExpr = subTree.getAllFilters();
        List<JoinNode> treePermutations = new ArrayList<>();
        for (JoinNode newTree : newTrees) {
            if (combinedWhereExpr != null) {
                newTree.setWhereExpression(combinedWhereExpr.clone());
            }
            // The new tree root node id must match the original one to be able to reconnect the
            // subtrees
            newTree.setId(subTree.getId());
            treePermutations.add(newTree);
        }
        return treePermutations;
    }
1113062
def from_list(lst):
        
        if not lst:
            return None

        head = Node(lst[0], None)

        if len(lst) == 1:
            return head

        head.next_node = LinkedList.from_list(lst[1:])
        return head
795
function createEdgeIterator(graph, type) {
  if (graph.size === 0)
    return Iterator.empty();

  let iterator;

  if (type === 'mixed') {
    iterator = graph._edges.values();

    return new Iterator(function next() {
      const step = iterator.next();

      if (step.done)
        return step;

      const data = step.value;

      const value = [
        data.key,
        data.attributes,
        data.source.key,
        data.target.key,
        data.source.attributes,
        data.target.attributes
      ];

      return {value, done: false};
    });
  }

  iterator = graph._edges.values();

  return new Iterator(function next() {
    const step = iterator.next();

    if (step.done)
      return step;

    const data = step.value;

    if ((data instanceof UndirectedEdgeData) === (type === 'undirected')) {
      const value = [
        data.key,
        data.attributes,
        data.source.key,
        data.target.key,
        data.source.attributes,
        data.target.attributes
      ];

      return {value, done: false};
    }

    return next();
  });
}
672442
static List<Point2D> pointsOf(final Shape shape) {
        final List<Point2D> points = new ArrayList<Point2D>();
        final double[] coordinates = new double[6];
        for (PathIterator i = shape.getPathIterator(null); !i.isDone(); i.next()) {
            switch (i.currentSegment(coordinates)) {
                case PathIterator.SEG_CLOSE:
                    break;
                case PathIterator.SEG_MOVETO:
                case PathIterator.SEG_LINETO:
                    points.add(new Point2D.Double(coordinates[0], coordinates[1]));
                    break;
                case PathIterator.SEG_QUADTO:
                    points.add(new Point2D.Double(coordinates[0], coordinates[1]));
                    points.add(new Point2D.Double(coordinates[2], coordinates[3]));
                    break;
                case PathIterator.SEG_CUBICTO:
                    points.add(new Point2D.Double(coordinates[0], coordinates[1]));
                    points.add(new Point2D.Double(coordinates[2], coordinates[3]));
                    points.add(new Point2D.Double(coordinates[4], coordinates[5]));
                    break;
            }
        }

        if (!points.isEmpty() && points.get(points.size() - 1).equals(points.get(0))) {
            points.remove(points.size() - 1);
        }
        return points;
    }
318737
function createGraph(modules, circular, config, options) {
	const g = graphviz.digraph('G');
	const nodes = {};
	const cyclicModules = circular.reduce((a, b) => a.concat(b), []);

	if (config.graphVizPath) {
		g.setGraphVizPath(config.graphVizPath);
	}

	Object.keys(modules).forEach((id) => {
		nodes[id] = nodes[id] || g.addNode(id);

		if (!modules[id].length) {
			setNodeColor(nodes[id], config.noDependencyColor);
		} else if (cyclicModules.indexOf(id) >= 0) {
			setNodeColor(nodes[id], config.cyclicNodeColor);
		}

		modules[id].forEach((depId) => {
			nodes[depId] = nodes[depId] || g.addNode(depId);

			if (!modules[depId]) {
				setNodeColor(nodes[depId], config.noDependencyColor);
			}

			g.addEdge(nodes[id], nodes[depId]);
		});
	});

	return new Promise((resolve, reject) => {
		g.output(options, resolve, (code, out, err) => {
			reject(new Error(err));
		});
	});
}
230124
function generateArcPath (x, y, radius, startAngle, endAngle) {
  var start = polarToCartesian(x, y, radius, startAngle);
  var end = polarToCartesian(x, y, radius, endAngle);
  var arcSweep = endAngle - startAngle <= 180 ? '0' : '1';
  return [
    'M', start.x, start.y,
    'A', radius, radius, 0, arcSweep, 0, end.x, end.y
  ].join(' ');
}
520109
private static List<JoinNode> generateFullJoinOrdersForTree(JoinNode subTree) {
        assert(subTree != null);
        List<JoinNode> joinOrders = new ArrayList<>();
        if (!(subTree instanceof BranchNode)) {
            // End of recursion
            joinOrders.add(subTree);
            return joinOrders;
        }
        BranchNode branchNode = (BranchNode) subTree;
        // Descend to the left branch
        assert(branchNode.getLeftNode() != null);
        List<JoinNode> leftJoinOrders = generateFullJoinOrdersForTree(branchNode.getLeftNode());
        assert(!leftJoinOrders.isEmpty());
        // Descend to the right branch
        assert(branchNode.getRightNode() != null);
        List<JoinNode> rightJoinOrders = generateFullJoinOrdersForTree(branchNode.getRightNode());
        assert(!rightJoinOrders.isEmpty());
        // Create permutation pairing left and right nodes and the revere variant
        for (JoinNode leftNode : leftJoinOrders) {
            for (JoinNode rightNode : rightJoinOrders) {
                JoinNode resultOne = new BranchNode(branchNode.getId(), branchNode.getJoinType(),
                        (JoinNode) leftNode.clone(), (JoinNode) rightNode.clone());
                JoinNode resultTwo = new BranchNode(branchNode.getId(), branchNode.getJoinType(),
                        (JoinNode) rightNode.clone(), (JoinNode) leftNode.clone());
                if (branchNode.getJoinExpression() != null) {
                    resultOne.setJoinExpression(branchNode.getJoinExpression().clone());
                    resultTwo.setJoinExpression(branchNode.getJoinExpression().clone());
                }
                if (branchNode.getWhereExpression() != null) {
                    resultOne.setWhereExpression(branchNode.getWhereExpression().clone());
                    resultTwo.setWhereExpression(branchNode.getWhereExpression().clone());
                }
                joinOrders.add(resultOne);
                joinOrders.add(resultTwo);
            }
        }
        return joinOrders;
    }