Use ring to restore M values on geoms
173069
private Collection<Geometry> restoreDim4(Collection<Geometry> geoms, Map<Coordinate, Double> map) {
        GeometryFactory factory = new GeometryFactory(
                new PackedCoordinateSequenceFactory(PackedCoordinateSequenceFactory.DOUBLE, 4));
        Collection<Geometry> result = new ArrayList<>();
        for (Geometry geom : geoms) {
            if (geom instanceof Point) {
                result.add(factory.createPoint(restoreDim4(
                        ((Point) geom).getCoordinateSequence(), map)));
            } else if (geom instanceof LineString) {
                result.add(factory.createLineString(restoreDim4(
                        ((LineString) geom).getCoordinateSequence(), map)));
            } else if (geom instanceof Polygon) {
                LinearRing outer = factory.createLinearRing(restoreDim4(
                        ((Polygon) geom).getExteriorRing().getCoordinateSequence(), map));
                LinearRing[] inner = new LinearRing[((Polygon) geom).getNumInteriorRing()];
                for (int i = 0; i < ((Polygon) geom).getNumInteriorRing(); i++) {
                    inner[i] = factory.createLinearRing(restoreDim4(
                            ((Polygon) geom).getInteriorRingN(i).getCoordinateSequence(), map));
                }
                result.add(factory.createPolygon(outer, inner));
            } else {
                for (int i = 0; i < geom.getNumGeometries(); i++) {
                    result.addAll(restoreDim4(Collections.singleton(geom.getGeometryN(i)), map));
                }
            }
        }
        return result;
    }
1366520
def _geom_points(geom):
    
    if geom['type'] == 'Point':
        yield tuple(geom['coordinates'])
    elif geom['type'] in ('MultiPoint', 'LineString'):
        for position in geom['coordinates']:
            yield tuple(position)
    else:
        raise InvalidFeatureError(
            "Unsupported geometry type:{0}".format(geom['type']))
837549
def restore_geometry_state(self, gs):
        
        if not gs:
            return
        if gs.get('geometry', None):
            self.restoreGeometry((gs['geometry']))
        if gs.get('state', None):
            self.restoreState((gs['state']))
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)
1096210
def geom(self):
        """"""
        adj_nodes = self._grid._graph.nodes_from_line(self)

        return LineString([adj_nodes[0].geom, adj_nodes[1].geom])
1151520
def fit_geometry(self, X=None, input_type='data'):
        """"""
        if self.geom is None:
            self.geom_ = Geometry()
        elif isinstance(self.geom, Geometry):
            self.geom_ = self.geom
        else:
            try:
                kwds = dict(**self.geom)
            except TypeError:
                raise ValueError("geom must be a Geometry instance or "
                                 "a mappable/dictionary")
            self.geom_ = Geometry(**kwds)

        if self.radius is not None:
            self.geom_.set_radius(self.radius, override=False)

        # if self.radius == 'auto':
        #     if X is not None and input_type != 'affinity':
        #         self.geom_.set_radius(self.estimate_radius(X, input_type),
        #                               override=False)
        # else:
        #     self.geom_.set_radius(self.radius,
        #                           override=False)

        if X is not None:
            self.geom_.set_matrix(X, input_type)

        return self
1225322
def dumps(obj, decimals=16):
    
    try:
        geom_type = obj['type']
        exporter = _dumps_registry.get(geom_type)

        if exporter is None:
            _unsupported_geom_type(geom_type)

        # Check for empty cases
        if geom_type == 'GeometryCollection':
            if len(obj['geometries']) == 0:
                return 'GEOMETRYCOLLECTION EMPTY'
        else:
            # Geom has no coordinate values at all, and must be empty.
            if len(list(util.flatten_multi_dim(obj['coordinates']))) == 0:
                return '%s EMPTY' % geom_type.upper()
    except KeyError:
        raise geomet.InvalidGeoJSONException('Invalid GeoJSON: %s' % obj)

    result = exporter(obj, decimals)
    # Try to get the SRID from `meta.srid`
    meta_srid = obj.get('meta', {}).get('srid')
    # Also try to get it from `crs.properties.name`:
    crs_srid = obj.get('crs', {}).get('properties', {}).get('name')
    if crs_srid is not None:
        # Shave off the EPSG prefix to give us the SRID:
        crs_srid = crs_srid.replace('EPSG', '')

    if (meta_srid is not None and
            crs_srid is not None and
            str(meta_srid) != str(crs_srid)):
        raise ValueError(
            'Ambiguous CRS/SRID values: %s and %s' % (meta_srid, crs_srid)
        )
    srid = meta_srid or crs_srid

    # TODO: add tests for CRS input
    if srid is not None:
        # Prepend the SRID
        result = 'SRID=%s;%s' % (srid, result)
    return result
416075
public static Double getMinY(Geometry geom) {
        if (geom != null) {
            return geom.getEnvelopeInternal().getMinY();
        } else {
            return null;
        }
    }
53265
def geom_dup(geom):
    
    g = ogr.CreateGeometryFromWkt(geom.ExportToWkt())
    g.AssignSpatialReference(geom.GetSpatialReference())
    return g
398127
function unflatten(valuesInOneDimension, size) {
  const {height, width} = size;
  const valuesInTwoDimensions = [];
  for (let y = 0; y < height; y++) {
    const start = y * width;
    const end = start + width;
    valuesInTwoDimensions.push(valuesInOneDimension.slice(start, end));
  }
  return valuesInTwoDimensions;
}
45857
def extract_source_geom(dstore, srcidxs):
    
    for i in srcidxs.split(','):
        rec = dstore['source_info'][int(i)]
        geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']]
        yield rec['source_id'], geom
312919
private void setVertex(Geometry geom, GeometryIndex index, Coordinate coordinate)
			throws GeometryIndexNotFoundException {
		if (index.hasChild() && geom.getGeometries() != null && geom.getGeometries().length > index.getValue()) {
			setVertex(geom.getGeometries()[index.getValue()], index.getChild(), coordinate);
		} else if (index.getType() == GeometryIndexType.TYPE_VERTEX && geom.getCoordinates() != null
				&& geom.getCoordinates().length > index.getValue()) {
			if (geom.getGeometryType().equals(Geometry.LINEAR_RING)) {
				// In case of a closed ring, the last vertex is not allowed to be moved:
				if ((geom.getCoordinates().length - 1) > index.getValue()) {
					geom.getCoordinates()[index.getValue()] = coordinate;
					if (index.getValue() == 0) {
						// In case of closed ring, keep last coordinate equal to the first:
						geom.getCoordinates()[geom.getCoordinates().length - 1] = new Coordinate(coordinate);
					}
				} else {
					throw new GeometryIndexNotFoundException("Can't move closing vertex of a LinearRing, "
							+ "move index=0 instead.");
				}
			} else {
				geom.getCoordinates()[index.getValue()] = coordinate;
			}
		} else {
			throw new GeometryIndexNotFoundException("Could not match index with given geometry");
		}
	}
619813
def __geometryToDict(self, geom):
        """"""
        if isinstance(geom, dict):
            return geom
        elif isinstance(geom, Point):
            pt = geom.asDictionary
            return {"geometry": {"x" : pt['x'], "y" : pt['y']}}
        elif isinstance(geom, Polygon):
            poly = geom.asDictionary
            return {
                "geometry" : {
                    "rings" : poly['rings'],
                    'spatialReference' : poly['spatialReference']
                }
            }
        elif isinstance(geom, list):
            return [self.__geometryToDict(g) for g in geom]
580768
def _decode_geom(ewkb):
    
    # it's already a shapely object
    if hasattr(ewkb, 'geom_type'):
        return ewkb

    from shapely import wkb
    from shapely import wkt
    if ewkb:
        try:
            return wkb.loads(ba.unhexlify(ewkb))
        except Exception:
            try:
                return wkb.loads(ba.unhexlify(ewkb), hex=True)
            except Exception:
                try:
                    return wkb.loads(ewkb, hex=True)
                except Exception:
                    try:
                        return wkb.loads(ewkb)
                    except Exception:
                        try:
                            return wkt.loads(ewkb)
                        except Exception:
                            pass
    return None
561567
def geom_transform(geom, t_srs):
    
    s_srs = geom.GetSpatialReference()
    if not s_srs.IsSame(t_srs):
        ct = osr.CoordinateTransformation(s_srs, t_srs)
        geom.Transform(ct)
        geom.AssignSpatialReference(t_srs)
1254542
def _update_3d_datalim(ax, obj):
    ''''''
    min_bounding_box, max_bounding_box = geom.bounding_box(obj)
    xy_bounds = np.vstack((min_bounding_box[:COLS.Z],
                           max_bounding_box[:COLS.Z]))
    ax.xy_dataLim.update_from_data_xy(xy_bounds, ignore=False)

    z_bounds = np.vstack(((min_bounding_box[COLS.Z], min_bounding_box[COLS.Z]),
                          (max_bounding_box[COLS.Z], max_bounding_box[COLS.Z])))
    ax.zz_dataLim.update_from_data_xy(z_bounds, ignore=False)
333224
def path_to_geom_dicts(path, skip_invalid=True):
    
    interface = path.interface.datatype
    if interface == 'geodataframe':
        return [row.to_dict() for _, row in path.data.iterrows()]
    elif interface == 'geom_dictionary':
        return path.data

    geoms = []
    invalid = False
    xdim, ydim = path.kdims
    for i, path in enumerate(path.split(datatype='columns')):
        array = np.column_stack([path.pop(xdim.name), path.pop(ydim.name)])
        splits = np.where(np.isnan(array[:, :2].astype('float')).sum(axis=1))[0]
        arrays = np.split(array, splits+1) if len(splits) else [array]
        subpaths = []
        for j, arr in enumerate(arrays):
            if j != (len(arrays)-1):
                arr = arr[:-1] # Drop nan

            if len(arr) == 0:
                continue
            elif len(arr) == 1:
                if skip_invalid:
                    continue
                g = Point(arr[0])
                invalid = True
            else:
                g = LineString(arr)
            subpaths.append(g)

        if invalid:
            geoms += [dict(path, geometry=sp) for sp in subpaths]
            continue
        elif len(subpaths) == 1:
            geom = subpaths[0]
        elif subpaths:
            geom = MultiLineString(subpaths)
        path['geometry'] = geom
        geoms.append(path)
    return geoms