Select the nearest weatherstation.
185387
def __select_nearest_ws(jsondata, latitude, longitude):
    """"""
    log.debug("__select_nearest_ws: latitude: %s, longitude: %s",
              latitude, longitude)
    dist = 0
    dist2 = 0
    loc_data = None

    try:
        ws_json = jsondata[__ACTUAL]
        ws_json = ws_json[__STATIONMEASUREMENTS]
    except (KeyError, TypeError):
        log.warning("Missing section in Buienradar xmldata (%s)."
                    "Can happen 00:00-01:00 CE(S)T",
                    __STATIONMEASUREMENTS)
        return None

    for wstation in ws_json:
        dist2 = __get_ws_distance(wstation, latitude, longitude)

        if dist2 is not None:
            if ((loc_data is None) or (dist2 < dist)):
                dist = dist2
                loc_data = wstation

    if loc_data is None:
        log.warning("No weatherstation selected; aborting...")
        return None
    else:
        try:
            log.debug("Selected weatherstation: code='%s', "
                      "name='%s', lat='%s', lon='%s'.",
                      loc_data[__STATIONID],
                      loc_data[__STATIONNAME],
                      loc_data[__LAT],
                      loc_data[__LON])
        except KeyError:
            log.debug("Selected weatherstation")
        return loc_data
479480
def nearbys(radius = 20, options = {})
      return nil unless geocoded?
      options.merge!(:exclude => self) unless send(self.class.primary_key).nil?
      self.class.near(self, radius, options)
    end
1314249
def find_nearest_index(arr, value):
    """"""
    arr = np.array(arr)
    index = (abs(arr-value)).argmin()
    return index
890899
def from_location(cls, location, north_angle=0, daylight_saving_period=None):
        """"""
        location = Location.from_location(location)
        return cls(location.latitude, location.longitude,
                   location.time_zone, north_angle, daylight_saving_period)
820827
def get_weather(self, time, max_hour=6):
        """"""
        if self.data is None:
            return {}

        ordered_entries = []
        for time_entry in self.data['product']['time']:
            valid_from = parse_datetime(time_entry['@from'])
            valid_to = parse_datetime(time_entry['@to'])
            if time > valid_to:
                # Has already passed. Never select this.
                continue

            average_dist = (abs((valid_to - time).total_seconds()) +
                            abs((valid_from - time).total_seconds()))

            if average_dist > max_hour * 3600:
                continue

            ordered_entries.append((average_dist, time_entry))

        if not ordered_entries:
            return {}
        ordered_entries.sort(key=lambda item: item[0])
        res = dict()
        res['datetime'] = time
        res['temperature'] = get_data('temperature', ordered_entries)
        res['condition'] = CONDITIONS.get(get_data('symbol', ordered_entries))
        res['pressure'] = get_data('pressure', ordered_entries)
        res['humidity'] = get_data('humidity', ordered_entries)
        res['wind_speed'] = get_data('windSpeed', ordered_entries)
        res['wind_bearing'] = get_data('windDirection', ordered_entries)
        return res
1345773
def pick_port(self):
        """"""
        ports = set(range(self.min_port, self.min_port + self.port_range))
        return port_for.select_random(ports)
107237
public Criteria near(Circle circle) {

		Assert.notNull(circle, "Circle for 'near' must not be 'null'.");
		return near(circle.getCenter(), circle.getRadius());
	}
766717
def distance_to_nearest_place(feature, parent):
    
    _ = feature, parent  # NOQA

    layer = exposure_summary_layer()
    if not layer:
        return None

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

    feature = next(layer.getFeatures())
    return feature[index]
874359
function closest(node, parentSelector) {
  var cursor = node;

  if (!parentSelector || typeof parentSelector !== 'string') {
    throw new Error('Please specify a selector to match against!');
  }

  while (cursor && !matches(cursor, parentSelector)) {
    cursor = cursor.parentNode;
  }

  if (!cursor) {
    return null;
  } else {
    return cursor;
  }
}
1340003
async def forecast(self):
        """"""

        _forecasts = await self.api.forecast(self.station.globalIdLocal)

        return _forecasts
123015
def get_nearest_by_coordinates(
        data: list, latitude_key: str, longitude_key: str,
        target_latitude: float, target_longitude: float) -> Any:
    """"""
    return min(
        data,
        key=lambda p: haversine(
            target_latitude,
            target_longitude,
            float(p[latitude_key]),
            float(p[longitude_key])
        ))
880303
def direction_to_nearest_place(feature, parent):
    
    _ = feature, parent  # NOQA

    layer = exposure_summary_layer()
    if not layer:
        return None

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

    feature = next(layer.getFeatures())
    return feature[index]
1005158
def selection(self, index):
        """"""
        self.update()
        self.isActiveWindow()
        self._parent.delete_btn.setEnabled(True)
404552
def _set_rain_delay(self, zoneid, value):
        """"""
        # current index for rain_delay starts in 0
        zoneid -= 1

        if isinstance(value, int):
            if value > MAX_RAIN_DELAY_DAYS or value < 0:
                return None
            elif value == 0:
                value = 'off'
            elif value == 1:
                value = '1day'
            elif value >= 2:
                value = str(value) + 'days'
        elif isinstance(value, str):
            if value.lower() != 'off':
                return None

        ddata = self.preupdate()
        attr = 'zone{}_rain_delay_select'.format(zoneid)
        ddata[attr] = value
        self.submit_action(ddata)
        return True
781208
public static function getNearestStation($stations, $coordinatesRequest)
    {
        $calculator = new Vincenty();
        $nearestStation = null;
        $nextDist = INF;
        foreach ($stations as $activeStation) {
            if (is_object($activeStation) && $activeStation instanceof DWDStation) {

                $coordinatesStation = new Coordinate($activeStation->getLatitude(), $activeStation->getLongitude());
                $diff = $calculator->getDistance($coordinatesRequest, $coordinatesStation);
                if ($diff < $nextDist) {
                    $nearestStation = $activeStation;
                    $nextDist = $diff;
                }

            } else
                throw new DWDLibException("Stations parameter does contain an object that is no instance of DWDStation");
        }
        return $nearestStation;
    }
1245885
def get_nearest_forecast_site(self, latitude=None,  longitude=None):
        
        if longitude is None:
            print('ERROR: No latitude given.')
            return False

        if latitude is None:
            print('ERROR: No latitude given.')
            return False

        nearest = False
        distance = None
        sites = self.get_forecast_sites()
        # Sometimes there is a TypeError exception here: sites is None
        # So, sometimes self.get_all_sites() has returned None.
        for site in sites:
            new_distance = \
                self._distance_between_coords(
                    float(site.longitude),
                    float(site.latitude),
                    float(longitude),
                    float(latitude))

            if ((distance == None) or (new_distance < distance)):
                distance = new_distance
                nearest = site

        # If the nearest site is more than 30km away, raise an error

        if distance > 30:
            raise APIException("There is no site within 30km.")

        return nearest
933084
def get_live_weather(lat, lon, writer):
    """"""
    requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon)
    req = requests.get(requrl)
    if req.status_code == requests.codes.ok:
        weather = req.json()
        if not weather['currently']:
            click.secho("No live weather currently", fg="red", bold=True)
            return
        writer.live_weather(weather)
    else:
        click.secho("There was problem getting live weather", fg="red", bold=True)