Produces matplotlib Path codes for exterior and interior rings
    of a polygon geometry.
186231
def ring_coding(array):
    
    # The codes will be all "LINETO" commands, except for "MOVETO"s at the
    # beginning of each subpath
    n = len(array)
    codes = np.ones(n, dtype=Path.code_type) * Path.LINETO
    codes[0] = Path.MOVETO
    codes[-1] = Path.CLOSEPOLY
    return codes
848700
private static Polygon processPolygon(Polygon p, Geometry triangleLines, GeometryFactory factory) {
        Geometry diffExt = p.getExteriorRing().difference(triangleLines);
        final int nbOfHoles = p.getNumInteriorRing();
        final LinearRing[] holes = new LinearRing[nbOfHoles];
        for (int i = 0; i < nbOfHoles; i++) {
            holes[i] = factory.createLinearRing(lineMerge(p.getInteriorRingN(i).difference(triangleLines), factory).getCoordinates());
        }
        return factory.createPolygon(factory.createLinearRing(lineMerge(diffExt, factory).getCoordinates()), holes);

    }
190512
def _in_polygon(points, polygon):
    """"""
    from matplotlib.path import Path
    points = _as_array(points)
    polygon = _as_array(polygon)
    assert points.ndim == 2
    assert polygon.ndim == 2
    if len(polygon):
        polygon = np.vstack((polygon, polygon[0]))
    path = Path(polygon, closed=True)
    return path.contains_points(points)
1232258
def nodes_geometry(self):
        

        nodes = np.array([
            n for n in self.transforms.nodes()
            if 'geometry' in self.transforms.node[n]
        ])

        return nodes
484922
def draw_polygon_with_info(ax, polygon, off_x=0, off_y=0):
    """"""
    pts = np.array(polygon)[ConvexHull(polygon).vertices]
    for i, pt in enumerate(pts):
        ax.plot([pt[0], pts[(i + 1) % len(pts)][0]],
                [pt[1], pts[(i + 1) % len(pts)][1]], 'k-')

    avex, avey = np.mean(pts, axis=0)
    ax.annotate('area: {:.3f}'.format(geometry.area(pts)), xy=(avex + off_x, avey + off_y),
                fontsize=12)
275253
def _drop_degenerate_inners(shape):
    

    assert shape.geom_type == 'Polygon'

    new_inners = []
    for inner in shape.interiors:
        # need to make a polygon of the linearring to get the _filled_ area of
        # the closed ring.
        if abs(Polygon(inner).area) >= 0.5:
            new_inners.append(inner)

    return Polygon(shape.exterior, new_inners)
23500
private Polygon createPolygon(double[][][] coordinates, CrsId crsId) {
        LinearRing[] rings = new LinearRing[coordinates.length];
        for (int i = 0; i < coordinates.length; i++) {
            rings[i] = new LinearRing(createPointSequence(coordinates[i], crsId));
        }
        return new Polygon(rings);
    }
671118
def polygon_generator(data, scale, style, permutation=None):
    """"""

    # We'll project the coordinates inside this function to prevent
    # passing around permutation more than necessary
    project = functools.partial(project_point, permutation=permutation)

    if isinstance(data, dict):
        data_gen = data.items()
    else:
        # Only works with style == 'h'
        data_gen = data

    for key, value in data_gen:
        if value is None:
            continue
        i = key[0]
        j = key[1]
        k = scale - i - j
        if style == 'h':
            vertices = hexagon_coordinates(i, j, k)
            yield (map(project, vertices), value)
        elif style == 'd':
            # Upright triangles
            if (i <= scale) and (j <= scale) and (k >= 0):
                vertices = triangle_coordinates(i, j, k)
                yield (map(project, vertices), value)
            # Upside-down triangles
            if (i < scale) and (j < scale) and (k >= 1):
                vertices = alt_triangle_coordinates(i, j, k)
                value = blend_value(data, i, j, k)
                yield (map(project, vertices), value)
        elif style == 't':
            # Upright triangles
            if (i < scale) and (j < scale) and (k > 0):
                vertices = triangle_coordinates(i, j, k)
                value = blend_value(data, i, j, k)
                yield (map(project, vertices), value)
            # If not on the boundary add the upside-down triangle
            if (i < scale) and (j < scale) and (k > 1):
                vertices = alt_triangle_coordinates(i, j, k)
                value = alt_blend_value(data, i, j, k)
                yield (map(project, vertices), value)
480982
def raster_to_shape(raster):
    """"""
    left = raster.bounds.left
    right = raster.bounds.right
    top = raster.bounds.top
    bottom = raster.bounds.bottom

    top_left = (left, top)
    top_right = (right, top)
    bottom_left = (left, bottom)
    bottom_right = (right, bottom)

    return Polygon((
        top_left, top_right, bottom_right, bottom_left, top_left,
    ))
493137
def __geomToStringArray(self, geometries, returnType="str"):
        
        listGeoms = []
        for g in geometries:
            if isinstance(g, Point):
                listGeoms.append(g.asDictionary)
            elif isinstance(g, Polygon):
                listGeoms.append(g.asDictionary) #json.dumps(
            elif isinstance(g, Polyline):
                listGeoms.append({'paths' : g.asDictionary['paths']})
        if returnType == "str":
            return json.dumps(listGeoms)
        elif returnType == "list":
            return listGeoms
        else:
            return json.dumps(listGeoms)
60151
private static float pointToPolygonDist(double x, double y, Polygon polygon) {
        boolean inside = false;
        double minDistSq = Double.POSITIVE_INFINITY;

        // External ring
        LineString exterior = polygon.getExteriorRing();
        for (int i = 0, n = exterior.getNumPoints() - 1, j = n - 1; i < n; j = i, i++) {
            Coordinate a = exterior.getCoordinateN(i);
            Coordinate b = exterior.getCoordinateN(j);

            if (((a.y > y) ^ (b.y > y)) &&
                    (x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x))
                inside = !inside;

            double seqDistSq = getSegDistSq(x, y, a, b);
            minDistSq = Math.min(minDistSq, seqDistSq);
        }
        // Internal rings
        for (int k = 0; k < polygon.getNumInteriorRing(); k++) {
            LineString interior = polygon.getInteriorRingN(k);
            for (int i = 0, n = interior.getNumPoints() - 1, j = n - 1; i < n; j = i, i++) {
                Coordinate a = interior.getCoordinateN(i);
                Coordinate b = interior.getCoordinateN(j);

                if (((a.y > y) ^ (b.y > y)) &&
                        (x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x))
                    inside = !inside;

                minDistSq = Math.min(minDistSq, getSegDistSq(x, y, a, b));
            }
        }

        return (float) ((inside ? 1 : -1) * Math.sqrt(minDistSq));
    }
1163572
def _make_annulus_path(patch_inner, patch_outer):
        

        import matplotlib.path as mpath

        path_inner = patch_inner.get_path()
        transform_inner = patch_inner.get_transform()
        path_inner = transform_inner.transform_path(path_inner)

        path_outer = patch_outer.get_path()
        transform_outer = patch_outer.get_transform()
        path_outer = transform_outer.transform_path(path_outer)

        verts_inner = path_inner.vertices[:-1][::-1]
        verts_inner = np.concatenate((verts_inner, [verts_inner[-1]]))

        verts = np.vstack((path_outer.vertices, verts_inner))
        codes = np.hstack((path_outer.codes, path_inner.codes))

        return mpath.Path(verts, codes)
1255806
function computePathBoundingBox(path) {

            var points = [];
            var iterator = function (c, p0, p1, p2) {
                if (c === 'L') {
                    points.push(p0);
                    points.push(p1);
                }
                else if (c === 'Q') {
                    var bound = computeQuadraticBezierBoundingBox(p0, p1, p2);

                    points.push(bound);
                    points.push({
                        x: bound.x + bound.width,
                        y: bound.y + bound.height
                    });
                }
            };

            if (arguments.length === 1) {
                pathIterator(path, function (c, p0, p1, p2) {
                    if (c === 'L') {
                        points.push(p0);
                        points.push(p1);
                    }
                    else if (c === 'Q') {
                        var bound = computeQuadraticBezierBoundingBox(p0, p1, p2);

                        points.push(bound);
                        points.push({
                            x: bound.x + bound.width,
                            y: bound.y + bound.height
                        });
                    }
                });
            }
            else {
                for (var i = 0, l = arguments.length; i < l; i++) {
                    pathIterator(arguments[i], iterator);
                }
            }

            return computeBoundingBox(points);
        }
25789
function(node) {
            var nodeList = this.getElementsByTagNameNS(node, this.gmlns,
                                                       "LinearRing");
            var components = [];
            if(nodeList.length > 0) {
                // this assumes exterior ring first, inner rings after
                var ring;
                for(var i=0; i<nodeList.length; ++i) {
                    ring = this.parseGeometry.linestring.apply(this,
                                                        [nodeList[i], true]);
                    if(ring) {
                        components.push(ring);
                    }
                }
            }
            return new OpenLayers.Geometry.Polygon(components);
        }
1355553
def get_tile_geometry(path, origin_espg, tolerance=500):
    

    with rasterio.open(path) as src:

        # Get tile geometry
        b = src.bounds
        tile_shape = Polygon([(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3]), (b[0], b[1])])
        tile_geojson = mapping(tile_shape)

        # read first band of the image
        image = src.read(1)

        # create a mask of zero values
        mask = image == 0.

        # generate shapes of the mask
        novalue_shape = shapes(image, mask=mask, transform=src.affine)

        # generate polygons using shapely
        novalue_shape = [Polygon(s['coordinates'][0]) for (s, v) in novalue_shape]

        if novalue_shape:

            # Make sure polygons are united
            # also simplify the resulting polygon
            union = cascaded_union(novalue_shape)

            # generates a geojson
            data_shape = tile_shape.difference(union)

            # If there are multipolygons, select the largest one
            if data_shape.geom_type == 'MultiPolygon':
                areas = {p.area: i for i, p in enumerate(data_shape)}
                largest = max(areas.keys())
                data_shape = data_shape[areas[largest]]

            # if the polygon has interior rings, remove them
            if list(data_shape.interiors):
                data_shape = Polygon(data_shape.exterior.coords)

            data_shape = data_shape.simplify(tolerance, preserve_topology=False)
            data_geojson = mapping(data_shape)

        else:
            data_geojson = tile_geojson

        # convert cooridnates to degrees
        return (to_latlon(tile_geojson, origin_espg), to_latlon(data_geojson, origin_espg))
406405
private Geometry getArealGeometryFromLinearRing(LinearRing ring) {
        if (ring.isSimple()) {
            return ring.getFactory().createMultiPolygon(new Polygon[]{
                ring.getFactory().createPolygon(ring, EMPTY_RING_ARRAY)
            });
        } else {
            // Node input LinearRing and extract unique segments
            Set<LineString> lines = nodeLineString(ring.getCoordinates(), ring.getFactory());
            lines = getSegments(lines);

            // Polygonize the line network
            Polygonizer polygonizer = new Polygonizer();
            polygonizer.add(lines);

            // Computes intersections to determine the status of each polygon
            Collection<Geometry> geoms = new ArrayList();
            for (Object object : polygonizer.getPolygons()) {
                Polygon polygon = (Polygon) object;
                Coordinate p = polygon.getInteriorPoint().getCoordinate();
                int location = RayCrossingCounter.locatePointInRing(p, ring.getCoordinateSequence());
                if (location == Location.INTERIOR) {
                    geoms.add(polygon);
                }
            }
            Geometry unionPoly = UnaryUnionOp.union(geoms);
            Geometry unionLines = UnaryUnionOp.union(lines).difference(unionPoly.getBoundary());
            geoms.clear();
            decompose(unionPoly, geoms);
            decompose(unionLines, geoms);
            return ring.getFactory().buildGeometry(geoms);
        }
    }
517694
function(geometry) {
            var kml = this.createElementNS(this.kmlns, "Polygon");
            var rings = geometry.components;
            var ringMember, ringGeom, type;
            for(var i=0, len=rings.length; i<len; ++i) {
                type = (i==0) ? "outerBoundaryIs" : "innerBoundaryIs";
                ringMember = this.createElementNS(this.kmlns, type);
                ringGeom = this.buildGeometry.linearring.apply(this,
                                                               [rings[i]]);
                ringMember.appendChild(ringGeom);
                kml.appendChild(ringMember);
            }
            return kml;
        }