connect polylines that are close and have a similar orientation
     o---o  <->  o---o  ==> o----o--o----o
    TODO: max_dist as function of cell size
7072
def connect(polylines, max_dist=10):
    
    ll = len(polylines)
    remove = []
    for n in range(ll - 1, -1, -1):
        c = polylines[n]
        if len(c) > 1:
            for d0, p0 in enumerate((c[0, 0], c[-1, 0])):
                for m in range(len(polylines) - 1, -1, -1):
                    # combine all x all polylines
                    if n == m:
                        continue
                    cc = polylines[m]

                    for d1, p1 in enumerate((cc[0, 0], cc[-1, 0])):
                        # for end points of other polylines:
                        # measure closest distance for current polyline
                        ndist = norm(p0 - p1)
                        if ndist < max_dist:
                            is_same, c = _connect(c, cc, d0, d1)
                            if is_same:
                                if m not in remove:
                                    remove.append(m)
                                polylines[n] = c
                                break
    # remove those which are already in connected to other polyline:
    remove.sort()
    remove.reverse()
    for r in remove:
        polylines.pop(r)
314909
function drawNonMono(
    ctx, points, start, segLen, allLen,
    dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
) {
    var prevIdx = 0;
    var idx = start;
    for (var k = 0; k < segLen; k++) {
        var p = points[idx];
        if (idx >= allLen || idx < 0) {
            break;
        }
        if (isPointNull(p)) {
            if (connectNulls) {
                idx += dir;
                continue;
            }
            break;
        }

        if (idx === start) {
            ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
            v2Copy(cp0, p);
        }
        else {
            if (smooth > 0) {
                var nextIdx = idx + dir;
                var nextP = points[nextIdx];
                if (connectNulls) {
                    // Find next point not null
                    while (nextP && isPointNull(points[nextIdx])) {
                        nextIdx += dir;
                        nextP = points[nextIdx];
                    }
                }

                var ratioNextSeg = 0.5;
                var prevP = points[prevIdx];
                var nextP = points[nextIdx];
                // Last point
                if (!nextP || isPointNull(nextP)) {
                    v2Copy(cp1, p);
                }
                else {
                    // If next data is null in not connect case
                    if (isPointNull(nextP) && !connectNulls) {
                        nextP = p;
                    }

                    vec2.sub(v, nextP, prevP);

                    var lenPrevSeg;
                    var lenNextSeg;
                    if (smoothMonotone === 'x' || smoothMonotone === 'y') {
                        var dim = smoothMonotone === 'x' ? 0 : 1;
                        lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
                        lenNextSeg = Math.abs(p[dim] - nextP[dim]);
                    }
                    else {
                        lenPrevSeg = vec2.dist(p, prevP);
                        lenNextSeg = vec2.dist(p, nextP);
                    }

                    // Use ratio of seg length
                    ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);

                    scaleAndAdd(cp1, p, v, -smooth * (1 - ratioNextSeg));
                }
                // Smooth constraint
                vec2Min(cp0, cp0, smoothMax);
                vec2Max(cp0, cp0, smoothMin);
                vec2Min(cp1, cp1, smoothMax);
                vec2Max(cp1, cp1, smoothMin);

                ctx.bezierCurveTo(
                    cp0[0], cp0[1],
                    cp1[0], cp1[1],
                    p[0], p[1]
                );
                // cp0 of next segment
                scaleAndAdd(cp0, p, v, smooth * ratioNextSeg);
            }
            else {
                ctx.lineTo(p[0], p[1]);
            }
        }

        prevIdx = idx;
        idx += dir;
    }

    return k;
}
994858
def polyline(document, coords):
	""
	points = []
	for i in range(0, len(coords), 2):
		points.append("%s,%s" % (coords[i], coords[i+1]))
	
	return setattribs(
		document.createElement('polyline'),
		points = ' '.join(points),
	)
404241
def _setup_xy(self, p):
        
        self.debug("bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, orientation=%s",p.bounds, p.xdensity, p.ydensity, p.x, p.y, p.orientation)

        x_points,y_points = SheetCoordinateSystem(p.bounds, p.xdensity, p.ydensity).sheetcoordinates_of_matrixidx()

        self.pattern_x, self.pattern_y = self._create_and_rotate_coordinate_arrays(x_points-p.x, y_points-p.y, p)
1323428
def separate(polylines, f_mx_dist=2, mn_group_len=4):
    
    s = []

    for n in range(len(polylines) - 1, -1, -1):
        c = polylines[n]
        separated = False
        start = 0

        for m in range(mn_group_len, len(c) - 1):
            if m - start < mn_group_len:
                continue
            m += 1
            group = c[m - mn_group_len:m]

            x, y = group[:, 0], group[:, 1]
            asc, offs, _, _, _ = linregress(x, y)
            yfit = asc * x + offs

            # check whether next point would fit in:
            p1 = c[m]
            l = (x[0], yfit[0], p1[-1], asc * p1[-1] + offs)
            std = np.mean([line.distance(l, g) for g in group])
            dist = line.distance(l, p1)

            if dist > 2 and dist > f_mx_dist * std:
                separated = True
                s.append(c[start:m - 1])
                start = m - 1

        if separated:
            if len(c) - start >= 2:
                s.append(c[start:])
            polylines.pop(n)

    polylines.extend(s)

    return polylines
421707
def union(rasters):
    
    if sum([rasters[0].x_cell_size == i.x_cell_size for i in rasters]) == len(rasters) \
       and sum([rasters[0].y_cell_size == i.y_cell_size for i in rasters]) == len(rasters)\
       and sum([rasters[0].projection.ExportToProj4() == i.projection.ExportToProj4() for i in rasters]) == len(rasters):
        if sum([rasters[0].nodata_value == i.nodata_value for i in rasters]) == len(rasters):
            ndv = rasters[0].nodata_value
        else:
            ndv = np.nan
        if ndv == None:
            ndv = np.nan
        if sum([rasters[0].datatype == i.datatype for i in rasters]) == len(rasters):
            datatype = rasters[0].datatype
        else:
            datatype = None
        projection = rasters[0].projection
        lonmin = min([i.xmin for i in rasters])
        lonmax = max([i.xmax for i in rasters])
        latmin = min([i.ymin for i in rasters])
        latmax = max([i.ymax for i in rasters])
        shape = (np.abs(np.floor((latmax-latmin)/rasters[0].y_cell_size)).astype(int), np.floor((lonmax-lonmin)/rasters[0].x_cell_size).astype(int))
        out = ndv*np.ones(shape)
        outmask = np.ones(shape).astype(bool)
        for i in rasters:
            (row, col) = map_pixel(i.xmin, i.ymax, rasters[0].x_cell_size, rasters[0].y_cell_size, lonmin, latmax)
            out[row:row+i.shape[0], col:col+i.shape[1]] = np.where(i.raster.data != i.nodata_value, i.raster.data,\
                                                         out[row:row+i.shape[0], col:col+i.shape[1]])
            outmask[row:row+i.shape[0], col:col+i.shape[1]] = np.where(i.raster.mask == False, False,\
                                                         outmask[row:row+i.shape[0], col:col+i.shape[1]])
        out = np.ma.masked_array(out, mask=outmask, fill_value=ndv)
        return GeoRaster(out, (lonmin, rasters[0].x_cell_size, 0.0, latmax, 0.0, rasters[0].y_cell_size), nodata_value=ndv, projection=projection, datatype=datatype)
    else:
        raise RasterGeoError('Rasters need to have same pixel sizes. Use the aggregate or dissolve functions to generate correct GeoRasters')
211456
def merge(polylines, mx_dist=4):
    
    l = len(polylines)
    to_remove = set()
    for n in range(l - 1, -1, -1):
        if n not in to_remove:
            c = polylines[n]
            for p0, p1 in zip(c[:-1], c[1:]):
                # create a line from any subsegment:
                l0 = p0[0], p0[1], p1[0], p1[1]

                # for every other polyline:
                for m in range(l - 1, -1, -1):
                    if m not in to_remove:
                        if n == m:
                            continue
                        remove = False
                        cc = polylines[m]
                        ind = np.zeros(shape=cc.shape[0], dtype=bool)

                        # for every point p in this polyline:
                        for o in range(len(cc) - 1, -1, -1):
                            p = cc[o]

                            if line.segmentDistance(l0, p) < mx_dist:
                                remove = True
                                ind[o] = True

                        if remove:
                            polylines[n] = np.append(c, cc[ind], axis=0)
                            ind = ~ind
                            s = ind.sum()
                            if s < 2:
                                to_remove.add(m)
                            else:
                                polylines[m] = cc[ind]

    to_remove = sorted(to_remove)
    to_remove.reverse()
    for i in to_remove:
        polylines.pop(i)
732403
public static <CL extends ClassUml>
      Point2D[] evalTwoLinesForAngle(SettingsGraphicUml gp, ClassRelationFull<CL> relClrel) {
    Point2D pointEnd2 = null;
    if(relClrel.getRelationship().getSharedJoint() == null) {//from this to across relClrel
      RectangleRelationship<ClassFull<CL>, CL> nextRelationClass = relClrel.getRelationship().getShapeRelationshipStart() == relClrel.getClassRelationship() ?
          relClrel.getRelationship().getShapeRelationshipEnd() : 
            relClrel.getRelationship().getShapeRelationshipStart();
      pointEnd2 = nextRelationClass.getPointJoint();      
    }
    else {//from this to interJoint
      pointEnd2 = new Point2D(relClrel.getRelationship().getSharedJoint().getX(), 
          relClrel.getRelationship().getSharedJoint().getY());
    }
    Point2D pointEnd1 = new Point2D(relClrel.getClassRelationship().getPointJoint().getX(), relClrel.getClassRelationship().getPointJoint().getY());
    if(relClrel.getClassRelationship().getSideJoint() == EJointSide.BOTTOM || relClrel.getClassRelationship().getSideJoint() == EJointSide.TOP) {
      pointEnd1.setX(pointEnd2.getX());
    }
    else {
      pointEnd1.setY(pointEnd2.getY());
    }
    return new Point2D[]{relClrel.getClassRelationship().getPointJoint(), pointEnd1, pointEnd2};
  }
187445
function align(point, grid, precision) {

        return round(snapToGrid(point.clone(), grid), precision);
    }
926130
def build_pos_grid(start, end, nstep, mesh=False):
    
    # Build X and Y arrays
    dx = end[0] - start[0]
    if dx < 0:
        nstart = end
        end = start
        start = nstart
    dx = -dx
    stepx = dx / nstep
    # Perform linear fit to find exact line that connects start and end
    xarr = np.arange(start[0], end[0] + stepx / 2.0, stepx)
    yarr = np.interp(xarr, [start[0], end[0]], [start[1], end[1]])

    # create grid of positions
    if mesh:
        xa, ya = np.meshgrid(xarr, yarr)
        xarr = xa.ravel()
        yarr = ya.ravel()

    return xarr, yarr
903306
function(p) {

            if (!p) return false;

            var points = this.points;
            var otherPoints = p.points;

            var numPoints = points.length;
            if (otherPoints.length !== numPoints) return false; // if the two polylines have different number of points, they cannot be equal

            for (var i = 0; i < numPoints; i++) {

                var point = points[i];
                var otherPoint = p.points[i];

                // as soon as an inequality is found in points, return false
                if (!point.equals(otherPoint)) return false;
            }

            // if no inequality found in points, return true
            return true;
        }
794650
def _union_in_blocks(contours, block_size):
    

    n_contours = len(contours)
    for i in range(0, n_contours, block_size):
        j = min(i + block_size, n_contours)

        inners = []
        for c in contours[i:j]:
            p = _contour_to_poly(c)
            if p.type == 'Polygon':
                inners.append(p)
            elif p.type == 'MultiPolygon':
                inners.extend(p.geoms)
        holes = unary_union(inners)
        assert holes.is_valid

        yield holes
344482
def polyline2pathd(polyline_d, is_polygon=False):
    """"""
    points = COORD_PAIR_TMPLT.findall(polyline_d)
    closed = (float(points[0][0]) == float(points[-1][0]) and
              float(points[0][1]) == float(points[-1][1]))

    # The `parse_path` call ignores redundant 'z' (closure) commands
    # e.g. `parse_path('M0 0L100 100Z') == parse_path('M0 0L100 100L0 0Z')`
    # This check ensures that an n-point polygon is converted to an n-Line path.
    if is_polygon and closed:
        points.append(points[0])

    d = 'M' + 'L'.join('{0} {1}'.format(x,y) for x,y in points)
    if is_polygon or closed:
        d += 'z'
    return d
1071897
private static boolean polylineDisjointPolyline_(Polyline polyline_a,
			Polyline polyline_b, double tolerance,
			ProgressTracker progress_tracker) {
		// Quick rasterize test to see whether the the geometries are disjoint.
		if (tryRasterizedContainsOrDisjoint_(polyline_a, polyline_b, tolerance,
				false) == Relation.disjoint)
			return true;

        MultiPathImpl multi_path_impl_a = (MultiPathImpl)polyline_a._getImpl();
        MultiPathImpl multi_path_impl_b = (MultiPathImpl)polyline_b._getImpl();

        PairwiseIntersectorImpl intersector_paths = new PairwiseIntersectorImpl(multi_path_impl_a, multi_path_impl_b, tolerance, true);

        if (!intersector_paths.next())
            return false;

		return !linearPathIntersectsLinearPath_(polyline_a, polyline_b,
				tolerance);
	}
1284992
function connectedComponents_dense(cells, vertex_count) {
  var labels = new UnionFind(vertex_count)
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      for(var k=j+1; k<c.length; ++k) {
        labels.link(c[j], c[k])
      }
    }
  }
  var components = []
    , component_labels = labels.ranks
  for(var i=0; i<component_labels.length; ++i) {
    component_labels[i] = -1
  }
  for(var i=0; i<cells.length; ++i) {
    var l = labels.find(cells[i][0])
    if(component_labels[l] < 0) {
      component_labels[l] = components.length
      components.push([cells[i].slice(0)])
    } else {
      components[component_labels[l]].push(cells[i].slice(0))
    }
  }
  return components
}
593349
function leftAlign(lines) {
    if (lines.length == 0) return lines;
    var distance = lines[0].match(/^\s*/)[0].length;
    var result = [];
    lines.forEach(function(line){
        result.push(line.slice(Math.min(distance, line.match(/^\s*/)[0].length)));
    });
    return result;
}
900996
def _walk_polyline(tid, intersect, T, mesh, plane, dist_tol):
    
    T = set(T)
    p = []
    # Loop until we have explored all the triangles for the current
    # polyline
    while True:
        p.append(intersect[1])

        tid, intersections, T = get_next_triangle(mesh, T, plane,
                                                  intersect, dist_tol)
        if tid is None:
            break

        # get_next_triangle returns triangles that our plane actually
        # intersects (as opposed to touching only a single vertex),
        # hence the assert
        assert len(intersections) == 2

        # Of the two returned intersections, one should have the
        # intersection point equal to p[-1]
        if la.norm(intersections[0][1] - p[-1]) < dist_tol:
            intersect = intersections[1]
        else:
            assert la.norm(intersections[1][1] - p[-1]) < dist_tol, \
                '%s not close to %s' % (str(p[-1]), str(intersections))
            intersect = intersections[0]

    return p, T