Helper function to identify MODIS tiles that intersect input geometry

    modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox)

    See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html
558847
def get_modis_tile_list(ds):
    
    from demcoreg import modis_grid
    modis_dict = {}
    for key in modis_grid.modis_dict:
        modis_dict[key] = ogr.CreateGeometryFromWkt(modis_grid.modis_dict[key])
    geom = geolib.ds_geom(ds)
    geom_dup = geolib.geom_dup(geom)
    ct = osr.CoordinateTransformation(geom_dup.GetSpatialReference(), geolib.wgs_srs)
    geom_dup.Transform(ct)
    tile_list = []
    for key, val in list(modis_dict.items()):
        if geom_dup.Intersects(val):
            tile_list.append(key)
    return tile_list
246652
def tiles_from_geom(self, geometry, zoom):
        
        validate_zoom(zoom)
        if geometry.is_empty:
            return
        if not geometry.is_valid:
            raise ValueError("no valid geometry: %s" % geometry.type)
        if geometry.geom_type == "Point":
            yield self.tile_from_xy(geometry.x, geometry.y, zoom)
        elif geometry.geom_type == "MultiPoint":
            for point in geometry:
                yield self.tile_from_xy(point.x, point.y, zoom)
        elif geometry.geom_type in (
            "LineString", "MultiLineString", "Polygon", "MultiPolygon",
            "GeometryCollection"
        ):
            prepared_geometry = prep(clip_geometry_to_srs_bounds(geometry, self))
            for tile in self.tiles_from_bbox(geometry, zoom):
                if prepared_geometry.intersects(tile.bbox()):
                    yield tile
939744
function tileToGeoJSON(tile) {
    var bbox = tileToBBOX(tile);
    var poly = {
        type: 'Polygon',
        coordinates: [[
            [bbox[0], bbox[1]],
            [bbox[0], bbox[3]],
            [bbox[2], bbox[3]],
            [bbox[2], bbox[1]],
            [bbox[0], bbox[1]]
        ]]
    };
    return poly;
}
538547
def tileset_info(self, uid):
        
        url = "http://{host}:{port}/api/v1/tileset_info/?d={uid}".format(
            host=self.host, port=self.port, uid=uid
        )

        req = requests.get(url)
        if req.status_code != 200:
            raise ServerError("Error fetching tileset_info:", req.content)

        content = json.loads(req.content)
        return content[uid]
443379
def get_tile_properties(self, x, y, layer):
        
        try:
            assert (x >= 0 and y >= 0 and layer >= 0)
        except AssertionError:
            raise ValueError

        try:
            gid = self.layers[int(layer)].data[int(y)][int(x)]
        except (IndexError, ValueError):
            msg = "Coords: ({0},{1}) in layer {2} is invalid."
            logger.debug(msg.format(x, y, layer))
            raise Exception

        else:
            try:
                return self.tile_properties[gid]
            except (IndexError, ValueError):
                msg = "Coords: ({0},{1}) in layer {2} has invalid GID: {3}"
                logger.debug(msg.format(x, y, layer, gid))
                raise Exception
            except KeyError:
                return None
298233
public TileSet getTileSetByGID(int gid) {
		for (int i = 0; i < tileSets.size(); i++) {
			TileSet set = (TileSet) tileSets.get(i);

			if (set.contains(gid)) {
				return set;
			}
		}

		return null;
	}
545784
def grid_items(self):
        
        if list(self.keys()) == []:  return {}
        cols = self._max_cols
        return {(idx // cols, idx % cols): (key, item)
                for idx, (key, item) in enumerate(self.data.items())}
72645
public static List<WayDataBlock> toWayDataBlockList(Geometry geometry) {
        List<WayDataBlock> res = new ArrayList<>();
        if (geometry instanceof MultiPolygon) {
            MultiPolygon mp = (MultiPolygon) geometry;
            for (int i = 0; i < mp.getNumGeometries(); i++) {
                Polygon p = (Polygon) mp.getGeometryN(i);
                List<Integer> outer = toCoordinateList(p.getExteriorRing());
                if (outer.size() / 2 > 0) {
                    List<List<Integer>> inner = new ArrayList<>();
                    for (int j = 0; j < p.getNumInteriorRing(); j++) {
                        List<Integer> innr = toCoordinateList(p.getInteriorRingN(j));
                        if (innr.size() / 2 > 0) {
                            inner.add(innr);
                        }
                    }
                    res.add(new WayDataBlock(outer, inner));
                }
            }
        } else if (geometry instanceof Polygon) {
            Polygon p = (Polygon) geometry;
            List<Integer> outer = toCoordinateList(p.getExteriorRing());
            if (outer.size() / 2 > 0) {
                List<List<Integer>> inner = new ArrayList<>();
                for (int i = 0; i < p.getNumInteriorRing(); i++) {
                    List<Integer> innr = toCoordinateList(p.getInteriorRingN(i));
                    if (innr.size() / 2 > 0) {
                        inner.add(innr);
                    }
                }
                res.add(new WayDataBlock(outer, inner));
            }
        } else if (geometry instanceof MultiLineString) {
            MultiLineString ml = (MultiLineString) geometry;
            for (int i = 0; i < ml.getNumGeometries(); i++) {
                LineString l = (LineString) ml.getGeometryN(i);
                List<Integer> outer = toCoordinateList(l);
                if (outer.size() / 2 > 0) {
                    res.add(new WayDataBlock(outer, null));
                }
            }
        } else if (geometry instanceof LinearRing || geometry instanceof LineString) {
            List<Integer> outer = toCoordinateList(geometry);
            if (outer.size() / 2 > 0) {
                res.add(new WayDataBlock(outer, null));
            }
        } else if (geometry instanceof GeometryCollection) {
            GeometryCollection gc = (GeometryCollection) geometry;
            for (int i = 0; i < gc.getNumGeometries(); i++) {
                List<WayDataBlock> recursiveResult = toWayDataBlockList(gc.getGeometryN(i));
                for (WayDataBlock wayDataBlock : recursiveResult) {
                    List<Integer> outer = wayDataBlock.getOuterWay();
                    if (outer.size() / 2 > 0) {
                        res.add(wayDataBlock);
                    }
                }
            }
        }

        return res;
    }
295298
def grid_tiles(self, bbox, zoomlevel):
        
        tiles = self.tileslist(bbox, [zoomlevel])
        grid = {}
        for (z, x, y) in tiles:
            if not grid.get(y):
                grid[y] = []
            grid[y].append(x)
        sortedgrid = []
        for y in sorted(grid.keys(), reverse=self.tile_scheme == 'tms'):
            sortedgrid.append([(x, y) for x in sorted(grid[y])])
        return sortedgrid
1184877
function(geometry) {
        var intersect = false;
        var i, len;
        if(geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
            intersect = this.containsPoint(geometry);
        } else if(geometry.CLASS_NAME == "OpenLayers.Geometry.LineString" ||
                  geometry.CLASS_NAME == "OpenLayers.Geometry.LinearRing") {
            // check if rings/linestrings intersect
            for(i=0, len=this.components.length; i<len; ++i) {
                intersect = geometry.intersects(this.components[i]);
                if(intersect) {
                    break;
                }
            }
            if(!intersect) {
                // check if this poly contains points of the ring/linestring
                for(i=0, len=geometry.components.length; i<len; ++i) {
                    intersect = this.containsPoint(geometry.components[i]);
                    if(intersect) {
                        break;
                    }
                }
            }
        } else {
            for(i=0, len=geometry.components.length; i<len; ++ i) {
                intersect = this.intersects(geometry.components[i]);
                if(intersect) {
                    break;
                }
            }
        }
        // check case where this poly is wholly contained by another
        if(!intersect && geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon") {
            // exterior ring points will be contained in the other geometry
            var ring = this.components[0];
            for(i=0, len=ring.components.length; i<len; ++i) {
                intersect = geometry.containsPoint(ring.components[i]);
                if(intersect) {
                    break;
                }
            }
        }
        return intersect;
    }
526128
def map_gid(self, tiled_gid):
        
        try:
            return self.gidmap[int(tiled_gid)]
        except KeyError:
            return None
        except TypeError:
            msg = "GIDs must be an integer"
            logger.debug(msg)
            raise TypeError
173150
function(bounds) {
        bounds = this.adjustBounds(bounds);
        var url = "";
        if (!this.tileFullExtent || this.tileFullExtent.intersectsBounds(bounds)) {            

            var center = bounds.getCenterLonLat();            
            var info = this.getTileInfo(center);
            var matrixId = this.matrix.identifier;
            var dimensions = this.dimensions, params;

            if (OpenLayers.Util.isArray(this.url)) {
                url = this.selectUrl([
                    this.version, this.style, this.matrixSet,
                    this.matrix.identifier, info.row, info.col
                ].join(","), this.url);
            } else {
                url = this.url;
            }

            if (this.requestEncoding.toUpperCase() === "REST") {
                params = this.params;
                if (url.indexOf("{") !== -1) {
                    var template = url.replace(/\{/g, "${");
                    var context = {
                        // spec does not make clear if capital S or not
                        style: this.style, Style: this.style,
                        TileMatrixSet: this.matrixSet,
                        TileMatrix: this.matrix.identifier,
                        TileRow: info.row,
                        TileCol: info.col
                    };
                    if (dimensions) {
                        var dimension, i;
                        for (i=dimensions.length-1; i>=0; --i) {
                            dimension = dimensions[i];
                            context[dimension] = params[dimension.toUpperCase()];
                        }
                    }
                    url = OpenLayers.String.format(template, context);
                } else {
                    // include 'version', 'layer' and 'style' in tile resource url
                    var path = this.version + "/" + this.layer + "/" + this.style + "/";

                    // append optional dimension path elements
                    if (dimensions) {
                        for (var i=0; i<dimensions.length; i++) {
                            if (params[dimensions[i]]) {
                                path = path + params[dimensions[i]] + "/";
                            }
                        }
                    }

                    // append other required path elements
                    path = path + this.matrixSet + "/" + this.matrix.identifier + 
                        "/" + info.row + "/" + info.col + "." + this.formatSuffix;

                    if (!url.match(/\/$/)) {
                        url = url + "/";
                    }
                    url = url + path;
                }
            } else if (this.requestEncoding.toUpperCase() === "KVP") {

                // assemble all required parameters
                params = {
                    SERVICE: "WMTS",
                    REQUEST: "GetTile",
                    VERSION: this.version,
                    LAYER: this.layer,
                    STYLE: this.style,
                    TILEMATRIXSET: this.matrixSet,
                    TILEMATRIX: this.matrix.identifier,
                    TILEROW: info.row,
                    TILECOL: info.col,
                    FORMAT: this.format
                };
                url = OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(this, [params]);

            }
        }
        return url;    
    }
782404
def get_surface_boundaries(self):
        
        min_lon, min_lat, max_lon, max_lat = self.get_bounding_box()
        return [[min_lon, max_lon]], [[min_lat, max_lat]]
881701
def extract_geometry(dataset):
        
        alg = vtk.vtkGeometryFilter()
        alg.SetInputDataObject(dataset)
        alg.Update()
        return _get_output(alg)
494947
def gridOn(self):  # noqa: N802
        """"""
        return (self._gridOn and (self._has_default_loc()
                or transforms.interval_contains(self.get_view_interval(), self.get_loc())))
117672
function getTileSpans(tileElements) {
      return [].map.call(tileElements, function(ele) {
        var ctrl = angular.element(ele).controller('mdGridTile');
        return {
          row: parseInt(
              $mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-rowspan'), 10) || 1,
          col: parseInt(
              $mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-colspan'), 10) || 1
        };
      });
    }
1065764
function setupGeometry(regionsData, options) {
  options = options || {};
  var regions = regionsData.regions,
    dataset = [],
    postFilter =
      options.postFilter ||
      (regionsData.meta && regionsData.meta.postFilter
        ? new Function("region", regionsData.meta.postFilter)
        : 0),
    scheme = options.scheme || (regionsData.meta && regionsData.meta.scheme),
    disputedBorders =
      (regionsData.meta && regionsData.meta.disputedBorders) || {},
    useSetup = options.recombine || options.lang || "en",
    disputedBorder =
      typeof useSetup == "string" ? disputedBorders[useSetup] : useSetup,
    geometry = 0;

  for (const i in disputedBorders) {
    var setup = disputedBorders[i];
    for (const j in setup) {
      var regionSet = setup[j];
      if (typeof regionSet == "string") {
        setup[j] = new Function("region", regionSet);
      }
    }
  }

  for (const i in regions) {
    if (regions.hasOwnProperty(i)) {
      if (!postFilter || postFilter(wrapRegion(i, regionsData))) {
        if (disputedBorder && disputedBorder[+i]) {
          geometry = recombineRegion(regionsData, {
            filter: disputedBorder[+i]
          });
        } else if (scheme && scheme[+i]) {
          var sch = scheme[+i];
          geometry = recombineRegion(regionsData, {
            filter: typeof sch == "string" ? new Function("region", sch) : sch
          });
        } else {
          geometry = getGeometry(+i, regionsData);
        }

        if (geometry) {
          dataset[regions[i].index] = {
            type: "Feature",
            geometry: geometry,
            properties: {
              osmId: i,
              level: regions[i].level,
              properties: regions[i].property || {},
              parents: regions[i].parents,
              hintContent: regions[i].name,
              name: regions[i].name,
              title: regions[i].name,
              wikipedia: regions[i].wikipedia,
              orderIndex: regions[i].index,
              square: regions[i].square
            }
          };
        }
      }
    }
  }
  var result = [];
  for (var i = 0, l = dataset.length; i < l; ++i) {
    if (dataset[i]) {
      result.push(dataset[i]);
    }
  }
  return result;
}