Get the nearest report (with local and state info) to a lat/lon.
181845
async def nearest_by_coordinates(
            self, latitude: float, longitude: float) -> dict:
        """"""
        # Since user data is more granular than state or CDC data, find the
        # user report whose coordinates are closest to the provided
        # coordinates:
        nearest_user_report = get_nearest_by_coordinates(
            await self.user_reports(), 'latitude', 'longitude', latitude,
            longitude)

        try:
            # If the user report corresponds to a known state in
            # flunearyou.org's database, we can safely assume that's the
            # correct state:
            nearest_state = next((
                state for state in await self.state_data()
                if state['place_id'] == nearest_user_report['contained_by']))
        except StopIteration:
            # If a place ID doesn't exist (e.g., ZIP Code 98012 doesn't have a
            # place ID), calculate the nearest state by measuring the distance
            # from the provided latitude/longitude to flunearyou.org's
            # latitude/longitude that defines each state:
            nearest_state = get_nearest_by_coordinates(
                await self.state_data(), 'lat', 'lon', latitude, longitude)

        return {'local': nearest_user_report, 'state': nearest_state}
966799
def closest(self, coords=[], **kwargs):
        
        if kwargs and coords:
            raise ValueError("Specify coordinate using as either a list "
                             "keyword arguments not both")
        if kwargs:
            coords = []
            getter = []
            for k, v in kwargs.items():
                idx = self.get_dimension_index(k)
                if np.isscalar(v):
                    coords.append((0, v) if idx else (v, 0))
                else:
                    if isinstance(v, list):
                        coords = [(0, c) if idx else (c, 0) for c in v]
                    if len(coords) not in [0, len(v)]:
                        raise ValueError("Length of samples must match")
                    elif len(coords):
                        coords = [(t[abs(idx-1)], c) if idx else (c, t[abs(idx-1)])
                                  for c, t in zip(v, coords)]
                getter.append(idx)
        else:
            getter = [0, 1]
        getter = itemgetter(*sorted(getter))
        if len(coords) == 1:
            coords = coords[0]
        if isinstance(coords, tuple):
            return getter(self.closest_cell_center(*coords))
        else:
            return [getter(self.closest_cell_center(*el)) for el in coords]
607014
def getAltitudeFromLatLon(self, lat, lon):
        
        # print "-----\nFromLatLon", lon, lat
        lat -= self.lat
        lon -= self.lon
        # print "lon, lat", lon, lat
        if lat < 0.0 or lat >= 1.0 or lon < 0.0 or lon >= 1.0:
            raise WrongTileError(self.lat, self.lon, self.lat+lat, self.lon+lon)
        x = lon * (self.size - 1)
        y = lat * (self.size - 1)
        # print "x,y", x, y
        x_int = int(x)
        x_frac = x - int(x)
        y_int = int(y)
        y_frac = y - int(y)
        # print "frac", x_int, x_frac, y_int, y_frac
        value00 = self.getPixelValue(x_int, y_int)
        value10 = self.getPixelValue(x_int+1, y_int)
        value01 = self.getPixelValue(x_int, y_int+1)
        value11 = self.getPixelValue(x_int+1, y_int+1)
        value1 = self._avg(value00, value10, x_frac)
        value2 = self._avg(value01, value11, x_frac)
        value  = self._avg(value1,  value2, y_frac)
        # print "%4d %4d | %4d\n%4d %4d | %4d\n-------------\n%4d" % (
        #        value00, value10, value1, value01, value11, value2, value)
        return value
112290
async def get(cls, websession, lat, lon):
        """"""

        self = Station(websession)
        
        stations = await self.api.stations()

        self.station = self._filter_closest(lat, lon, stations)

        logger.info("Using %s as weather station", self.station.local)

        return self
1189804
def _find_neighbors(self, inst, avg_dist):
        
        NN_near = []
        NN_far = []
        min_indices = []
        max_indices = []

        for i in range(self._datalen):
            if inst != i:
                locator = [inst, i]
                if i > inst:
                    locator.reverse()
                d = self._distance_array[locator[0]][locator[1]]
                if d < avg_dist:
                    min_indices.append(i)
                if d > avg_dist:
                    max_indices.append(i)

        for i in range(len(min_indices)):
            NN_near.append(min_indices[i])
        for i in range(len(max_indices)):
            NN_far.append(max_indices[i])

        return np.array(NN_near, dtype=np.int32), np.array(NN_far, dtype=np.int32)
157828
function(lat, lon, done){

    var url = "http://api.met.no/weatherapi/locationforecast/1.8/?lat=" + lat + ";lon=" + lon;

    request(url, function(error, response, body) {

      if (!error && response.statusCode < 400) {

        var $ = cheerio.load(body);
        var nearbyForecasts = closestInstantForecasts($, $("product time"), FORECASTS_COUNT);

        done(nearbyForecasts.map(createForecastItem));

      } else {
        console.error("error requesting met.no forecast");
        done();
      }
    });
  }
837934
def get_closest_box(self, pos):
        """"""
        pos = np.atleast_2d(pos)
        d = np.sum((np.array(self.box_pos) - pos) ** 2, axis=1)
        idx = np.argmin(d)
        return idx
1083367
def get_closest(cls, *locale_codes: str) -> "Locale":
        """"""
        for code in locale_codes:
            if not code:
                continue
            code = code.replace("-", "_")
            parts = code.split("_")
            if len(parts) > 2:
                continue
            elif len(parts) == 2:
                code = parts[0].lower() + "_" + parts[1].upper()
            if code in _supported_locales:
                return cls.get(code)
            if parts[0].lower() in _supported_locales:
                return cls.get(parts[0].lower())
        return cls.get(_default_locale)
1037823
def nearest_loc_obs(self, lat, lon):
        
        sitelist = self.loc_observations(SITELIST)
        sites = parse_sitelist(sitelist)
        site = get_nearest_site(sites, lat, lon)
        return self.loc_observations(site)
588485
def closest_waypoint(self, latlon):
        ''''''
        (lat, lon) = latlon
        best_distance = -1
        closest = -1
        for i in range(self.module('wp').wploader.count()):
            w = self.module('wp').wploader.wp(i)
            distance = mp_util.gps_distance(lat, lon, w.x, w.y)
            if best_distance == -1 or distance < best_distance:
                best_distance = distance
                closest = i
        if best_distance < 20:
            return closest
        else:
            return -1
752077
def get_lat_lon(self, exif_data):
        """"""
        lat = None
        lon = None

        if "GPSInfo" in exif_data:
            gps_info = exif_data["GPSInfo"]

            gps_latitude = self._get_if_exist(gps_info, "GPSLatitude")
            gps_latitude_ref = self._get_if_exist(gps_info, 'GPSLatitudeRef')
            gps_longitude = self._get_if_exist(gps_info, 'GPSLongitude')
            gps_longitude_ref = self._get_if_exist(gps_info, 'GPSLongitudeRef')

            if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
                lat = self._convert_to_degress(gps_latitude)
                if gps_latitude_ref != "N":
                    lat = 0 - lat

                lon = self._convert_to_degress(gps_longitude)
                if gps_longitude_ref != "E":
                    lon = 0 - lon

        return lat, lon
1156939
def get_dataset(self, key, info):
        """"""
        if key.name in ['longitude', 'latitude']:
            logger.debug('Reading coordinate arrays.')

            if self.lons is None or self.lats is None:
                self.lons, self.lats = self.get_lonlats()

            if key.name == 'latitude':
                proj = Dataset(self.lats, id=key, **info)
            else:
                proj = Dataset(self.lons, id=key, **info)

        else:
            data = self.get_sds_variable(key.name)
            proj = Dataset(data, id=key, **info)

        return proj
992801
def geo_filter(d):
    """"""
    page = d["page"]
    if not "revision" in page:
        return None
    title = page["title"]
    if skip_article(title):
        LOG.info("Skipping low-value article %s", title)
        return None
    text = page["revision"]["text"]
    if not utils.is_str_type(text):
        if "#text" in text:
            text = text["#text"]
        else:
            return None
    LOG.debug("--------------------------------------------------------------")
    LOG.debug(title)
    LOG.debug("--------------------------------------------------------------")
    LOG.debug(text)
    c = find_geo_coords(text)
    u = wikip_url(title)
    """
    m = hashlib.md5()
    m.update(u.encode("UTF-8") if hasattr(u, 'encode') else u)
    i = base64.urlsafe_b64encode(m.digest()).replace('=', '')
    """
    return {
        #"id": i,
        "title": title,
        "url": u,
        "coords": c,
        "updated": page["revision"].get("timestamp")
    } if c else None
1121839
async def status_by_coordinates(
            self, latitude: float, longitude: float) -> dict:
        """"""
        return await self.nearest_by_coordinates(latitude, longitude)
300641
def _closest_location(self, location_map, target):
        """"""

        def dist(a, b):
            return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))

        paths = iter(location_map.keys())
        closest = next(paths)
        closest_dist = dist(target, location_map[closest])
        for path in paths:
            cur_dist = dist(target, location_map[path])
            if cur_dist < closest_dist:
                closest = path
                closest_dist = cur_dist
        return closest
540925
def lookupGeoInfo(positions):
    
    list_data=[]
    oldlat=0
    oldlon=0
    d={}
    for pos in positions:
        # Only lookup point if it is above threshold
        diff_lat=abs(float(pos['lat'])-oldlat)
        diff_lon=abs(float(pos['lon'])-oldlon)
        if (diff_lat>POS_THRESHOLD_DEG) or\
           (diff_lon>POS_THRESHOLD_DEG):
            d=lookup_by_latlon(pos['lat'],pos['lon'])
            oldlat=float(pos['lat'])
            oldlon=float(pos['lon'])
        else:
            logger.debug("Skipping %s/%s, close to prev"%(pos['lat'],pos['lon']))

        # Use fresh lookup value or old value
        list_data.append(d)

    logger.info('looked up %d positions'%(len(list_data)))
    return list_data
311415
def name_of_the_nearest_place(feature, parent):
    
    _ = feature, parent  # NOQA

    layer = exposure_summary_layer()
    if not layer:
        return None

    index = layer.fields().lookupField(
        exposure_name_field['field_name'])
    if index < 0:
        return None

    feature = next(layer.getFeatures())
    return feature[index]